My challenge lies in arranging items into two columns or one, with a specific layout for mobile devices.
The order of the items changes between the two column and single column layouts.
The number and size of items vary dynamically.
For example, in a two-column display:
left.one right.one
left.two right.two
left.three
Due to varying item heights, left.two may not align perfectly with right.two...
In a single column, it might look like this:
left.one
left.two
right.one
right.two
left.three
I need to assign classes dynamically based on whether the items are displayed in one or two columns.
How can I create a flexible grid structure without needing to conditionally wrap column content (such as div.left and div.right) when in two-column view? I want to avoid relying on JavaScript for this solution. Can it be achieved using just CSS?
I won't share my current JavaScript-dependent workaround that wraps each column's content because I'm looking for a pure CSS solution.
Please note, this is a demonstration and does not serve as the final answer to the problem at hand.
:root {
--gridColumns: 2;
}
.left,
.right {
padding: 10px;
margin: 10px;
color: white;
background-color: grey;
border-radius: 2px;
}
.grid {
display: grid;
background-color: lightgrey;
grid-template-columns: repeat(var(--gridColumns), 1fr);
}
@media screen and (max-width: 400px) {
:root {
--gridColumns: 1;
}
}
<div class="grid">
<div class="left one">left one</div>
<div class="right one">right one</div>
<div class="left two">left two</div>
<div class="right two">right two</div>
<div class="left three">left three</div>
</div>