1.水平居中
1.1 text-align:center
父盒子设置text-align:center,如果子盒子不是行内元素,可以先设置display:inline或者display:inline-block转成行内元素。
.father{
text-align:center;
}
.chlidren{
display:inline-block;
background: red;
}
<div class="father">
<div class="chlidren">抹茶冰淇淋居中方法研究</div>
</div>
1.2 margin:0 auto
需要谁居中,给其设置 margin: 0 auto,盒子的宽度也要进行设置
.father{
}
.chlidren{
margin:0 auto;
width:180px;
background: red;
}
<div class="father">
<div class="chlidren">抹茶冰淇淋居中方法研究</div>
</div>
1.3 父盒子相对定位,子盒子绝对定位,对子盒子设置transform:translateX(-50%); left:50%;
.father {
position: relative;
}
.chlidren {
position: absolute;
left: 50%;
transform: translateX(-50%);
background: red;
}
<div class="father">
<div class="chlidren">抹茶冰淇淋居中方法研究</div>
</div>
2.垂直居中
2.1 单行元素垂直居中,设置height和line-height的高度一样
.chlidren {
height:100px;
line-height: 100px;
background:red;
}
2.1 多行元素垂直居中 父盒子设置display:table-cell;vertical-align:middle;
3.水平垂直居中
3.1 flex布局
父盒子设置 display:flex; justify-content:center; align-items:center;
.father {
display: flex;
justify-content: center;
align-items: center;
height: 400px;
}
3.2 父盒子相对定位,子盒子绝对定位,利用transform
.father {
position:relative;
height:400px;
}
.chlidren {
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,50%);
background: red;
}
<div class="father">
<div class="chlidren">抹茶冰淇淋居中方法研究</div>
</div>
3.3 父盒子相对定位,子盒子绝对定位,利用方位值和margin: auto
.father {
position:relative;
height:400px;
}
.chlidren {
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
background: red;
width:100px;
height:100px;
}