Zenn Tech Blog

iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🙆

Adding Book-like Shadows and Gloss to Images with CSS

に公開

You can create a three-dimensional, book-like appearance by applying the box-shadow property, used for adding shadows in CSS, to pseudo-elements as well.

This is the same technique used for books on Zenn.

HTML

The elements involved are (1) the image and (2) the parent element surrounding the image.

<div class="book-cover">
  <img src="~" class="book-cover-image" />
</div>

👆 Although I used a div tag for the book-cover class, a p tag or similar would also work.

Why are two elements necessary?

Ideally, I would like to create a book-like three-dimensional effect using only the img tag. However, to achieve the glossy look characteristic of a book cover, we need to layer a transparent gradient over the image.
This gradient that covers the image is implemented using a pseudo-element (in this case, after).

CSS

/* Element surrounding the image */
.book-cover {
  width: 180px; /* Width of the book */
  position: relative;
  box-shadow: 10px 15px 22px -5px rgba(0, 0, 0, 0.2),
    0 0 2px rgba(0, 0, 0, 0.15); /* Surrounding shadow */
  border-radius: 4px; /* Rounded corners make it look more like a book */
}

/* Use a pseudo-element to overlay a cover for the glossy effect */
.book-cover:after {    
  content: '';
  position: absolute; /* To overlap with the parent element */
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  /* 👇 A gradient with adjusted white transparency */
  background: linear-gradient(
    -90deg,
    rgba(255, 255, 255, 0) 0%,
    rgba(255, 255, 255, 0.1) 80%,
    rgba(255, 255, 255, 0.4) 94%,
    rgba(255, 255, 255, 0.5) 96%,
    rgba(255, 255, 255, 0) 100%
  );
}

/* Image */
.book-cover-image {
  display: block;
  width: 100%; /* Fits the width of the parent element */
  border-radius: 4px; /* Apply border-radius to the image itself as some browsers have bugs with overflow on the parent */
}

The gradient for the glossy effect is simply a white color with adjusted transparency.

  • A vertical glossy line is represented by making the white color intensify sharply just before the left edge.
  • The rounded look of a spine is represented by making the left edge transparent.

With this CSS, you can create a three-dimensional effect that looks like a book. You might not have many opportunities to use this, but I hope you find it helpful.

Zenn Tech Blog
Zenn Tech Blog

Discussion