前端学习(77):css中常见margin塌陷问题之解决办法
塌陷問題
?
當(dāng)兩個(gè)盒子在垂直方向上設(shè)置margin值時(shí),會(huì)出現(xiàn)一個(gè)有趣的塌陷現(xiàn)象。
①垂直并列
首先設(shè)置兩個(gè)DIV,并為其制定寬高
1
1 /*HTML部分*/2 <body>3 <div class="box1">box1</div>4 <div class="box2">box2</div>5 </body>6 /*CSS部分*/7 <style> 8 *{9 margin: 0; 10 padding: 0; 11 } 12 .box1{ 13 width: 200px; 14 height: 200px; 15 background: yellowgreen; 16 } 17 .box2{ 18 width: 200px; 19 height: 200px; background: gray; 20 } 21 </style>? ? ? ? ??
? ?
?對(duì)box1我們?yōu)槠湓O(shè)置margin-bottom:50px;
? 對(duì)box2我們?yōu)槠湓O(shè)置margin-top: 40px;
?
1 <style>2 *{3 margin:0;4 padding:0;5 }6 .box1{7 width:200px;8 height:200px;9 background: yellowgreen; 10 margin-bottom: 50px; 11 } 12 .box2{ 13 width:200px; 14 height:200px; 15 background: gray; 16 margin-top: 40px; 17 } 18 </style>?
? ?我們肯定會(huì)很理所當(dāng)然的認(rèn)定這兩個(gè)盒子之間的距離為90px,事實(shí)上并非如此.
?如下圖所示:
? ? ? ? ??
?兩盒子之間的距離僅是50px,也就是說(shuō)兩盒子之間的margin出現(xiàn)了重疊部分,故而我們可以得出:垂直之間塌陷的原則是以兩盒子最大的外邊距為準(zhǔn)。
?
②嵌套關(guān)系(父級(jí)元素塌陷)
2
1 /*CSS部分*/2 <style>3 .box1{4 width:400px;5 height:400px;6 background: pink;7 }8 .box2{9 width:200px; 10 height:200px; 11 background: lightblue; 12 } 13 </style> 14 /*HTML部分*/ 15 <body> 16 <divclass="box1"> 17 <divclass="box2"></div> 18 </div> 19 </body>?如圖示
?
? ? ? ? ?
?當(dāng)為子盒子添加margin-top:10px;時(shí)會(huì)發(fā)生如下情況:
? ? ? ? ??
?子盒子和父盒子之間并沒出現(xiàn)期望的10px間隙而是父盒子與子盒子一起與頁(yè)面頂端產(chǎn)生了10px間隙(即父級(jí)盒子往下塌陷了10px)。
解決方法:
(1)為父盒子設(shè)置border,為外層添加border后父子盒子就不是真正意義上的貼合 ?(可以設(shè)置成透明:border:1px solid transparent)。
(2)為父盒子添加overflow:hidden;
(3)為父盒子設(shè)定padding值;
(4)為父盒子添加position:fixed;
(5)為父盒子添加 display:table;
(6)利用偽元素給子元素的前面添加一個(gè)空元素
.son:before{ content:"";overflow:hidden; } 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的前端学习(77):css中常见margin塌陷问题之解决办法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [python 进阶] 第7章 函数装饰
- 下一篇: 前端学习(5):深入了解网站开发