简单的保证金上限/保证金留下的麻烦

时间:2012-12-19 12:56:38

标签: html css

启发我一个问题:

如果我把div放在另一个div中,在第二个div中我不能使用属性margin-leftmargin-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;
}​

3 个答案:

答案 0 :(得分:3)

此行为称为margin collapse。两个相邻的边距将相互折叠,绝对值越高越好。

这可以通过分隔边距(通过父元素上的paddingborder),或者通过在子元素上使用position: relative并通过这种方式调整其位置来解决

HTML:

<div class="parent">
    <div class="child"></div>
</div>

CSS:

正常

/*
    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;
 }

会奏效。但由于某种原因,绝对定位可能不是你想要的。例如,它可能会更改您的页面布局。

请参阅:http://jsfiddle.net/zyEYj/13/