一つのdivを垂直に中央に配置するいくつかの方法
水平方向の中央には多くの実施形態があり、主に2つのタイプに分類される。定幅高 位置決め+magin 位置決め+transfrom を使用します。 table-cell方式 canc方式 幅が高いかもしれません。幅が高い方法は基本的に定幅が高い場合に適用されます。ここでdivの幅を内容に合わせて展開します。位置付け+transformを使うのも同じです。 です。 flex、grid方法: static方法
と
は、bodyの下にdivを挿入することを例とする。element.style {
position: absolute;
left: 50%;
top: 50%;
margin-left: -250px;
margin-top: -250px;
width: 500px;
height: 500px;
background: yellow;
z-index: 1;
}
を使用してelement.style {
position: absolute;
left: 50%;
top: 50%;
width: 500px;
height: 500px;
background: yellow;
z-index: 1;
transform: translate3d(-50%,-50%,0);
}
div.parent-box {
display: table;
width: 100%;
}
div.parent {
display: table-cell;
height: 200px;
width: 200px;
background-color: orange;
text-align: center;
vertical-align: middle;
}
div.child {
display: inline-block;
width: 100px;
height: 100px;
background-color: blue;
}
<div class="parent-fix">
<div class="parent">
<div class="child">DEMOdiv>
div>
div>
table-cellは設定width:100%がサポートされていません。parentとその容器の幅を一致させたいです。dispaly:tableを設定したほうがいいです。父の入れ物 .parent {
border: 1px solid;
width: 1000px;
height: 1000px;
}
.child {
position: relative;
border: 1px solid;
width: 100px;
height: 100px;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
div.parent {
position: reletive;
}
element.style {
position: absolute;
left: 50%;
top: 50%;
background: yellow;
z-index: 1;
transform: translate3d(-50%,-50%,0);
}
div.parent{
display:flex;
}
div.child{
margin:auto;
}
//
div.parent {
display: flex;
justify-content: center;
align-items: center;
}
またはdiv.parent{
display:flex;
}
div.child{
margin:auto;
}
div.parent {
font-size: 0;
text-align: center;
&::before {
content: "";
display: inline-block;
width: 0;
height: 100%;
vertical-align: middle;
}
}
div.child{
display: inline-block;
vertical-align: middle;
}
この法律は張鑫旭の『CSS世界』から来ています。原理はinline-block
とvertical-align:middle
を設置した後、中の元素は中間の文字準線に基づいて中央に揃えられます。文字の配置はこれらの線によるものです。vertical-align
より多くの情報は張鑫旭博文を見てもいいです。次いで、疑似クラスはposition:static( )
であるので、疑似クラスは親要素の基準線(高さ100%)を開いており、このとき文字の基準線はdiv.parentの中心全体となり、またvertical-align
はinline
またはinline-block
に影響を与えるだけで、div.child設定vertical-align
は中に位置することができる。参考資料:https://muyiy.cn/question/css/52.html