关于CSS中的float

时间:2017-08-13 10:03:03

标签: css css-float

我在“浮动”中遇到了一些麻烦。在css。 我有一个宽度为960px的包装div。我想在其中添加5个child-div,宽度为960/5 = 192px。这就是我所拥有的: https://i.stack.imgur.com/R6bsw.png

这是我的代码行。谁能告诉我他们有什么问题?

HTML



#overall-info h1 {
  text-align: center;
  padding: 1em;
}

.box {
  width: 192px;
  height: 192px;
  border: 1px solid green;
  background-color: aquamarine;
  float: left;
}

<section id="overall-info">
  <div class="container">
    <h1>Info</h1>
    <div class="box">

    </div>

    <div class="box">

    </div>

    <div class="box">

    </div>

    <div class="box">

    </div>

    <div class="box">

    </div>
  </div>
</section>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

  

关于box-sizing:border-box

     

宽度和高度属性(以及最小/最大属性)包括内容,填充和边框,但不包括边距。

修复它:

因此,您必须使用box-sizing:border-box;,因为.box(192px)的宽度包括.box边框宽度(边框左边为1px,边框右边为1px)。

如果您不添加 box-sizing:border-box,则会向每个.box添加2px(边框左边为1px,边框右边为1px),换句话说,宽度.box获得宽度(192px + 2px = 194px)。

* {
  box-sizing:border-box;
}

&#13;
&#13;
* {
    box-sizing: border-box;
}

.container {
    width: 960px;
}


#overall-info h1 {
    text-align: center;
    padding: 1em;
}

.box {
    width: 192px;
    height: 192px;
    border: 1px solid green;
    background-color: aquamarine;
    float: left;
}
&#13;
<section id="overall-info">
    <div class="container">
        <h1>Info</h1>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
    </div>
</section>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

对于每个子框,您有1px的边框,它连续累加到总宽度。

因此,如果您希望所有子框都包含在一行中,则容器的宽度应为(192 + 1 + 1)* 5 = 970而不是960。您也可以抑制边框或使用子框宽度190(190 + 1 + 1 = 192)

此外,为容器保留1px的自由宽度空间也可以提供帮助

答案 2 :(得分:0)

您的1px边框正在累加到您的框的宽度空间。

在你的css中设置:

* {box-sizing: border-box; }

你也可以使用百分比宽度btw欢迎你进入响应时代;)

.box {
  float: left;
  box-sizing: border-box;
  background: aquamarine;
  border: 1px solid green;
  width: 20%;
  height: 100px;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing

其中box-sizing设置为border-box用于将边框,填充和宽度计入目标元素的内框模型宽度。

如果您计划支持IE7(今天不需要),则必须手动从元素border-width中减去width