Home > Mobile >  Positioning divs with CSS - Flex
Positioning divs with CSS - Flex

Time:08-12

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.

<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>

CodePudding user response:

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>

  •  Tags:  
  • css
  • Related