使用 CSS 获取 Flexbox 中的行数/行数

KWe*_*iss 8 html css flexbox

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

[.....] [....]  
[.............]  
[..] [....] [.]  
[......]
Run Code Online (Sandbox Code Playgroud)

当超过三行时,我想以不同的方式设置元素的样式,而不是只有三行、两行或一行时。有什么方法可以用 CSS 做到这一点吗?

我不知道一行中有多少个子元素。每行可能有一个孩子,也可能是两个或三个。如上图所示。这些元素是根据可以更改的数据生成的,因此我无法将它们固定为每行 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;
}
Run Code Online (Sandbox Code Playgroud)

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

需要明确的是,我想根据父级的高度来设置所有子级的样式,而不仅仅是附加行中的子级。

Jak*_*ake -3

我能找到的唯一解决方案来自 Lea Verou 2011 年的一篇文章,可在此处找到。

正如我在评论中所说,您必须使用复杂的nth-child选择器。

* {
  box-sizing: border-box;
  font-family: Arial, sans-serif;;
}

body {
  margin: 0;
}

.wrapper,
.container {
  display: flex;
  flex-wrap: wrap;
}

.wrapper {
  align-items: flex-start;
}

.container {
  width: calc(1/3 * 100% - 2em);
  flex-direction: column;
  border: 1px solid #000;
  margin: 1em;

  /* Optional : if you want border-radius on the container */
  border-radius: 5px;
  overflow: hidden;
}

.item {
  padding: 1em;
}

/* Style for standalone element */

.item:nth-child(1):nth-last-child(1) {
  background: lemonchiffon;
}

/* Style for element that has 2 childs */

.item:nth-child(1):nth-last-child(2),
.item:nth-child(2):nth-last-child(1) {
  background: lightskyblue;
}

/* Style for element that has 3 childs */

.item:nth-child(1):nth-last-child(3),
.item:nth-child(2):nth-last-child(2),
.item:nth-child(3):nth-last-child(1) {
  background: thistle;
}

/* Style for element that has 4 childs */

.item:nth-child(1):nth-last-child(4),
.item:nth-child(2):nth-last-child(3),
.item:nth-child(3):nth-last-child(2),
.item:nth-child(4):nth-last-child(1) {
	background: gainsboro;
}

/* For further information, see http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/ */
Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
  <div class="container">
    <div class="item">
      Item
    </div>
  </div>
  <div class="container">
    <div class="item">Item</div>
    <div class="item">Item</div>
  </div>
  <div class="container">
    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)