<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 方法一: 定宽高- 绝对定位+-margin */
.father {
width: 200px;
height: 200px;
background-color: lightcoral;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: lightgreen;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
方法二:子元素绝对定位后, 使用transform 中的translate都为-50%后实现。
/* 2. 绝对定位+transform */
.father {
width: 200px;
height: 200px;
background-color: lightcoral;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: lightgreen;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方法三: 子元素绝对定位后, top, left , right 和bottom都设置为0, margin 为auto
/* 3. 绝对定位+ margin:auto */
.father {
width: 200px;
height: 200px;
background-color: lightcoral;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: lightgreen;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
方法四:flex布局: 父元素加入flex布局后, 使用水平居中和垂直居中。
.father {
width: 200px;
height: 200px;
background-color: lightcoral;
display: flex;
justify-content: center; //水平居中
align-items: center; //垂直居中
}
.son {
width: 100px;
height: 100px;
background-color: lightgreen;
}
方法五:栅格布局 grid
父元素加入栅格, 子元素margin auto
.father {
width: 200px;
height: 200px;
background-color: lightcoral;
display: grid;
}
.son {
width: 100px;
height: 100px;
background-color: lightgreen;
margin: auto;
}
方法六:让元素以表格单元形式出现, 在父元素中,文本水平居中,垂直居中; 子元素margin:auto
/* 6. table-cell */
.father {
width: 200px;
height: 200px;
background-color: lightcoral;
display: table-cell;
/* 文本水平居中 */
text-align: center;
/* 垂直居中 */
vertical-align: middle;
}
.son {
width: 100px;
height: 100px;
background-color: lightgreen;
margin: auto;
}