启发我一个问题:
如果我把div放在另一个div中,在第二个div中我不能使用属性margin-left
和margin-top
而不改变父div的位置?
我需要使用padding
而不是
例:
带有边缘的条:http://jsfiddle.net/zyEYj/1/
没有边缘的FIDDLE:http://jsfiddle.net/zyEYj/2/
在母亲DIV内部填充的FIDDLE:http://jsfiddle.net/zyEYj/3/(这是我想要的最终效果,但我需要使用填充,并更改#header
的高度)
代码:
<div id="header" class="container">
<div class="logo">
<a href="index.asp"><img src="imagens/logo.png" /></a>
</div>
</div>
的CSS:
body{
background:#d3f1fc;
}
#header{
height:135px;
background:#ee4b14;
padding-top:35px;
padding-left:21px;
}
.container {
margin:0 auto;
width:960px;
}
.logo{
width:382px;
height:114px;
background:#FFCC00;
}
答案 0 :(得分:3)
此行为称为margin collapse
。两个相邻的边距将相互折叠,绝对值越高越好。
这可以通过分隔边距(通过父元素上的padding
或border
),或者通过在子元素上使用position: relative
并通过这种方式调整其位置来解决
<div class="parent">
<div class="child"></div>
</div>
/*
these margins will collapse, and result in a total margin of 15px
*/
.parent
{
margin: 5px;
}
.child
{
margin: 15px;
}
/*
these margins will be separate, resulting in a total margin of 20px
plus the border or padding of 1px
*/
.parent
{
margin: 5px;
padding: 1px; /* or border: 1px; */
}
.child
{
margin: 15px;
}
/*
there is only one margin here, and the child
is positioned relative to where it would usually be rendered
*/
.parent
{
margin: 5px;
}
.child
{
position: relative;
top: 15px;
}
答案 1 :(得分:1)
这是正常的行为。 http://www.w3.org/TR/CSS2/box.html是一个很好的阅读,以便更好地理解。
您必须在父级上使用padding
来移动孩子的顶部。
像这样:http://jsfiddle.net/88ATa/
祝你好运。 纳斯
答案 2 :(得分:0)
解决它的一种方法是将container
div置于绝对位置,以便内部div的限制受到容器边界的限制。
所以juste添加
.container {
position:absolute;
}
会奏效。但由于某种原因,绝对定位可能不是你想要的。例如,它可能会更改您的页面布局。