I'm using flex-wrap
, which gives me output like
In this two-column example the container number 5 in the last row grows.
However, the first containers are usually more important than the last.
So how can I priorise them? I considered flex-direction: row-reverse
without success.
It should work also for say, 3 columns and 8 containers, in which case the first two should grow (not the last two). All containers should have the same size in case the number of containers is a integer multiple of the column numbers .
And the code for the example above
div > div {
background-color: #3b3;
flex: 1 1 40%;
}
<div style="display:flex; flex-wrap: wrap; gap: 10px;">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
CodePudding user response:
You can use specific selector to achieve this:
.box {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin: 20px 0;
}
.box > div {
background-color: #3b3;
flex: 1 1 40%;
}
/* make the first child full width if there is an odd number of elements */
.box > div:nth-last-child(odd):first-child {
flex-basis: 100%;
}
<div >
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
<div >
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
For a 3 columns configuration, you use the same logic
.box {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin: 20px 0;
}
.box > div {
background-color: #3b3;
flex: 1 1 30%;
}
/* the first child full width when we have 3N 1 elements */
.box > div:nth-last-child(3n 1):first-child {
flex-basis:100%;
}
/* first and second child half width when we have 3N 2 elements */
.box > div:nth-last-child(3n 2):first-child,
.box > div:nth-last-child(3n 2):first-child *{
flex-basis: 40%;
}
<div >
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
</div>
<div >
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div >
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
<div >
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>