How to create a fade-in effect for background images over a specific distance (30rem) from the top using CSS mask-image or pseudo-element overlay techniques.
Problem
Background image extends to bottom of page, but needs to fade in gradually over the first 30rem from the top rather than appearing immediately.
Solution 1: Using mask-image (Recommended)
.your-element {
background-image: url('your-image.jpg');
background-size: cover;
background-position: center;
/* Fade-in mask */
mask-image: linear-gradient(
to bottom,
transparent 0,
black 30rem
);
-webkit-mask-image: linear-gradient(
to bottom,
transparent 0,
black 30rem
);
}
Pros:
- Clean, minimal CSS
- No additional DOM elements
- Good browser support (with -webkit- prefix)
Cons:
- Requires -webkit- prefix for Safari
- Not supported in IE11
Solution 2: Using Pseudo-Element Overlay
.your-element {
position: relative;
background-image: url('your-image.jpg');
background-size: cover;
background-position: center;
}
.your-element::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 30rem;
background: linear-gradient(
to bottom,
white 0%, /* Match page background color */
transparent 100%
);
pointer-events: none; /* Allow clicks through overlay */
z-index: 1; /* Adjust as needed */
}
Pros:
- Broader browser support
- More control over layering
- Easy to adjust overlay color
Cons:
- Requires position: relative on parent
- Adds complexity to DOM
- Must match page background color exactly
- May need z-index management
Key Parameters
- 30rem: Distance over which fade occurs (adjust as needed)
- transparent → black: For mask-image (black = fully visible)
- white → transparent: For overlay (match your page background)
- pointer-events: none: Ensures overlay doesn’t block interactions
Browser Compatibility
- mask-image: Modern browsers + Safari (with -webkit-)
- Pseudo-element: All browsers including IE11
Usage Notes
Choose mask-image for cleaner code when browser support allows. Use pseudo-element when you need IE11 support or have complex layering requirements.
