html - 为什么 margin-top 可以工作?

标签 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 的顶部,我想在 div.box3 的 css 中用 margin-top:20px; 在 box3 上插入边距空间。
为什么margin-top能起作用?
我已经接受了Narxx的答案,一些事实让我取消它作为最佳答案,真实网页中有很多元素要 float ,很多网页长达3000行或更多, float 框太多,我们不得不wrapp all the floated box when to clear the floating effect with the css code.

如果有10个地方要清除 float ,下面的css代码要写10次,加上10个容器来装盒子,很繁琐,如何简化操作?

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

也许 luboskrnac 的方法更好。

最佳答案

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

您可以添加一个 divclear: both;(向下移动所有内容),这样它将在 float 元素之后向下移动所有内容

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>

关于html - 为什么 margin-top 可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36966162/

相关文章:

html - 如何为导航选项卡的事件选项卡设置样式

css - div创建滚动条

html - 消除砖石式 float 布局中的死 Angular

css - 由于已经给出了最小高度,因此盒子不会明智地扩展高度

html - 居中对齐包含在父元素中的旋转元素

html - 伪类和文本装饰问题 :underline in IE6

string - 如何使用 CSS 避免文本重叠?

javascript - 单击 Button 不会向下钻取 Table Bootstrap 4 和 JS 和 JQuery 中的元素

css - 如何使 div 缩放到浏览器宽度的 100%?

javascript - 按提交时表单不执行任何操作