Home > Web Front-end > CSS Tutorial > How Can I Create Transparent Background Images with Opacity Control in CSS?

How Can I Create Transparent Background Images with Opacity Control in CSS?

Susan Sarandon
Release: 2024-12-27 18:48:15
Original
244 people have browsed it

How Can I Create Transparent Background Images with Opacity Control in CSS?

Transparent Background Images with Opacity Control

In CSS, setting a background image and adjusting its opacity are separate tasks. However, it is possible to combine these two to create a transparent background image.

Setting Background Image and Opacity

To set a background image, use the background-image property with a valid image URL. For example:

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

To specify the opacity of the background image, use the opacity property. The value ranges from 0 (fully transparent) to 1 (fully opaque).

However, directly applying opacity to the background-image property only affects the image, not the background itself. To achieve a transparent background image, we need an additional step.

Creating a Transparent Background Layer

To create a transparent layer over the background image, use the following CSS:

#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

In this CSS:

  • #main:after creates a pseudo-element that will be the transparent layer.
  • position: absolute places the layer over the main element.
  • opacity: 0.2 sets the layer's opacity to 20%.
  • z-index: -1 ensures that the layer is behind the main element's content.

By combining these CSS techniques, you can create transparent background images with precise opacity control.

The above is the detailed content of How Can I Create Transparent Background Images with Opacity Control in CSS?. 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