Trusted answers to developer questions

How to set the opacity of a background image using CSS

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Unlike non-background images, setting the opacity of a background image cannot be done by simply setting the opacity property through CSS.

When opting for the opacity property of CSS for an HTML element, what will generally happen is that the opacity of the image in the background will change and the opacity changes will be reflected in its child elements.

Opacity is only to be applied on the background image without affecting any of the children elements.

Method 1: Using absolute positioning and an image

Simply use absolute positioning on a normal img tag to make it seem like the background-image property is being used. The image only needs to be put inside of a position: relative container.

See the example below:

Change the value of the opacity property in the CSS ccode to make sure that only the background image is affected.

Method 2: Using CSS Pseudo-Elements

By using CSS pseudo-elements of either :before or :after, a div is created with a background image and an opacity is set on it.

See the example below:

Change the value of the opacity property in the CSS code to make sure that only the background image is affected.

RELATED TAGS

opacity
image
css
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?