经常学到一些布局方法,但总是学了就忘,忘了又学。现在把它总结起来,即使后面又忘了,也可以打开来看看。
单列水平垂直居中
我们规定下面的 html 结构为
<div class="parent">
<div class="child"></div>
</div>
1. table-cell+vertical-align;inline-block
<style>
.parent{
display:table-cell;
text-align:center;
vertical-align:middle;
width:200px;height: 200px;
border:1px solid #000;
}
.child{
display: inline-block;
width:100px;height: 100px;
background-color: orange;
}
</style>
2.绝对定位+transform(或者负的外边距)
<div class="wrap">
<div class="box"></div>
</div>
<style>
.parent{
position:relative;
width:200px;height: 200px;
border:1px solid #000;
}
.child{
position: absolute;
left: 50%;top:50%;
transform: translate(-50%,-50%);
width:100px;height: 100px;
background-color: orange;
}
</style>
3.flex
.parent{
display: flex;
justify-content:center;
align-items: center;
width:200px;height: 200px;
border:1px solid #000;
}
.child{
width:100px;height: 100px;
background-color: orange;
}