Home > Software engineering >  How to have 2 overlapping elements fill their parent
How to have 2 overlapping elements fill their parent

Time:05-09

I need 2 elements (in the demo marked #a and #b) to both fill their parent entirely. I need element #a filling it's parent (this is easy, I just set flex to 1), and I need element #b to be atop of #a and have exactly same size as #a. How to make #b have the same size? If I set width/height to 100% #b will overflow.

body {
  margin: 0;
  display: flex;
  width: 100vw;
  height: 100vh;
}

nav {
  background-color: silver;
}

main {
  flex: 1;
  border: 5px solid green;
  display: flex;
}

#a {
  border: 1px solid aqua;
  flex: 1;
}
#b {
  position: absolute;
  border: 1px dashed blue;
  flex: 1;
}
<nav>sidebar of variable width</nav>
<main>
  <div id="a">aaa</div>
  <div id="b">bbb</div>
</main>

CodePudding user response:

If you set the parent (main) to position: relative while #b is position: absolute then you should be able to size it in relation to main (100% width and height in this case) and position it to top and left 0.

body {
  margin: 0;
  display: flex;
  width: 100vw;
  height: 100vh;
}

nav {
  background-color: silver;
}

main {
  flex: 1;
  border: 5px solid green;
  display: flex;
  position: relative;
}

#a {
  border: 1px solid aqua;
  flex: 1;
}

#b {
  position: absolute;
  border: 1px dashed blue;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<nav>sidebar of variable width</nav>
<main>
  <div id="a">aaa</div>
  <div id="b">bbb</div>
</main>

  • Related