Imagine this set of items in a container (I'm trying with flexbox):
1 2 3
4 5
6
7 8 9
Where item 6 is 100% width, whereas the other items have 33% width. I don't want the space to the right of item 5 to be left empty, instead I would want this:
1 2 3
4 5 7
6
8 9
Is this possible to do with CSS? I could solve this backend for content that doesn't change. But we have media queries that change the number of columns depending on the device you're using.
Code:
.container {
display: flex;
flex-wrap: wrap;
}
.container > * {
width: 33%;
}
.fullsize {
width: 100%;
}
<div >
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div >6</div>
<div>7</div>
<div>8</div>
<div>9</div>
</div>
CodePudding user response:
This is a use case of CSS grid
.box {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* 3 columns */
gap: 5px;
grid-auto-flow: dense; /* don't leave empty areas */
}
.box > div {
border: 1px solid red;
font-size: 30px;
}
.big {
grid-column: 1/-1; /* 100% width */
}
@media (max-width: 600px) {
.box {
grid-template-columns: 1fr 1fr; /* 2 columns */
}
}
<div >
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div >6</div>
<div>7</div>
<div>8</div>
<div>9</div>
</div>
CodePudding user response:
My approach using flexbox
* {
box-sizing: border-box;
}
.container {
max-width: 600px;
min-width: fit-content;
max-height: fit-content;
margin: auto;
background-color: rgba(20, 20, 20, .2);
display: flex;
flex-flow: wrap row;
}
.container-items:nth-child(n) {
flex-basis: 33.3%;
outline: 1px solid black;
text-align: center;
padding: 1em;
}
/* Put item 6th to ordinal group 1 */
.container-items:nth-child(6) {
flex-basis: 100%;
order: 1;
}
/* Put items 1st to 5th to ordinal group 0 */
.container-items:nth-child(n 1):nth-child(-n 5) {
order: 0;
}
/* Put items 8th to 9th to ordinal group 2 */
.container-items:nth-child(n 8):nth-child(-n 9) {
order: 2;
}
<div >
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>
<div >6</div>
<div >7</div>
<div >8</div>
<div >9</div>
</div>
The order
property controls the order in which flex items appear within the flex container, by assigning them to ordinal groups. It takes a single value, which specifies which ordinal group
the flex item belongs to.
For more about order
- link