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>
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;
}
...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;
}
Here is a codepen link with the full example.
Happy coding!
Top comments (4)
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.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.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?
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, arole="presentation"
oraria-hidden="true"
should be added.