Reputation: 1145
I have several elements on a web page that's intended to be responsive to screen size. There is always an even number of the elements, and they're always the same height and width, so that when there are four of them, on a desktop screen, each will be one quarter of the width of the screen. To distinguish the elements to the viewer, I have them alternate colour, like this:
When the screen size changes, my CSS automatically reduces the number of elements per row, moving them to multiple rows. On a thin screen, this looks something like this:
However, when the screen size is a tiny bit wider, but still smaller than desktop, I want there to be two elements per row. Here's the problem: When I do that, instead of forming a checkerboard pattern, which would keep the elements distinguished from each other, they of course form columns of the same colour:
This is a problem, since when the elements aren't separated by a margin, you can't tell the rows apart in each column. My question, then, is how you would get the elements to always automatically form a checkerboard pattern, whether they're all in one row, one column, or in multiple rows and columns?
Right now, I'm generating the elements with PHP, so each element is assigned a class denoting its colour. I am open to a solution using PHP, CSS, or JavaScript, but it should work no matter the screen size, and should automatically change the elements' colour to fit the checkerboard pattern whenever the screen resizes.
Upvotes: 4
Views: 395
Reputation: 4715
You should not define the actual colour, but eg the number. If you are dealing with 4, 2 and 1 per row, than use numbers 0-3 like this:
for ($i=0; $i < 20; $i++) {
echo '<div class="box box-'.($i % 4).'">...</div>';
}
Now you can use CSS media queries to define the colors for each screen width you want to change them.
For desktop:
.box-0, .box-2 { color: blue; }
.box-1, .box-3 { color: red; }
For the 2-by-2 layout:
.box-0, .box-3 { color: blue; }
.box-1, .box-2 { color: red; }
Upvotes: 4