DEV Community

Michael
Michael

Posted on

How to stack HTML elements

I recently had to build this. It's a button with a separate image behind it, providing a cool background effect to the container the button is in.

Alt Text

At first, I didn't have a clue what to do. I'm familiar with z-index but I'd never used it to stack elements directly on top of each other like that.

After a bit of Googling and speaking to a colleague, here's what I ended up doing.



<div class="container">
   <img class="image" src="">
   <a href="" target="_blank" class="btn">Button</a>
</div>


Enter fullscreen mode Exit fullscreen mode

The container



.container {
  display: flex;
  align-items: center;
  justify-content: center;
  float: left
}


Enter fullscreen mode Exit fullscreen mode

I'm using flexbox here along with align-items: center and justify-content: center so that my image and button are both centred inside the parent container. Depending on your needs this may not be the right solution for you. You can read more on flexbox by following the link at the bottom of the page.

float: left here isn't needed for the actual stacking of elements, but in my case it was needed to ensure that the component is left-aligned relative to some text above it, but also that the image stays centred behind the button.

Image



.image {
    z-index: 1;
    position: absolute;
}


Enter fullscreen mode Exit fullscreen mode

I've given the image z-index: 1 and position: absolute. Absolute positioning essentially pulls the element out of the normal document flow meaning that surrounding elements won't be affected by this element.

The Button



.btn {
    z-index: 2;
}


Enter fullscreen mode Exit fullscreen mode

With z-index: 2, and absolute positioning on the image this means the button is nicely stacked on top of the image.

Wrapping up

These basic properties should give you a button stacked nicely on top of an image. This is because the button is now acting as if the image wasn't even there. So rather than getting positioned next to it, it is now on top of it.

If you'd like to learn more about flexbox, absolute position or relative position then check out these great MDN links.
https://developer.mozilla.org/en-US/docs/Glossary/Flexbox
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning

I'm keen to hear if there are any other ways this could be tackled, or any ways my implementation could be improved. So please leave a comment!

Top comments (1)

Collapse
 
thecodepixi profile image
Emmy | Pixi

Excellent first post, Michael! 🎉