html - 如何根据元素数量设置元素宽度?

标签 html css

我正在寻找一个解决方案,通过该解决方案,我将能够根据一行中的元素数量设置元素宽度。最重要的是,如果一行中的元素数量达到“8”,那么下一个元素应该移动到另一行。我正在使用 bootstrap 3.3.7。

.child-element {
    background:green;
    border:1px solid #fff;
}

/* one item */
.child-element:first-child:nth-last-child(1) {
    width: 100%;
}

/* two items */
.child-element:first-child:nth-last-child(2),
.child-element:first-child:nth-last-child(2) ~ .child-element {
    width: 50%;
}

/* three items */
.child-element:first-child:nth-last-child(3),
.child-element:first-child:nth-last-child(3) ~ .child-element {
    width: 33.3333%;
}

/* four items */
.child-element:first-child:nth-last-child(4),
.child-element:first-child:nth-last-child(4) ~ .child-element {
    width: 25%;
}

/* five items */
.child-element:first-child:nth-last-child(5),
.child-element:first-child:nth-last-child(5) ~ .child-element {
    width: 20%;
}

/* six items */
.child-element:first-child:nth-last-child(6),
.child-element:first-child:nth-last-child(6) ~ .child-element {
    width: 16.6666%;
}

/* seven items */
.child-element:first-child:nth-last-child(7),
.child-element:first-child:nth-last-child(7) ~ .child-element {
    width: 14.2857%;
}

/* eight items */
.child-element:first-child:nth-last-child(8),
.child-element:first-child:nth-last-child(8) ~ .child-element {
    width: 12.5%;
} 

我尝试实现以下代码,但它根本无法按要求工作(它不起作用)。

<div class="container">
    <div class="row bg-red">
        <div class="col-lg-12"> 
                <div class="child-element">1</div>
                <div class="child-element">1</div>
        </div>
    </div>
</div>

元素宽度应基于一行中元素的数量。我不知道如何添加将第九个及更多元素分解为第二个的功能

最佳答案

您可以执行以下操作:在父级上启用 flexbox,然后设置 justify-content: space- Betweenflex-wrap: wrap. 在每个子项上,将 flex-grow: 1 设置为 width 的 100%,然后设置 min-width: calc(100%/8) 设置它不能小于 width 的 1/8。 它将使所有下一个元素进入下一行。

.parent {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.item {
  flex-grow: 1;
  min-width: calc(100%/8);
}
<div class="parent">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
  <div class="item">8</div>
  <div class="item">9</div>
  <div class="item">10</div>
</div>

示例:

关于html - 如何根据元素数量设置元素宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54617107/

相关文章:

php - 在 Laravel 中列出本月或每个月的所有日期

html - 代码复制理论

html - 在 div 响应式 CSS 中制作图像

javascript - 使用键盘放大会将居中图像向右移动

javascript - 单击选项卡无法准确工作

php - 如何将特色内容放在商店内容下方

css - 使用 box-shadow 创建边框

html - 截断时使绝对定位元素滚动

javascript - 使用线性渐变 CSS 将 html Div 分成 12 列

jquery - 复选框未 checkin jQuery slideToggle UL 列表