Home >Web Front-end >CSS Tutorial >How Can I Overlay a Gradient on a Background Image in CSS?

How Can I Overlay a Gradient on a Background Image in CSS?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 19:17:15805browse

How Can I Overlay a Gradient on a Background Image in CSS?

Gradient Overlay on Background Image: Unveiling the Solution

The inability to display both a background image and a gradient overlay simultaneously can be frustrating. However, the solution is straightforward and lies in the correct order of elements within your CSS declaration.

To achieve the desired fading effect from black to transparent at the bottom of your background, the following steps are crucial:

  1. Position the background image URL at the end of the line: Contrary to intuition, the URL for the background image should be placed after the gradient declaration, as seen in the corrected code:
.css {
  background: 
   linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%),
   url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;
  height: 200px;
}
  1. Ensure correct syntax: The example code contains valid CSS syntax for the gradient declaration. The multiple color stops are defined within parentheses, and the starting and ending positions of the gradient are specified using percentages.
  2. Provide a height for the container: To ensure the gradient effect is visible, a height must be set for the container element containing the gradient and background image. In the provided code, the ".css" element has a height of 200 pixels.

With these adjustments in place, the gradient overlay will now be displayed correctly on top of the background image, achieving the desired fading effect.

The above is the detailed content of How Can I Overlay a Gradient on a Background Image in CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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