html - CSS 边距 : Why does this layout behave this way?

标签 html css

我目前正在尝试自学一些 CSS。

我做了这个示例布局:

.group div {
  width: 100px;
  height: 100px;
  background-color: orange;
  display: inline-block;
  text-align: center;
  line-height: 100px;
  font-size: 3em;
  font-weight: bold;
  color: white;
  margin: 10px;
}

.wrap {
  width: 500px;
  height: 120px;
  background-color: #efefef;
}
<div class="wrap">
  <div class="group">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
  </div>
</div>

其中的 div 元素都是 100px 宽度加上 10px margin-left 和 10px margin-right。总和高达 120px。 4 乘以 120px 等于 480px。

=> 它应该适合宽度为 500 像素的环绕元素。

但事实并非如此。第四个元素换行。我必须将宽度增加到 510 以使其适合一行。

为什么?

即使使用 Firebug 我也找不到原因......

最佳答案

display-inline 更改为 float

.group div {
  width: 100px;
  height: 100px;
  background-color: orange;
  float: left;
  text-align: center;
  line-height: 100px;
  font-size: 3em;
  font-weight: bold;
  color: white;
  margin: 10px;
}

.wrap {
  width: 480px;
  height: 120px;
  background-color: #efefef;
}
<div class="wrap">
  <div class="group">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
  </div>
</div>

关于html - CSS 边距 : Why does this layout behave this way?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36541954/

相关文章:

css - 按钮中的文本 (CSS)

html - 我如何使用 Materialize 创建一个带有居中对齐链接的导航栏?

jquery - css:在浏览器中包含随机定位的图像

html - 悬停时隐藏子菜单

jquery - 使用 CSS 和 JQuery 创建组织结构图

html - 制作一个 div "hug"它包含的组件

javascript - 用于增强 HTML5 输入 [type=range] 的插件,例如 jquery-mobile slider

c# - 生成 HTML 的替代方法

css - 下拉菜单使用css显示

javascript - 增加 div 的高度,只有它下面的 div 向下移动,而不是整行