1.父の表示: テーブル;+子の表示: テーブルセル;+垂直配置: 中央
設定用のコード:
.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>
設定後の効果:
2.父の高さ+行の高さ+子の表示: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>
レンダリング:
3. 書類の流れからの脱却
注: 高さの高さはテキストコンテンツの高さに応じて変わります。
<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. エラスティックボックスモデル: 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>
レンダリング:
5. サブディスプレイ: インラインブロック + 相対位置 + 移動
<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>
レンダリング: