CSS:当父级没有边框时,页边距
正如您在这张图片中看到的,我有一个橙色的div 位于绿色
div
内,没有顶部边框。橙色 div
的上边距为 30px
,但它也将绿色 div
向下推。当然,添加顶部边框可以解决问题,但我需要绿色 div
为顶部无边框。我能做什么?
.body {
border: 1px solid black;
border-top: none;
border-bottom: none;
width: 120px;
height: 112px;
background-color: lightgreen;
}
.body .container {
background-color: orange;
height: 50px;
width: 50%;
margin-top: 30px;
}
<div class="header">Top</div>
<div class="body">
<div class="container">Box</div>
</div>
<div class="foot">Bottom</div>
As you can see in this picture, I've got an orange div
inside a green div
with no top border. The orange div
has a 30px
top margin, but it's also pushing the green div
down. Of course, adding a top border will fix the issue, but I need the green div
to be top borderless. What could I do?
.body {
border: 1px solid black;
border-top: none;
border-bottom: none;
width: 120px;
height: 112px;
background-color: lightgreen;
}
.body .container {
background-color: orange;
height: 50px;
width: 50%;
margin-top: 30px;
}
<div class="header">Top</div>
<div class="body">
<div class="container">Box</div>
</div>
<div class="foot">Bottom</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以将
overflow:auto
添加到.body
以防止边距折叠。请参阅http://www.w3.org/TR/CSS2/box。 html#collapsing-marginsYou could add
overflow:auto
to.body
to prevent margin-collapsing. See http://www.w3.org/TR/CSS2/box.html#collapsing-margins你所经历的是利润崩溃。边距并不指定元素周围的区域,而是指定元素之间的最小距离。
由于绿色容器没有任何边框或填充,因此没有任何内容可以包含橙色元素的边距。顶部元素和橙色元素之间使用边距,就像绿色容器具有边距一样。
在绿色容器中使用填充,而不是在橙色元素上使用边距。
What you experience is margin collapsing. The margin doesn't specify an area around an element, but rather the minimum distance between elements.
As the green container doesn't have any border or padding, there is nothing to contain the margin of the orange element. The margin is used between the top element and the orange element just as if the green container would have the margin.
Use a padding in the green container instead of a margin on the orange element.
使用
padding
而不是margin
:Use
padding
instead ofmargin
:不确定这是否适用于您的情况,但我刚刚通过以下 CSS 属性解决了这个问题
#element
被下推,因为它的第一个子元素有一个margin-top: 30px.有了这个 CSS,它现在可以按预期工作:) 不确定它是否适用于所有情况,YMMV。
Not sure if this will work in your case, but I just solved this with the following CSS properties
#element
was being pushed down because it's first child element had amargin-top: 30px
. With this CSS, it now works as expected :) Not sure if it'll work for every case, YMMV.您可以在绿色框上添加
padding-top: 30
,在橙色框上使用top: 30px
进行相对定位,或者浮动橙色框并使用相同的 <代码>页边距:30px。You can either add
padding-top: 30
on the green box, use relative positioning on the orange box withtop: 30px
, or float the orange box and use the samemargin-top: 30px
.您阅读了这份文档:
盒子模型 - 边距折叠
CSS
You read this document:
Box model - Margin collapsing
CSS
不知道这听起来有多黑客,但是添加一个透明边框怎么样?
Not sure how hackish this sounds, but how about adding a transparent border?