Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a container's size fits its `position: absolute;` children's size

I’m trying to make a set of divs overlap one another inside a given container:

.container {
  display: inline-block;
  position: relative;
}

.block {
  position: absolute;
  left: 0;
  top: 0;
}
This is a <div class="container">
  <div class="block" style="background: rgba(255, 0, 0, 0.3);">wonderful</div>
  <div class="block" style="background: rgba(0, 255, 0, 0.3);">cool</div>
  <div class="block" style="background: rgba(0, 0, 255, 0.3);">great</div>
</div> test!

So that they are inline with text. The problem is: the container has no width or height, and the children are not properly positioned.

The trick is not to have to specify explicitly the size of the container but have CSS figure it out automatically so that these three words overlap inline with the sentence.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A workaround is to set the container an inline-grid with place-items: start (so its children only take minimum space and the grid width will be determined by its longest child), then set all its children with both grid-column and grid-row to 1:

.container {
  display: inline-grid;
  place-items: start;
}

.block {
  grid-column: 1;
  grid-row: 1;
}
This is a <div class="container">
  <div class="block" style="background: rgba(255, 0, 0, 0.3);">wonderful</div>
  <div class="block" style="background: rgba(0, 255, 0, 0.3);">cool</div>
  <div class="block" style="background: rgba(0, 0, 255, 0.3);">great</div>
</div> test!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading