1

How can I position the first child under a flex parent, out of the flex calculations, and also set its position as needed?

.mycontainer{
      background-color: 
      rgb(200,200,200);
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
    }
    .mycontainer-bar{
      width: 20px;
      height: 20px;
      background-color: red;
      position: absolute;
      /* The following sticks the bar/box to the top-right of the page, not of container */
      top: 0px;
      right: 0px;
    }
    .row{
      margin: 5px;
      background-color: blue;
      width: 80%;
      height: 90px;
    }
<div class="mycontainer">
      <div class="mycontainer-bar">t</div>
      <div class="row">r1</div>
      <div class="row">r2</div>
    </div>

I'm trying to make the red box like a toolbar, sticking it to the top-left or top-right of its parent container.

One way around, I can make two children of the container, where the first child would be the toolbar and the second one would be a Flex parent of the required rows. But before I march on that, I really want to if it is possible to make it work out as I want without needing extra html content.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Kora21
  • 21
  • 6
  • why not use a CSS-Grid? – tacoshy Jun 21 '22 at 07:11
  • It's not positioned inside container because absolutely positioned element is not relative to `.mycontainer` but `body`, so it is positioned in the top right of `body`. You need to add `position: relative` to `.mycontainer`. If want to absolutely position an element inside some parent element, then parent need to be relatively positioned. – tony Jun 21 '22 at 07:12

2 Answers2

1

(Will mark it as best answer when I'm able to.)

I've sorted it out by having

position: relative

on the container, and

position: absolute; 
top:0px; 
right:0px;

On the red box. It also helped not take any space for the box!

Kora21
  • 21
  • 6
0

If I understood correctly where you want to place it, one way to do it is with position:relative and adding margin-left.

.mycontainer{
  background-color: 
  rgb(200,200,200);
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}
.mycontainer-bar{
  width: 20px;
  height: 20px;
  background-color: red;
  position: relative;
  margin-left: calc(100% - 20px)
}
.row{
  margin: 5px;
  background-color: blue;
  width: 80%;
  height: 90px;
}
<div class="mycontainer">
  <div class="mycontainer-bar">t</div>
  <div class="row">r1</div>
  <div class="row">r2</div>
</div>
nedoder
  • 465
  • 1
  • 5
  • 17
  • 1
    Thank you, I've just sorted it out which I'll post as an answer in a moment. I should've been more clear, I also wanted the red box to not push the other childs down. Nevertheless thank you very much – Kora21 Jun 21 '22 at 07:22