CSS查缺补漏:《优雅解决margin垂直方向塌陷和合并问题》
一:父子元素之间margin垂直方向塌陷问题
在处理margin垂直方向问题时,经常会遇到在给子元素设置margin时,导致效果出现在了父元素上;如下代码所示:
代码原义是想实现三方面:
① 将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;
-
}
从上述代码可以看到,效果出现与预期不同的情况:
① 给第一个子元素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值会取二者之间的最大值,而不是将二者相加,该种现象称为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的空隙,产生了合并现象。如何解决此问题?
最好的方法是指设置一个,计算好兄弟元素之间的margin,只设置一方即可~
如上述代码只给第一个兄弟元素添加margin-bottom为60px即可,
-
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; */
-
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhgeihfh
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
怎样阻止微信小程序自动打开
PHP中文网 06-13 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01