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.
>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!