構造に変更する必要があります。 <style>
.parent{
display:table-cell;
vertical-align: middle;
}
.child{
display: table;
margin: 0 auto;
}
</style>
<p class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<p class="child" style="background-color: lightblue;">测试文字</p>
</p>
アイデア4:
絶対配置を使用する【1】絶対配置要素のボックスモデル機能を使用し、オフセット属性
に基づくマージンを設定する決められた値: auto<style>
.parent{
position: relative;
}
.child{
position: absolute;
top: 0;
left: 0;
rightright: 0;
bottombottom: 0;
height: 50px;
width: 80px;
margin: auto;
}
</style>
<p class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<p class="child" style="background-color: lightblue;">测试文字</p>
</p>
【2】絶対配置要素のoffset属性とtranslate()
関数の自己オフセットを利用して水平方向と垂直方向のセンタリング効果を実現
[注意] IE9 ブラウザはサポートしていません
<style>
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
<p class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<p class="child" style="background-color: lightblue;">测试文字</p>
</p>
[3] 子要素の幅と高さがわかっている場合、margin の負の値を使用して水平方向と垂直方向のセンタリング効果を実現できます
<style>
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
width: 80px;
height: 60px;
margin-left: -40px;
margin-top: -30px;
}
</style>
<p class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<p class="child" style="background-color: lightblue;">测试文字</p>
</p>
思考5:
flexを使う
【注意】IE9ブラウザはをサポートしていません【1】flexアイテムにはmargin:auto<style>
.parent{
display: flex;
}
.child{
margin: auto;
}
</style>
<p class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<p class="child" style="background-color: lightblue;">测试文字</p>
</p>
を使用します
【2】フレックスコンテナで主軸配置の justify-content と交差軸配置の align-items を使用します
<style>
.parent{
display: flex;
justify-content: center;
align-items: center;
}
</style>
<p class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<p class="child" style="background-color: lightblue;">测试文字</p>
</p>
上記の記事では、水平方向と垂直方向のセンタリングを同時に実現するための CSS の 5 つのアイデアを簡単に分析しています. これは編集者が共有したすべての内容ですので、参考にしていただければ幸いです。また、皆様にも PHP 中国語 Web サイトをサポートしていただければ幸いです。