實(shí)現(xiàn)方法:
1、添加 margin 值 auto
2、定位 position(子絕父相) + 偏移值 left + margin-left 回退 [ 需要計(jì)算,有點(diǎn) 麻煩 ]
3、定位 position(子絕父相) + 偏移值 left + CSS-2d transform
4、文字居中 text-align:center; + 行內(nèi)塊元素
5、彈性盒子布局 [ 推薦 ]
示例
代碼實(shí)現(xiàn):
<div class="box">
<div class="box1"></div>
</div>
.box{
width: 500px;
height: 300px;
background-color: aquamarine;
}
.box1{
width: 200px;
height: 100px;
background-color: lightpink;
}
原始效果圖:
接下來,將使用這個(gè)例子來測試上面提到的幾種實(shí)現(xiàn)水平居中的方法以及記錄解決測試過程中出現(xiàn)的一些小問題…
-
添加margin值(外邊距):
margin:auto;
.box1{ width: 200px; height: 100px; background-color: lightpink; margin: auto; }
效果圖:水平居中成功實(shí)現(xiàn)
拓展注意點(diǎn):???????如果需要小盒子上下也有一定邊距,可以修改margin設(shè)置:
margin:100px auto;
效果圖:
從上面效果圖可以發(fā)現(xiàn):兩個(gè)盒子同時(shí)向下移動
這種情況的出現(xiàn)是由 margin塌陷 導(dǎo)致的
那么,該如何解決這種問題呢?
這里,可以將父元素box變?yōu)锽FC:
overflow: hidden;
[ 注意不是超出隱藏的作用 ]效果圖:
到這里,盒子們都走上了正軌,margin塌陷的問題完美解決 ~
-
定位
position
+ 偏移值 left + margin-left 回退.box{ width: 500px; height: 300px; background-color: aquamarine; position: relative; } .box1{ width: 200px; height: 100px; background-color: lightpink; position: absolute; /* 相對父級寬度50% */ left: 50%; margin-left: -100px; }
注意點(diǎn):
只設(shè)置
left: 50%;
并不能實(shí)現(xiàn)水平居中的效果:
如果想讓小盒子水平居中 ,需要向左移動半個(gè)小盒子的寬度距離:margin-left: -100px;
效果圖:
-
定位
position
+ 偏移值 left + CSS-2d transform.box{ width: 500px; height: 300px; background-color: aquamarine; position: relative; } .box1{ width: 200px; height: 100px; background-color: lightpink; position: absolute; left: 50%; transform: translateX(-50%); }
注意點(diǎn):
left: 50%;
與transform: translateX(-50%);
中的 50% 代表的意義不一樣:left: 50%;
:相對于父元素box的寬度transform: translateX(-50%);
:相對于自己box1的寬度效果圖:
-
文字居中:
text-align:center;
+ 行內(nèi)塊元素.box{ width: 500px; height: 300px; background-color: aquamarine; text-align: center; } .box1{ width: 200px; height: 100px; background-color: lightpink; display: inline-block; }
注意點(diǎn):
如果僅使用
text-align:center;
是無法達(dá)到水平居中的效果的,為什么?text-align:center;
需要在行內(nèi)塊元素上使用的,而盒子是塊級元素,所以,需要將盒子轉(zhuǎn)換為行內(nèi)塊元素text-align:center;
才能生效。效果圖:
-
彈性布局:
display:flex;
[推薦].box{ width: 500px; height: 300px; background-color: aquamarine; display: flex; /*主軸-x軸:居中*/ justify-content: center; } .box1{ width: 200px; height: 100px; background-color: lightpink; }
效果圖:文章來源:http://www.zghlxwxcb.cn/news/detail-437745.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-437745.html
到了這里,關(guān)于CSS實(shí)現(xiàn): 水平居中 的幾種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!