Card with a lazy-loaded background image

HTML card element that has a background image with lazy loading.

Preview

Card with a Lazy-loaded Background Image and a Title

Html

Click to edit (doesn't update preview)

<div class="card">
  <p>Card with a Lazy-loaded Background Image and a Title</p>
  <img src="https://vaihe.com/component-library/sample-image.jpg" alt="" loading="lazy" width="500" height="500">
</div>

/

Click to edit (doesn't update preview)

.card {
  position: relative;
  min-height: 25em;
  width: 25em;
  max-width: 100%;
  display: flex;
  align-items: flex-end;
  border-radius: 0.75em;
  overflow: hidden;
}

.card img {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.card p {
  z-index: 1;
  position: relative;
  color: #fff;
  margin: 0.5em;
  font-size: 1.25rem;
  font-weight: 600;
}

.card::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  height: max(20em, 50%);
  background: linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 100%);
  width: 100%;
}

Description

Accessibility

Remember to give the image an alt attribute so screen readers will properly announce it. I didn't include one as this is just an example.

Using <img> vs background-image

This card uses <img> element because it's more performance friendly than background-image. Regular <img> elements can be lazy-loaded using loading="lazy" attributes, but background images can't.