Home > Software design >  absolute positioned parent with a flex growing child not inheriting width
absolute positioned parent with a flex growing child not inheriting width

Time:02-03

I have a flex box that will grow column wise based on content inside it; the width of the box should fit the content. I have to place this box inside a parent container which is absolutely positioned on the page.

If I do so, the parent container is not taking the dynamic width of the child rather it's sticking to it's initial width and the child content is overflowing.

Code Available: https://jsfiddle.net/visu310p/q8hsk42L/8/

.parent {
  color: white;
  background: blue;
  margin: auto;
  padding: 1em;
  position: absolute;
  left: 10px;
  top: 100px;
}
.child {
  background-color: green;
  display: flex;
  height: 100px;
  flex-direction: column;
  flex-wrap: wrap;
  margin: 0;
}

CodePudding user response:

You have to set a width for the parent. That is because whenever an element is positioned absolutely the width and height is automatically set to auto. So in your case the child's flex-wrap: wrap will cause an overflow unless a width is specified for the absolutely positioned parent.

.parent {
  color: white;
  background: blue;
  margin: auto;
  padding: 1em;
  position: absolute;
  left: 10px;
  top: 100px;
  width: calc(100% - 20px); /* can be any value */
}
.child {
  background-color: green;
  display: flex;
  height: 100px;
  flex-direction: column;
  flex-wrap: wrap;
  margin: 0;
}
  •  Tags:  
  • Related