Basics and Properties of CSS box-shadow
By using the box-shadow
property in CSS, you can add shadows to elements, create a sense of depth, and achieve visually engaging effects.
The code itself is simple, like the example below. However, because it’s so concise, it can be tricky to understand what each value represents.
box-shadow: 10px 10px 20px 0px rgba(0,0,0, 1);
These five values, from left to right, represent:
- Horizontal offset
- Vertical offset
- Blur radius
- Spread radius
- Color and opacity
It’s easier to understand by trying it out using the generator at the top of the page. As you experiment, refer to the following breakdown:
Horizontal Offset
The first value sets how far the shadow is offset horizontally. A positive value moves the shadow to the right; a negative value moves it to the left.
- Example:
10px
→ shadow shifts 10px to the right - Example:
-10px
→ shadow shifts 10px to the left
Vertical Offset
The second value sets the vertical offset of the shadow. A positive value moves it downward, and a negative value moves it upward.
- Example:
10px
→ shadow shifts 10px downward - Example:
-10px
→ shadow shifts 10px upward
Blur Radius
The third value controls the blurriness of the shadow. The higher the value, the more spread out and softer the shadow becomes. A value of 0
results in a sharp shadow.
- Example:
20px
→ blurred shadow - Example:
0px
→ sharp-edged shadow
Spread Radius
The fourth value determines how much the shadow expands or contracts. Positive values make the shadow larger, while negative values shrink it inward.
- Example:
10px
→ shadow spreads out - Example:
-5px
→ shadow contracts inward
Color and Opacity
Finally, the color of the shadow is set. Using the rgba()
function allows you to specify the color along with its opacity (alpha value). Opacity ranges from 0
(fully transparent) to 1
(fully opaque).
- Example:
rgba(0,0,0,0.3)
→ a black shadow with 30% opacity
Q&A About box-shadow
Q: Can units other than px
—like rem
or vw
—be used for the distances?
Yes, but some units may not behave as expected.
Unit | Usable? | Comment |
---|---|---|
px | ✅ Yes | Common and reliable |
rem | ✅ Yes | Easy to manage |
em | ✅ Yes | Affected by parent font size |
% | ⚠️ Not recommended | Often produces strange results |
vw/vh | ⚠️ Not recommended | Can behave unpredictably |
Although %
and vw
aren’t explicitly disallowed, they often produce undesirable effects when used. In most cases, fixed units like px
or rem
are easier to control. em
depends on the font size of the parent, which can make consistent styling harder across a website.
Q: Can the blur radius have a negative value?
No, it can’t. Although the browser won’t crash if you set a negative value like -5px
, it will treat it as 0px
. Negative blur values are not valid.