Problem statement

Sometimes when you apply a gradient background to a scrollable div, it seems like nothing happens. For example:

.scroll-region {
    height: 200px;
    overflow: auto;
    background: linear-gradient(135deg, #1e3c72, #2a5298);
}

While a solid colour works perfectly:

.scroll-region {
    height: 200px;
    overflow: auto;
    background-color: #1e3c72;
}

Why this happens

The key reason is how CSS backgrounds behave on scrolling content:

  • background-color is a flat fill of the box, so you never notice where it starts or stops.
  • linear-gradient is a background image. By default it is sized to the element's visible box and stays fixed to it (background-attachment: scroll) while the content scrolls over it.
  • If the container's height isn't set explicitly, a container with little content collapses and the gradient has almost nothing to paint on.

Solution

To make gradients work reliably in scrollable divs:

.scroll-region {
    height: 200px;
    overflow: auto;
    background: linear-gradient(135deg, #1e3c72, #2a5298);
    background-repeat: no-repeat;
    background-size: cover;          /* fill the entire div */
    background-attachment: local;    /* gradient scrolls with the content */
    padding: 1rem;
    color: white;
}

Demo

Scroll both boxes. On the left the gradient stays pinned while the text moves over it. On the right, with background-attachment: local, it covers the whole scrollable area and moves with the content.

Default (scroll)

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero.

Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet.

Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta.

Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent.

background-attachment: local

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero.

Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet.

Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta.

Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent.

Key tips for students

  • Always set a definite height or min-height for gradient containers.
  • Use background-size: cover to fill the container fully.
  • Use background-attachment: local if you want the gradient to scroll with the content.
  • Test with both solid colours and gradients to debug visibility issues.

This approach ensures your scrollable divs always show the gradient as intended, even with overflowing content.

Happy coding! 🚀