Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Positioning divs with CSS – Flex

I recently had a challenge for Positioning divs with CSS

Challenge:
You are allowed to use only one position property and use flex for the rest.

I am curious how it can be done with just flex. I was able to solve it with grid. But I have no clue how can I position it with flex without rearranging the HTML.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div id="root">
    <div id="a">
        <div>I should be on bottom right</div>
    </div>
    <div id="b">
        <div>I should be on top right</div>
        <div>I should be on top left</div>
        <div>I should be on bottom left</div>
    </div>
</div>

>Solution :

Figured it out. Firstly, setting the main container’s display to flex and then setting the flex-direction to row-reverse yields this as the result with the row order reversed

enter image description here

Set the justify-content to space-between pushes the row elements to their extremes and align-items to flex-end so that the elements are aligned to the bottom line of the container

enter image description here

Finally, set the I should be on top right div‘s position to absolute and move it to extreme right, by setting it’s right property to a finite value, in this case 8px

#root {
  display: flex;
  flex-direction: row-reverse;
  justify-content: space-between;
  align-items: flex-end;
}

#b>div:first-child {
  position: absolute;
  right: 8px;
}
<div id="root">
  <div id="a">
    <div>I should be on bottom right</div>
  </div>
  <div id="b">
    <div>I should be on top right</div>
    <div>I should be on top left</div>
    <div>I should be on bottom left</div>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading