Search code examples
csscss-grid

Move tag elements using CSS (without JS)


I have this output:

H1

H2

P

But I want to to move H1 between H2 and P so the new output is:

H2

H1

P

Can this be done with CSS grid or any type of CSS?

Code (Changing HTML structure is not possible):

<div class="wrapper">
  <h1>H1</h1>
  <div class="details">
    <h2>H2</h2>
    <p>P</p>
  </div>
</div>

Solution

  • Using display:contents to "unwrap" the inner div..and the use flexbox and order.

    CSS-Grid options also exist but also require display:contents.

    .details {
      display: contents;
    }
    
    .wrapper {
      display: flex;
      flex-direction: column;
    }
    
    h2 {
      order: -1;
    }
    <div class="wrapper">
      <h1>H1</h1>
      <div class="details">
        <h2>H2</h2>
        <p>P</p>
      </div>
    </div>