Search code examples
htmlcsspure-css

How to make an alternating responsive grid?


I have a 2-column grid as follows: some text, followed by an image related to that text. On the other row the order is flipped:

| Text 1           | Image for Text 1 |
| Image for Text 2 | Text 2           |
| Text 3           | Image for Text 3 |

I created a standard grid to achieve it (jsfiddle: https://jsfiddle.net/6yxLpqmr/), extract from source:

<div class="pure-g">
  <article class="pure-u-1 pure-u-md-1-2">Text 1</article>
  <article class="pure-u-1 pure-u-md-1-2">Image for Text 1</article>
  <article class="pure-u-1 pure-u-md-1-2">Image for Text 2</article>
  <article class="pure-u-1 pure-u-md-1-2">Text 2</article>
  <article class="pure-u-1 pure-u-md-1-2">Text 3</article>
  <article class="pure-u-1 pure-u-md-1-2">Image for Text 3</article>
  <!-- many more alternating articles like this -->
</div>

However, once the grid is collapsed on a narrow screen, it results in:

Text 1
Image for Text 1
Image for Text 2
Text 2
Text 3
Image for Text 3
<...>

Which is un-intuitive.

Q1: How can I change the result to:

Image for Text 1
Text 1
Image for Text 2
Text 2
Image for Text 3
Text 3

Q2: is it possible to write CSS in a way that creates the alternation by itself (without generating the CSS of course), while semantically keeping the HTML "in order" (image/text/image/text/...)?


Solution

  • It is better to create child box and use flex-direction: column-reverse. Check out the jsFiddle here.

    <!DOCTYPE html>
    <html>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <head>
        <link rel="stylesheet" href="https://unpkg.com/purecss@2.0.6/build/pure-min.css">
        <link rel="stylesheet" href="https://unpkg.com/purecss@2.0.6/build/grids-responsive-min.css" />
        <style>
            article {
                min-height: 100px;
                min-width: 200px;
            }
            .box {
                display: flex;
                flex-direction: column;
            }
            @media screen and (max-width: 600px) {
                 .box:first-child {
                    flex-direction: column-reverse;
                 }
            }
        </style>
    </head>
    
    <body>
    
        <div class="pure-g">
            <div class="box">
                <article class="pure-u-1 pure-u-md-1-2">Text 1</article>
                <article class="pure-u-1 pure-u-md-1-2">Image for Text 1</article>
            </div>
            <div class="box">
                <article class="pure-u-1 pure-u-md-1-2">Image for Text 2</article>
                <article class="pure-u-1 pure-u-md-1-2">Text 2</article>
            </div>
        </div>
    </body>
    </html>