【问题标题】:Why margin property is not working in the "container3" after using "clear" property (css)?为什么使用“clear”属性(css)后margin属性在“container3”中不起作用?
【发布时间】:2020-05-11 10:55:01
【问题描述】:

您在附件中看到的所有 3 个容器都在一个主容器中。我在第一个两个容器中使用了“float:left”,在第三个容器中使用了“clear:both”属性。

但是,似乎在将“clear”属性应用于第三个容器后,ma​​rgin-top 不起作用。

请帮我解决以下问题:

  1. 为什么会这样?
  2. 我该如何解决这个问题?

谢谢!

代码:

    div#insideContainer1
{
      max-width:        500px;
      padding:          20px;
      box-sizing:       border-box;
      border:           1px solid #e0e0e0;
      border-radius:    5px;

      float:            left;
}

div#insideContainer2
{
      max-width:        500px;
      padding:          20px;
      box-sizing:       border-box;
      border:           1px solid #e0e0e0;
      border-radius:    5px;

      margin-left:      20px;
      float:            left;
}

div#insideContainer3
{
      max-width:        500px;
      padding:          20px;
      box-sizing:       border-box;
      border:           1px solid #e0e0e0;
      border-radius:    5px;

      margin-top:       30px;
      clear:            both;
}

CSS Output Screenshot

CSS Code Screenshot

【问题讨论】:

  • 欢迎来到 Stack Overflow!请在您的问题中包含您的代码和重现问题的最简单方法
  • 当然@Joundill。

标签: html css css-float


【解决方案1】:

好吧,
1-当clear: both;一个div时,你清除左右两边的东西,所以div#3 clear什么都不做...
(例如:如果你同时给 div#1 和 div#2 clear: both; 每个 div 将占用它自己的块,它会破坏 float: left;

2- 在这种情况下,要打破浮动,您不需要在任何这些 div 中使用 clear" both;,它会是一个 div 本身 来清除和拆分!

3- 由于 div 具有相同的 CSS 样式,我们应该一次全选(阅读更多:CSS 选择器参考)。

HTML:

<div class="container">
    <div class="div1"></div> 
    <div class="div2"></div>
    <div class="clear-both"></div> 
    <div class="div3"></div>
</div>

CSS:

.div1,
.div2,
.div3{
    width: 500px;
    padding: 20px;
    box-sizing: border-box;
    border: 1px solid #e0e0e0;
    border-radius: 5px;
    background-color: #f40b0b;
    margin: 10px;
}

.div1, .div2 {
    float: left;
}

.div3 {
    background-color: aqua;
}

.clear-both {
    clear: both;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2022-09-23
    • 2019-02-19
    • 2017-02-16
    • 1970-01-01
    相关资源
    最近更新 更多