CSS 实现垂直居中的5种方法
方法1:使用绝对定位和负外边距对块级元素进行垂直居中
优点:兼容不错。缺点:必须提前知道被居中块级元素的尺寸
.father {
width: 300px;
height: 300px;
background-color: red;
position: relative;
margin-bottom: 10px;
}
#child1 {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
background-color: green;
}
<div class="father">
<div id="child1"></div>
</div>
方法2:使用绝对定位和transform
优点:不必提前知道被居中的元素的尺寸
.father {
width: 300px;
height: 300px;
background-color: red;
position: relative;
margin-bottom: 10px;
}
#child2 {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: green;
}
<div class="father">
<div id="child2">内容撑开</div>
</div>
方法3:绝对定位结合margin:auto
.father {
width: 300px;
height: 300px;
background-color: red;
position: relative;
margin-bottom: 10px;
}
#child3 {
position: absolute;
height: 100px;
width: 100px;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
background-color: green;
}
<div class="father">
<div id="child3">内容撑开</div>
</div>
方法4:flex布局
#father1 {
width: 300px;
height: 300px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}
#child4 {
/* width:100px; */
width: calc(50% + 1px);
height: 100px;
background-color: green;
}
<div id="father1">
<div id="child4">123</div>
</div>
方法5:用table实现
#father2 {
width: 300px;
height: 300px;
display: table;
background-color: red;
}
#child5 {
display: table-cell;
text-align: center;
/* 水平居中 */
vertical-align: middle;
/* 垂直居中*/
}
<div id="father2">
<div id="child5">内容</div>
</div>
浙公网安备 33010602011771号