CSS - Shadows & Opacity

Overview

Estimated time: 12–15 minutes

Shadows add depth and hierarchy. Opacity creates layering effects. Use both for polished, modern interfaces.

Learning Objectives

  • Apply box-shadow for depth and focus states.
  • Use text-shadow for readable text over images.
  • Control transparency with opacity and rgba/hsla colors.

Details & Examples

/* Box shadows */
.card { 
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); 
}
.card:hover { 
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15); 
}
.inset-shadow { 
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1); 
}

/* Text shadows */
.hero-text { 
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.8); 
}

/* Opacity */
.fade { opacity: 0.6; }
.overlay { background: rgba(0, 0, 0, 0.5); } /* preferred over opacity for backgrounds */
Soft shadow
Lifted shadow
Text shadow over gradient
Faded with opacity

Try it

Vocabulary

  • Offset: Horizontal and vertical distance of the shadow.
  • Blur radius: How spread out the shadow appears.
  • Spread radius: Expands the shadow before blurring.

Common Pitfalls

  • Too many or too heavy shadows can make interfaces feel cluttered.
  • Using opacity affects child elements; prefer rgba colors when possible.

Checks for Understanding

  1. What's the difference between opacity: 0.5 and background: rgba(255,255,255,0.5)?
  2. How do you create an inset shadow?
Show answers
  1. opacity affects the entire element and its children; rgba only affects the background
  2. Add the inset keyword: box-shadow: inset 0 2px 4px rgba(0,0,0,0.1)

Exercises

  1. Create a focus ring using box-shadow (not outline) that’s visible on dark and light backgrounds.
  2. Build a card hover that increases shadow radius and y-offset subtly.
Suggested answers
  1. Example: box-shadow: 0 0 0 3px rgba(34,197,94,.45) (tune color/alpha for contrast)
  2. Example hover: box-shadow: 0 10px 28px rgba(0,0,0,.15)