Home > Web Front-end > CSS Tutorial > How Can I Make a CSS Gradient Background Stretch to Fit the Entire Browser Window Instead of Repeating?

How Can I Make a CSS Gradient Background Stretch to Fit the Entire Browser Window Instead of Repeating?

Patricia Arquette
Release: 2024-12-26 01:29:14
Original
113 people have browsed it

How Can I Make a CSS Gradient Background Stretch to Fit the Entire Browser Window Instead of Repeating?

Gradient Backgrounds on Body Element: Repeat or Stretch?

In web design, employing CSS gradients for backgrounds can enhance aesthetics. However, when applying a gradient to the body element, a common issue arises—the gradient ceases to stretch, instead repeating itself.

The Question:

Suppose a document's body content measures 300px in height. Setting a gradient background using -webkit-gradient or -moz-linear-gradient results in a gradient that is only 300px tall and repeats endlessly to fill the remaining window space. Is there a solution to have the gradient stretch to fit the window rather than repeating?

The Answer:

To achieve a gradient that stretches to fill the entire window, apply the following CSS:

html {
    height: 100%;
}

body {
    height: 100%;
    margin: 0;
    background-repeat: no-repeat;
    background-attachment: fixed;
}
Copy after login
  • The html element's height is set to 100% to ensure it expands to the entire window height.
  • The body element's height is also set to 100%, causing it to fill the available height within the html element.
  • margin: 0 is added to remove any unwanted spacing around the body.
  • background-repeat: no-repeat prevents the gradient from repeating itself.
  • background-attachment: fixed keeps the gradient in place as the window scrolls.

By implementing these CSS rules, the gradient background on the body element will stretch to fill the entire window height, providing a visually seamless and immersive effect.

The above is the detailed content of How Can I Make a CSS Gradient Background Stretch to Fit the Entire Browser Window Instead of Repeating?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template