1.父display: table;+子display: table-cell;+vertical-align: middle
Code for setting:
.father{
width: 400px;
height: 400px;
background-color: red;
display: table;
}
.son{
background-color: orange;
display: table-cell;
vertical-align: middle;
}
</style>
<body>
<div class="father">
<div class="son">
<span> 1.父元素使用display: table;和子元素 display: table-cell;
来模拟表格,子元素再使用vertical-align: middle即可实现垂直居中。</span>
</div>
</div>
</body>
The effect after setting:
2.父 height+ line-height+子display:inline-block+vertical-align: middle+line-height
<style>
.father{
width: 400px;
height: 400px;
line-height:400px;
background-color: red;
}
.son{
background-color: orange;
display:inline-block;
vertical-align: middle;
line-height:30px;
}
</style>
<body>
<div class="father">
<div class="son">
<span>2.子元素设置display:inline-block;转为行内款元素,模拟单行文本;
父元素设置height和line-height,对子元素设置vertical-align: middle;使其基线对齐。
添加line-height属性的值会覆盖继承父元素的高度。
注意:文本的高度不能超出外部盒子的高度。</span>
</div>
</body>
Renderings:
3. Break away from document flow
Note: the height of height will change according to the height of the text content
<style>
.father{
position:relative;
}
.son{
width:300px;
height:127px;
position:absolute;
top:50%;
margin-top:-63.5px;
background-color: orange;
}
</style>
<body>
<div class="father">
<div class="son">
<span>3.脱离文档流的居中方式,把内部div设置宽高之后,再设置top为50%,
使用负边距调整,将margin-top设置为负的高度的一半就可以垂直居中了。缺点:需要计算出多行文字固定的高度。高度一旦改变,负边距也要调整。
</span>
</div>
</body>
4. Elastic box model: flex+justify-content+align-items:center;
<style>
.content{
width:400px;
height:400px;
background-color:pink;
display:flex;
justify-content:center;
align-items:center;
}
</style>
<body>
<div class="content">
<span>
4.利用弹性模型,首先设置布局方式为盒模型的方式:display:flex;
再利用justify-content和align-items属性设置主轴和交叉轴的对齐方式即可实现多文本的垂直居中。
</span>
</div>
</body>
Renderings:
5. Sub-dispaly: inline-block + relative positioning + translation
<style>
.father{
width: 400px;
height: 400px;
background-color: red;
}
.son{
dispaly:inline-block;
position:relative;
top:50%;
transform: translateY(-50%);
}
<body>
<div class="father">
<div class="son">
<span>5.子元素设置为行内块元素,模拟单行文本,再对子元素设置相对定位,
之后利用top和transform设置平移,来实现垂直居中</span>
</div>
</div>
</body>
Renderings: