-1

I have a div with a specific width and height in pixels. I have another div inside it which takes 100% of both the width and height of the outer div. When I don't have position: fixed on the inside div, it takes the correct (100%) width of the outer div. However, when I set position: fixed to it, the div goes beyond the outside div boundaries. I am not sure why.

Code:

#outer-div {
  width: 800px;
  height: 300px;
}

#inner-div {
  width: 100%;
  height: 100%;
  border: 1px solid black;
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
}

#bottom-div {
  position: absolute;
  top: 2000px;
}
<div id="outer-div">
  <div id="inner-div">This is some text</div>
</div>
<div id="bottom-div">I am at the bottom to allow page to scroll.</div>
user12055579
  • 694
  • 11
  • 22

2 Answers2

2

Since you want the maximum height and width of the parent element, you can inherit this.
So apply width: inherit and height: inherit to the fixed element.

#inner-div {
  width: inherit;
  height: inherit;
  border: 1px solid black;
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
}
Azametzin
  • 5,223
  • 12
  • 28
  • 46
1

I am pretty sure it is because position: fixed; takes it out of the normal document flow so the width: 100%; and height: 100%; doesn't take the parent divs' width and height.

You can use width: inherit; and height: inherit; instead.

Dostrelith
  • 922
  • 5
  • 13