html - 使用 CSS 获取 flexbox 中的行数

标签 html css flexbox

我有一个 flexbox 元素,它可以有任意数量的子元素。这些 child 可以有不同的宽度(但不超过 100%),但高度都相同,因此它们形成整齐的行。插图:

[.....] [....]  
[.............]  
[..] [....] [.]  
[......]

当元素多于三行时,我想给元素设置不同的样式,而不是只有三行、两行或一行时。有没有办法用 CSS 做到这一点?

我不知道一行中会有多少个子元素。每排可以是一个 child ,也可以是两个或三个。如上图所示。这些元素是根据可以更改的数据生成的,因此我无法将它们固定为每行 x 个元素。

.parent {
  display: flex;
  flex-wrap: wrap;
}

.parent .child {
  max-width: 100%;
  background: red;
}

// can I do this?
.parent:has-more-than-three-lines .child {
  background: blue;
}

我知道我可以使用 JavaScript 读取元素的高度和呈现后子项的高度,并计算有多少行。但我想避免这种情况。如果我必须给子元素一个固定的高度,那对我来说没问题。

明确地说,我想根据 parent 的高度为所有 child 设置样式,而不仅仅是附加行中的 child 。

最佳答案

如果您知道每个元素的高度(即每行的高度),这里有一个使用多个背景的想法

.parent {
  display: flex;
  flex-wrap: wrap;
  margin:10px;
  
  background:
    linear-gradient(blue,blue)     0 0/100% calc(100% - 4 * 50px),
    linear-gradient(yellow,yellow) 0 0/100% calc(100% - 3 * 50px),
    linear-gradient(grey,grey)     0 0/100% calc(100% - 2 * 50px), 
    linear-gradient(pink,pink)     0 0/100% calc(100% - 1 * 50px), 
    linear-gradient(black,black)   0 0/100% calc(100% - 0 * 50px);
}

.parent > div {
  max-width: 100%;
  height:50px;
  flex-grow:1;
  min-width:100px;
  border:1px solid red;
  box-sizing:border-box;
}

div.two {
  flex-basis:22%;
  border:1px solid blue;
}
div.three {
  flex-basis:44%;
  border:1px solid green;
}
<div class="parent">
<div class="two"></div>
<div ></div>
<div ></div>
<div class="two"></div>
<div ></div>
<div class="three"></div>
<div ></div>
<div class="two"></div>
<div class="three"></div>
<div class="three"></div>
</div>

<div class="parent">
<div class="two"></div>
<div ></div>
<div ></div>
<div class="two"></div>
<div ></div>
<div class="three"></div>
<div ></div>
<div class="two"></div>
<div class="three"></div>
<div class="three"></div>
<div ></div>
<div class="three"></div>
</div>


<div class="parent">
<div class="two"></div>
<div ></div>
<div ></div>
<div ></div>
<div class="two"></div>
<div class="three"></div>
<div class="three"></div>
</div>

<div class="parent">
<div class="two"></div>
<div ></div>
<div ></div>
<div ></div>
<div class="two"></div>
</div>

诀窍很简单,我们有不同的背景图层,每个图层的宽度和高度等于 calc(100% - n * 50px)。如果 height 的值为负,图层将不会显示,但如果为正,它将显示,并且由于 background-repeat 默认为 repeat,它将覆盖所有元素.

顺序也很重要。例如,如果我们有 3 行,蓝色和黄色的高度将为负值,而另一行的高度为正值,因此我们将在顶部显示灰色。我们添加另一行,使黄色为正(它会显示)。我们删除另一行,使灰色为负,粉红色将显示。

当然,这个技巧只有在你想对元素应用背景样式时才有效。如果您想应用其他样式,我们应该找到其他技巧。

关于html - 使用 CSS 获取 flexbox 中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55847999/

相关文章:

javascript - css 按钮位于工具栏下方

html - CSS Border-Image/Frame Like 叠加层

CSS隐藏div在flexbox的末尾

html - css:Chrome 和 Safari 中不同的列容器高度(bootstrap 4)

html - 如何在 flex-direction 为 column 和 flex-wrap 为 wrap 的 flex box 中将容器宽度设置为 child

html - 当屏幕尺寸足够小时,列表中的第三项将移至第二行的右侧而不是左侧

html - 更改页脚样式 - Wordpress

用于在 Firefox 中缩放背景 svg 的 css sprite

css - 单击其子项时如何突出显示 <ul> 中的颜色?

html - 垂直列表而不是下拉列表的水平列表