I have a simple grid layout in Bootstrap 5 like this:
<div class="row row-cols-1 row-cols-sm-2 row-cols-lg-3">
<div class="col border">Field1</div>
<div class="col border">Field2</div>
<div class="col border">Field3</div>
<div class="col border">Field4</div>
<div class="col border">Field5</div>
<div class="col border">Field6</div>
<div class="col border">Field7</div>
<div class="col border">Field8</div>
<div class="col border">Field9</div>
</div>
Depending on the screen width, it looks like this:
Large Medium Small
[ 1 ] [ 2 ] [ 3 ] [ 1 ] [ 2 ] [ 1 ]
[ 4 ] [ 5 ] [ 6 ] [ 3 ] [ 4 ] [ 2 ]
[ 7 ] [ 8 ] [ 9 ] [ 5 ] [ 6 ] [ 3 ]
[ 7 ] [ 8 ] [ 4 ]
[ 9 ] [ 5 ]
...
However, I want it to be ordered vertically:
Large Medium Small
[ 1 ] [ 4 ] [ 7 ] [ 1 ] [ 6 ] [ 1 ]
[ 2 ] [ 5 ] [ 8 ] [ 2 ] [ 7 ] [ 2 ]
[ 3 ] [ 6 ] [ 9 ] [ 3 ] [ 8 ] [ 3 ]
[ 4 ] [ 9 ] [ 4 ]
[ 5 ] [ 5 ]
...
A solution I found is to use the order class depending on the screen width, like:
<div class="col border order-4 order-sm-7 order-lg-2">Field4</div>
This seams to be a mass and error prone, if a field es added in the future.
Is this the way to go, or is there a simpler solution?
You can add custom class on the parent element and with the additional CSS property column-count and two breakpoints to reduce the column-count. Also remove the row class from the parent element.
.column-order {
--count: 3;
column-count: var(--count);
column-gap: 0;
}
.column-order>div {
width: 100%;
}
@media screen and (max-width: 992px) {
.column-order {
--count: 2;
}
}
@media screen and (max-width: 576px) {
.column-order {
--count: 1;
}
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<div class="column-order">
<div class="col border">Field1</div>
<div class="col border">Field2</div>
<div class="col border">Field3</div>
<div class="col border">Field4</div>
<div class="col border">Field5</div>
<div class="col border">Field6</div>
<div class="col border">Field7</div>
<div class="col border">Field8</div>
<div class="col border">Field9</div>
<div class="col border">Field10</div>
<div class="col border">Field11</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With