一:父子元素之間margin垂直方向塌陷問題
在處理margin垂直方向問題時,經常會遇到在給子元素設置margin時,導致效果出現(xiàn)在了父元素上;如下代碼所示:
代碼原義是想實現(xiàn)三方面:
① 將box1的margin-top調為50px,使其與父元素之間形成空隙;
② 將box2的margin-top調為20px,使其與兄弟元素box1之間形成空隙;
③ 將box3的margin-bottom調為20px,使其與父元素之間形成空隙;
<div class="box">
<div class="box1">box1</div>
<div class="box2">box2</div>
<div class="box3">box3</div>
</div>
.box {
width: 400px;
height: 400px;
background-color: antiquewhite;
text-align: center;
}
.box1 {
margin-top: 50px;
width: 100px;
height: 100px;
line-height: 100px;
background-color: rgba(0, 115, 255, 0.39);
}
.box2 {
width: 100px;
height: 100px;
line-height: 100px;
background-color: rgba(0, 255, 51, 0.232);
margin-top: 20px;
}
.box3 {
width: 100px;
height: 100px;
line-height: 100px;
background-color: rgba(255, 196, 0, 0.232);
margin-bottom: 20px;
}
?從上述代碼可以看到,效果出現(xiàn)與預期不同的情況:
① 給第一個子元素box1設置了margin-top值后,并沒有起作用,卻導致了父元素的margin-top存在;
該種情況被稱為父子元素在垂直方向的margin塌陷問題,如何解決此問題?
有三種方法:
① 給父元素設置不為0的padding值
.box {
width: 400px;
height: 400px;
background-color: antiquewhite;
text-align: center;
padding: 2px;
}
?② 給父元素設置寬度不為0的border值
.box {
width: 400px;
height: 400px;
background-color: antiquewhite;
text-align: center;
border-top: 1px solid red;
}
?或
.box {
width: 400px;
height: 400px;
background-color: antiquewhite;
text-align: center;
border: 1px solid red;
}
?
③?給父元素設置CSS樣式overflow: hidden
.box {
width: 400px;
height: 400px;
background-color: antiquewhite;
text-align: center;
overflow: hidden;
}
二:兄弟元素之間margin垂直方向合并問題
在處理兄弟元素問題時,若上面的兄弟元素設置了margin-bottom,下面的兄弟元素設置了margin-top,則最后的margin值會取二者之間的最大值,而不是將二者相加,該種現(xiàn)象稱為margin合并問題;
<div class="box">我是box元素</div>
<div class="bro">我是box的兄弟元素</div>
div {
height: 200px;
line-height: 200px;
width: 200px;
text-align: center;
}
.box {
background-color: aquamarine;
margin-bottom: 40px;
}
.bro {
background-color: rgb(234, 250, 57);
margin-top: 20px;
}
? ? ?
可以看到,在二者之間只有40px的空隙,產生了合并現(xiàn)象。如何解決此問題?
最好的方法是指設置一個,計算好兄弟元素之間的margin,只設置一方即可~
?
如上述代碼只給第一個兄弟元素添加margin-bottom為60px即可,文章來源:http://www.zghlxwxcb.cn/news/detail-495812.html
div {
height: 200px;
line-height: 200px;
width: 200px;
text-align: center;
}
.box {
background-color: aquamarine;
margin-bottom: 60px;
}
.bro {
background-color: rgb(234, 250, 57);
/* margin-top: 20px; */
}
?
?文章來源地址http://www.zghlxwxcb.cn/news/detail-495812.html
到了這里,關于CSS查缺補漏之《如何優(yōu)雅解決margin垂直方向塌陷與合并問題?》的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!