直奔主题在这里提供三种块级元素垂直水平居中的方法
- flex(子级宽高可固定也可不固定,随意)
- 定位 +margin(固定子级的宽高,margin-top,margin-left 取自身一半的负值)
- 定位 +transform(不固定子级的宽高)
flex
html
<div class="parent">
<div class="child"></div>
</div>
css
.parent{
width: 500px;
height: 500px;
margin: 0 auto;
border: 1px solid gainsboro;
display: flex;
justify-content: center;
align-items: center;
}
.child{
width: 200px;
height: 200px;
background: red;
}
定位 +margin
html
<div class="parent">
<div class="child"></div>
</div>
css
.parent{
position: relative;
width: 500px;
height: 500px;
margin: 0 auto;
border: 1px solid gainsboro;
}
.child{
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
margin-left: -100px;
margin-top: -100px;
background: red;
}
定位 +transform
html
<div class="parent">
<div class="child">
<span> 我是子元素 </span>
</div>
</div>
css
.parent{
position: relative;
width: 500px;
height: 500px;
margin: 0 auto;
border: 1px solid gainsboro;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: red;
}
个人更喜欢 flex
–end–