包装元素上的CSS容器宽度

问题描述 投票:0回答:1

我试图让一个容器div扩展以包裹几个内联块元素。

一切都有效,直到容器缩小或添加更多元素。

.top {
  width: 80%;
  background-color: red;
}
.container {
  background-color: gray;
  display: inline-block;
}
.box {
  display: inline-block;
  background-color: blue;
  height: 100px;
  width: 100px;
}
<div class="top">
  <div class="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>

这是一个例子。 https://jsfiddle.net/8fhjaf6z/11/

灰色.container将盒子包装在其中,直到您添加更多盒子或收缩.top容器。在那一点,盒子包裹并移动到下一行,这是我想要的,但现在灰色.container填充红色.top容器留下一堆空的空间到右边。

我也试过浮动.box元素,但得到相同的结果。

html css containers width
1个回答
1
投票

填充由移动到下一行的框创建的空间的一种可能方法是将.container的显示设置为内联。现在你只有框背后的灰色背景。使用顶部填充,您可以使灰色背景占据框的整个高度(作为将高度设置为内联元素的解决方法,这对于height属性是不可能的):

.top {
  width: 80%;
  background-color: red;
  font-size: 0;
}
.container {
  background-color: gray;
  display: inline;
  padding: 105px 0 0 0;
}
.box {
  display: inline-block;
  background-color: blue;
  height: 100px;
  width: 100px;
  margin: 0 0 5px 5px;
}
<div class="top">
  <div class="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.