html不用class怎麼居中
第一種:將元素通過display:inline-block轉化為行內塊元素居中,例如:
box{width:500pxheight:500pxbox-shadow:0 0 5px #000text-align:centerfont-size:0}
box {width:120pxheight:100pxbackground:#0f0display:inline-blockvertical-align:middle}
box:after{content:""display:inline-blockheight:100%vertical-align:middle}
第二種:用定位的方式將之移動到位置,例如:
box{width:500pxheight:500pxbox-shadow:0 0 5px #000position:relative}
box {width:120pxheight:100pxbackground:#0f0
position:absoluteleft:0right:0top:0bottom:0margin:auto}
第三種:類似第二中只不過通過百分比調整位置,例如
box{width:500pxheight:500pxbox-shadow:0 0 5px #000position:relative}
box {width:120pxheight:100pxbackground:#0f0position:absoluteleft:50%top:50%margin:-50px 0 0 -60px}
第四種:類似第三種,但是在調整回到中心位置時使用transform:translate( ,)進行調整,例如
box{width:500pxheight:500pxbox-shadow:0 0 5px #000position:relative}
box {width:120pxheight:100pxbackground:#0f0
position:absoluteleft:50%top:50%transform:translate(-50%,-50%)}
第五種:使用彈性盒(display:flex),例如
box{width:500pxheight:500pxbox-shadow:0 0 5px #000display:flexjustify-content:centeralign-items:center}
box {width:120pxheight:100pxbackground:#0f0}
以上最常用的五種方式,除此之外還有很多方式,根據每個人的習慣不同個人用法不同