Position the outer div however you want, then position the inner divs using absolute. They'll all stack up.
Just remove absolute positioning. Center the divs using margin:auto and then provide whatever vertical margins you like. Show activity on this post. You can give margin to inner div.
To align div horizontally, one solution is to use css float property. But a better solution is to to use CSS display:inline-block on all divs which needs to be aligned horizontally and place them in some container div.
Just remove the min-width from your CSS! And give min-width to the container with margin: auto to make it center. Show activity on this post. Take out the min-width CSS.
Position the outer div however you want, then position the inner divs using absolute. They'll all stack up.
.inner {
position: absolute;
}
<div class="outer">
<div class="inner">1</div>
<div class="inner">2</div>
<div class="inner">3</div>
<div class="inner">4</div>
</div>
To add to Dave's answer:
div { position: relative; }
div div { position: absolute; top: 0; left: 0; }
You can now use CSS Grid to fix this.
<div class="outer">
<div class="top"> </div>
<div class="below"> </div>
</div>
And the css for this:
.outer {
display: grid;
grid-template: 1fr / 1fr;
place-items: center;
}
.outer > * {
grid-column: 1 / 1;
grid-row: 1 / 1;
}
.outer .below {
z-index: 2;
}
.outer .top {
z-index: 1;
}
If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index
CSS attribute. This should work (untested)
<div>
<div style='z-index: 1'>1</div>
<div style='z-index: 2'>2</div>
<div style='z-index: 3'>3</div>
<div style='z-index: 4'>4</div>
</div>
This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)
All the answers seem pretty old :) I'd prefer CSS grid for a better page layout (absolute
divs can be overridden by other divs in the page.)
<div class="container">
<div class="inner" style="background-color: white;"></div>
<div class="inner" style="background-color: red;"></div>
<div class="inner" style="background-color: green;"></div>
<div class="inner" style="background-color: blue;"></div>
<div class="inner" style="background-color: purple;"></div>
</div>
<style>
.container {
width: 300px;
height: 300px;
margin: 0 auto;
background-color: yellow;
/* important part */
display: grid;
place-items: center;
grid-template-areas:
"inner-div";
}
.inner {
height: 100px;
width: 100px;
/* important part */
grid-area: inner-div;
}
</style>
If you hide the purple div with CSS, you'll see the blue div is at the top.
Here's a working link
style="position:absolute"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With