Home > Web Front-end > CSS Tutorial > Can CSS Combine Background Image and Opacity in a Single Property?

Can CSS Combine Background Image and Opacity in a Single Property?

DDD
Release: 2024-12-16 19:54:12
Original
681 people have browsed it

Can CSS Combine Background Image and Opacity in a Single Property?

Can Background Images and Opacity Be Set in One Property?

CSS allows you to set background transparency and background images separately, but how do you achieve a transparent background image?

Example Scenario:

Consider an image that would be visually overwhelming as a background if used at full opacity. You want to reduce its opacity to around 0.2 for a more subtle effect.

Traditional Approach:

Using the background-image property alone won't adjust the image's transparency.

#main {
    background-image: url(/wp-content/uploads/2010/11/tandem.jpg); 
}
Copy after login

Solution: Pseudo-Element Hack

To create a transparent background image, utilize a pseudo-element:

#main {
    position: relative;
}
#main:after {
    content : "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    background-image: url(/wp-content/uploads/2010/11/tandem.jpg); 
    width: 100%;
    height: 100%;
    opacity : 0.2;
    z-index: -1;
}
Copy after login

Explanation:

  • The :after pseudo-element creates a new element within the #main div.
  • It has no content (content: ""), so it's not visually apparent.
  • It is absolutely positioned at the top left of #main and covers its entire area.
  • The reduced opacity of 0.2 makes the background image transparent.
  • The z-index of -1 places the image behind the content in #main.

The above is the detailed content of Can CSS Combine Background Image and Opacity in a Single Property?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template