Home > Blockchain >  How to overlap elements along both width and height, taking on minimum value for each?
How to overlap elements along both width and height, taking on minimum value for each?

Time:06-29

I want to have elements that overlay each other, such that the parent takes on the minimum height and width needed to contain them. Inspired from this question, I've come up with the below solution. See this identical JSFiddle.

#merger {
  text-align: center;
  background-color: #f2e7e5;

  overflow: hidden;      
  display: inline-block;
}

#merger > * {
  float: left;
  width: 100%;
}

#merger .active {
  visibility: visible;
}

#merger > *:not(:first-child) {
  margin-left: -100%;
}
<div id="merger">
  <div>
    1
  </div>
  <div>
    222
  </div>
  <div>
    3
    <br />
    3
  </div>
  <div>
    444
    <br />
    444
  </div>
</div>

However, the above solution only works for height. You can see that the parent merger actually takes on extra width.

If you go into the JSFiddle and remove one of the elements that has less width than the rest (such as the "1"), the parent's width shrinks. The expected behavior is that the parent's width remains the same, since it should be equivalent to the width of it's widest child. Removing the non-widest child should have no impact on width, just like removing the non-tallest child currently has no impact on height.

How do I extend the behavior I already have for height to width as well?

CodePudding user response:

I'd suggest using CSS Grid, as follows:

#merger {
  /* displaying the element as an inline grid; so that the
     element itself behaves as an inline element, while still
     laying its own content out as a grid; so instead of
     taking the full block-width of its parent it takes only
     the space it needs: */
  display: inline-grid;
  /* defining one named area into which all content will be
     placed: */
  grid-template-areas: "allContent";
  background-color: #f2e7e5;
  overflow: hidden;
}

#merger>div {
  /* placing all the <div> children of the #merger element
     into the single named grid area: */
  grid-area: allContent;
}
<div id="merger">
  <div>
    1
  </div>
  <div>
    222
  </div>
  <div>
    3
    <br /> 3
  </div>
  <div>
    444
    <br /> 444
  </div>
</div>

References:

Bibliography:

  • Related