为什么margin-top可以工作?

时间:2016-05-01 11:31:30

标签: html css

        

    div.box{
        width:105px;
        height:200px;
        border:1px solid red;
        }
    div.box1{
        float:left;
        width:50px;
        height:50px;
        border:1px solid red;
        }
    div.box2{
        float:left;
        width:50px;
        height:50px;
        border:1px solid red;
        }
    div.box3{
        width:100px;
        clear:both;
        margin-top:20px;
        height:50px;
        border:1px solid red;
        }
<body>
    <div class="box">
            <div class="box1">box1</div>
            <div class="box2">box2</div>
            <div class="box3">box3</div>
    </div>
 </body>    

Box1和box2都向左浮动,在box3 css中,所有这些都被清除。 现在box1和box2位于box3的顶部,我想在box3上插入边距空间,并在div.box3的css中插入margin-top:20px;
为什么保证金最高可以发挥作用? 我接受了Narxx的回答,有些事实让我取消它作为最佳答案,有很多元素要在真正的网页上浮动,很多网页都长达3000行以上,所以很多浮动的盒子,我们要在使用css代码清除浮动效果时,使用所有浮动框进行包装。

如果有10个地方可以清除浮动,下面的css代码将写入10次并添加10个容器来容纳盒子,这很繁琐,如何简化操作?

        div.container:after{
            clear:both;
            display:block;
            content:"";
            }

也许luboskrnac的方式更好。

2 个答案:

答案 0 :(得分:0)

你清除box3上的浮动,所以从box3,没有浮动,但box3本身受前面的浮动影响。 你应该用一个容器包装浮动元素,并确保在其内容之后有一个明确的。

    div.container:after {
       clear: both;
       display: block;
       content: " ";
    }

    div.box{
        width:105px;
        height:200px;
        border:1px solid red;
        }
    div.box1{
        float:left;
        width:50px;
        height:50px;
        border:1px solid red;
        }
    div.box2{
        float:left;
        width:50px;
        height:50px;
        border:1px solid red;
        }
    div.box3{
        width:100px;
        margin-top:20px;
        height:50px;
        border:1px solid red;
        }
<body>
    <div class="box">
            <div class="container">
                <div class="box1">box1</div>
                <div class="box2">box2</div>
            </div>
            <div class="box3">box3</div>
    </div>
 </body>    

答案 1 :(得分:0)

clear应该在两个浮动元素下的div中使用,但不能在box3中使用。 clear "specifies whether an element can be next to floating elements that precede it or must be moved down (cleared) below them'

您可以添加div clear: both;(向下移动所有内容),以便在浮动元素之后向下移动

css:

.box{
    width:105px;
    height:200px;
    border:1px solid red;
  }

.box1{
  float:left;
  width:50px;
  height:50px;
  border:1px solid red;
}

.box2{
  float:left;
  width:50px;
  height:50px;
  border:1px solid red;
}

.box3{
  width:100px;
  margin-top:20px;
  height:50px;
  border:1px solid red;
}

.clearfix {
  clear: both;
}

HTML

<div class="box">
  <div class="box1">box1</div>
  <div class="box2">box2</div>
  <div class="clearfix"></div>
  <div class="box3">box3</div>
</div>