html盒子居中的方式,CSS盒子居中三种方法
前言
CSS盒子居中,我覺得是很有必要學習一下的。特別是第三種方法,奇淫技巧升級版,也是生產環境中非常常見的一種方法,不需要知道寬度,隨著祖先元素的變化而變化!
1.常規方法
常規方法只需要給盒子設置寬高,利用外邊距讓它居中!
常規方法.box1{width: 200px;
height: 200px;
margin: 0 auto;
background-color: pink;
}
2.奇淫技巧
奇淫技巧利用定位元素。將祖先元素設為相對定位,子級元素設為絕對定位。left設置為50%;margin-left設置為-寬度的一半。但是必須得設置寬度,并且得知道寬度值為多少!
奇淫技巧.bigbox2{position: relative
}
.bigbox2 .box2{
width: 200px;
height: 200px;
background-color: skyblue;
position: absolute;
left: 50%;
margin-left: -100px;
}
3.奇淫技巧升級版
奇淫技巧利用定位元素和CSS transform屬性。將祖先元素設為相對定位,子級元素設為絕對定位。left設置為50%;transform設置為translate(-50%);優點:不需要知道寬度值為多少!
奇淫技巧升級版.bigbox3{position: relative;
}
.bigbox3 .box3{
width: 200px;
height: 200px;
background-color: lightseagreen;
position: absolute;
left: 50%;
transform: translate(-50%);
}
在線代碼
總結
以上是生活随笔為你收集整理的html盒子居中的方式,CSS盒子居中三种方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 串的块链存储c语言栈,小蚂蚁学习数据结构
- 下一篇: 11210怎么等于24_想要消耗100大