Max
Max

Reputation: 1

How do I style elements based on how many of them there are?

I'm trying to add flex-basis to both of the child elements when there are two of them.

<div class="group">
 <div class="column"></div>
 <div class="column"></div>
</div>

I've tried a number of ways to set the flex-basis if there are only two columns, including:

 .group:first-child:nth-last-child(2) ~ .column{
    flex-basis: calc(50% - 30px);
    background: red;
  }

but it only styles one of the columns. Is there a way I can use this same code but get it to style all the columns?

Upvotes: 0

Views: 33

Answers (1)

A Haworth
A Haworth

Reputation: 36664

You can test whether the first-child is also the nth-last-child(2) [ie the second from last child] and also you can test whether the last-child is also the second child.

.group :first-child:nth-last-child(2),
.group :last-child:nth-child(2) {
  flex-basis: calc(50% - 30px);
  background: red;
}
<div class="group">
  <div class="column">col1</div>
  <div class="column">col2</div>
</div>

Upvotes: 1

Related Questions