Search code examples
htmlcssflexboxmedia-queries

How to group flex-children and show them in a different direction?


I'm new to flexbox, and I can't find a solution for my problem. I have a label, an image, an input, and an image in a paragraph. I added display:flex to my paragraph which aligns my images to the input very nicely.

<p style='display:flex'><label>
    <image><input><image>
</p>

When my resolution is to small I want to center my content and put the label above my input like this:

<p><label>
<MINUS-image><input><PLUS-image></p>

I added flex-direction: column to my paragraph (and do some centering-stuff to my label) when my resolution is below 600px. But then everything is in a column.

<p><label>
<MINUS-image>
<input>
<PLUS-image></p>

Is there a way to group my images and the input, to keep them in one line?


Solution

  • Instead of change to column, use flex-wrap: wrap and give the label a width of 100%.

    Using the media query, and on narrower screens, this will make the label take full width of its parent, the p, and push the other elements to a second row, instead of stack them all vertically, as column does.

    Stack snippet

    p {
      display:flex;
    }
    
    @media (max-width: 600px) {
      p {
        flex-wrap: wrap;
      }
      p label {
        width: 100%;
      }
    }
    <p>
      <label>Label</label>
      <span>image</span>
      <input>
      <span>image</span>
    </p>