margin-top影响内部和外部元素,但margin-left不影响。为什么?

时间:2014-10-12 04:36:25

标签: html css

如果我将margin-top: 50px;添加到#box,那么#container也会获得margin-top,但如果我将#margin-left: 50px添加到#box那么为什么不是#container #39; t margin-left获得<body> <div id="container"> <div id="box">box</div> </div> </body>

Fiddle

HTML:

#container {
    width: 500px;
    height: 500px;
    background-color: gray;
    margin-top: 30px;
    margin-left: 30px;
}
#box {
    width: 100px;
    height: 100px;
    background-color: orange;
    margin-top: 10px;
}

CSS:

{{1}}

5 个答案:

答案 0 :(得分:1)

您可以将possition:fixed添加到here等容器中,从而实现您想要的效果。

答案 1 :(得分:0)

请为#box float添加:left。使用

更新您的CSS
#box {
    width: 100px;
    height: 100px;
    background-color: orange;
    margin-top: 20px;
    margin-left:25px;
    float : left;

}

希望这会有所帮助

答案 2 :(得分:0)

欢迎来到利润率下降的疯狂世界。

http://www.w3.org/TR/CSS2/box.html#collapsing-margins

  

在CSS中,两个或多个框(可能是也可能不是兄弟)的相邻边距可以组合形成单个边距。据说以这种方式组合的边距会崩溃,因此产生的合并边距称为折叠边距。

您可以在外部div上添加透明边框,使用填充,或者使用外部div上的clearfix浮动内部div。

答案 3 :(得分:0)

这是保证金折叠的工作原理。以下是W3C的详细信息:

http://www.w3.org/TR/CSS2/box.html#collapsing-margins

引自W3C的文章,“水平边距永不崩溃。”

同样来自W3C,有几种方式可以触及崩溃的垂直边距,包括:

  1. 如果“没有行框,没有间隙,没有填充,没有边框分开 他们“
  2. 这两个元素属于相邻的盒子边缘,“盒子的顶部边缘和其第一个流入的顶部边缘 子“
  3. 阻止这种情况的好方法是将30px顶部边距分配给父级,并将10px顶部填充分配给父级。这会将父节点向下移动30px,并将子节点向下移动10px。

    有关详细信息,请参阅此类似问题:Margin on child element moves parent element

    #container {
            width: 500px;
            height: 500px;
            background-color: gray;
            margin-top: 30px;
            margin-left: 30px;
            padding-top:10px;
        }
        #box {
            width: 100px;
            height: 100px;
            background-color: orange;
            margin-top: 0px;
        }
    

答案 4 :(得分:0)

尝试使用#container中的填充而不是#box中的边距,或者像这样使用它们:

#container
{
   padding-top: 1px;
   padding-left: 1px;
}
#box
{
  margin-top: 100px;
  margin-left: 100px;
}

fiddle