How can I apply CSS to flex items on a certain row, or to flex items that have been wrapped?

醉酒当歌 提交于 2021-01-29 00:39:53

问题


I have a flex div that contains five green boxes.

green boxes

The flex div is using flex-wrap: wrap; to wrap the objects inside when needed.

I want all of the wrapped items to have an orange border:

enter image description here

And I want all wrapped items on the third row to be yellow instead of green.

enter image description here


回答1:


AFAIK there is no way to select elements depending on which line of their containing block they are placed. So it may not be possible to do this directly.

However, you can fake the borders:

#outer {
  display: flex;
  flex-wrap: wrap;
  overflow: hidden; /* Hide additional borders after the last line */
}
#outer::after { /* Hide additional borders in the last line */
  content: '';
  background: #fff;
  flex-grow: 1;
}
.box {
  background-color: green;
  width: 50px;
  height: 30px;
  margin: 10px;
  position: relative;
}
.box::after { /* Fake border for the next line */
  content: '';
  position: absolute; /* Remove from the flow */
  top: 100%; /* Move downwards to the next line */
  margin-top: 20px; /* Move a bit more because .box have margin */
  outline: 3px solid #ffa500; /* Borders */
  width: 100%;
  height: 100%;
  z-index: -1;
}
<div id="outer">
  <div class="box"></div><div class="box"></div>
  <div class="box"></div><div class="box"></div>
  <div class="box"></div><div class="box"></div>
  <div class="box"></div><div class="box"></div>
  <div class="box"></div><div class="box"></div>
  <div class="box"></div><div class="box"></div>
</div>


来源:https://stackoverflow.com/questions/30360544/how-can-i-apply-css-to-flex-items-on-a-certain-row-or-to-flex-items-that-have-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!