DEV Community

Cover image for Don't use CSS position: absolute to overlay two elements
Roman
Roman

Posted on

Don't use CSS position: absolute to overlay two elements

Let's asume you have the following HTML structure to overlay an image with a header:

<div class="card">
    <figure>
        <img src="https://picsum.photos/300/200" alt="Title">
    </figure>
    <header>
        <h2>Title of card</h2>
        <h3>With some short teaser text</h3>
    </header>
</div>
Enter fullscreen mode Exit fullscreen mode

You could be tempted to position the header absolute:

.card {
    position: relative;
    width: 300px;
}
.card > * {
    margin: 0;
}
.card header {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: #fff3;
}
Enter fullscreen mode Exit fullscreen mode

...but then you loose layout on the header. Use grid instead:

.card {
    display: grid;
    width: 300px;
}
.card > * {
    grid-area: 1/1;
    margin: 0;
}
.card header {
    background-color: #fff3;
}
Enter fullscreen mode Exit fullscreen mode

Here is a codepen link with the full example.

Happy coding!

Top comments (4)

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

You could be tempted to position the header absolute

Personally I'd probably be positioning the image with position: absolute instead. That way the header can just do its thing normally while the image can get stretched over the entire object.

It's also probably worth to set object-fit: cover for the image in either case to make sure the image doesn't get stretched around weirdly.

Collapse
 
ratron profile image
Roman

Thank you, @darkwiiplayer, for your feedback. Of course, it all depens on the actual usecase. If it's a card for a product or profile, the image would be important.
In that case, grid makes sure that the image retains it's original size - is not croped or stretched.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

I don't think that image should have an alt attribute, as it is purely decorative; but maybe someone more knowledgeable about accessibility can confirm or correct me?

Collapse
 
ratron profile image
Roman

Again, thank you, @darkwiiplayer, for your question. It's always a good idea to have meaningful alt descriptions for images. If they are purely decorative, a role="presentation" or aria-hidden="true" should be added.