imgまたはdivをdivで水平垂直に中央に表示する方法
2610 ワード
暇な時に、imgをdivの中で垂直に表示する方法を聞かれ、以下の方法をまとめました.参考にしてください.
方法1:boxにspan空要素を追加する
方法2:位置決め法を使用し、位置決め法を使用する場合、imgは2つの状況を含む.
(1)幅の高さを固定する
(2)固定幅なし
方法4:flexレイアウトの使用
前の2つは开発で使われることが多いですが、最后の1つは移动侧のレイアウトでよく使われています.サブエレメントが1つしかない场合に限り、以上は本人の见解ですが、间违いがあればご指摘ください.
方法1:boxにspan空要素を追加する
#box{
width: 200px;
height: 200px;
background:black;
margin:0 auto;
text-align: center;
}
.img{
width: 100px;
height: 100px;
background:white;
display: inline-block;
vertical-align: middle;
}
#box span{
display: inline-block;
width:0;
height:100%;
vertical-align: middle;
}
方法2:位置決め法を使用し、位置決め法を使用する場合、imgは2つの状況を含む.
(1)幅の高さを固定する
#box{
width: 200px;
height: 200px;
background:black;
margin:0 auto;
text-align: center;
position: relative;
}
.img{
width: 100px;
height: 100px;
position: absolute;
background: white;
left:50%;
top:50%;
margin-top:-50px;
margin-left:-50px;
}
(2)固定幅なし
#box{
width: 200px;
height: 200px;
background:black;
margin:0 auto;
text-align: center;
position: relative;
}
.img{
width: 100px;
height: 100px;
position: absolute;
background: white;
left:50%;
top:50%;
-webkit-transform: translate(-50%,-50%);
-moz-transform:translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
メソッド3:親divをtable-cellプロパティに設定する #box{
width: 200px;
height: 200px;
background:black;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.img{
width: 100px;
height:100px;
background: white;
display: inline-block;
}
方法4:flexレイアウトの使用
#box{
width: 200px;
height: 200px;
background:black;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
margin:0 auto;
}
.img{
width: 100px;
height:100px;
background: white;
}
前の2つは开発で使われることが多いですが、最后の1つは移动侧のレイアウトでよく使われています.サブエレメントが1つしかない场合に限り、以上は本人の见解ですが、间违いがあればご指摘ください.