Home > Web Front-end > CSS Tutorial > Why Do Child Elements Inherit Opacity From Their Parent, and How Can I Prevent It?

Why Do Child Elements Inherit Opacity From Their Parent, and How Can I Prevent It?

Mary-Kate Olsen
Release: 2024-10-28 04:23:30
Original
752 people have browsed it

Why Do Child Elements Inherit Opacity From Their Parent, and How Can I Prevent It?

Resolving Opacity Inheritance for Child Elements

When applying opacity to a parent element, you may encounter the issue of child elements inheriting this opacity. This can be undesirable if you wish for the child elements to maintain their original opacity.

Contrary to the typical assumption, this issue is not solely due to inheritance. Instead, it stems from the manner in which opacity is calculated. Consider the following example:

<div id="parent">
    <div></div>
</div>

<div id="original"></div>

<div id="quarter"></div>

#parent div, #quarter {
    width: 100px;
    height: 100px;
    background-color: orange;
}

#parent div {
    opacity: 0.5;
}

#parent {
    opacity: 0.5;
}

#quarter {
    opacity: 0.25;
}
Copy after login

While it may appear that #quarter's opacity is equivalent to #parent div's, #parent div actually has twice the opacity of #quarter. This is evident in the following fiddle: https://jsfiddle.net/HUaNm/.

Solution

The only true solution to this issue is to physically move the child element outside of the parent. Alternatively, you could consider employing rgba colors for the parent's background, border, or font instead of opacity, although the effect will differ.

The above is the detailed content of Why Do Child Elements Inherit Opacity From Their Parent, and How Can I Prevent It?. 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