Is a there a way using CSS to apply styles to a parent element only if the parent has a certain child element?
Here is my HTML:
<div class="Environment">
<div class="col-md-6 interior_environment">
<div class="aboutEnvironment">
<div class="col-sm-12 col-md-12">
<div class="title_environment"></div>
<div class="description_environment">
<p><span>The natural environment or natural world encompasses all living and non-living things occurring naturally, meaning in this case not artificial. The term is most often applied to Earth or some parts of Earth.</span></p>
</div>
</div>
</div>
</div>
</div>
I want add the following CSS(mentioned below) to .Environment
and .interior_environment
only if .aboutEnvironment
class is present inside .Environment .interior_environment
.
If .aboutEnvironment
class is not present inside .Environment .interior_environment
then this CSS should not be added to .Environment
and .interior_environment
.
.Environment
{
display: block;
}
.interior_environment
{
flex: 1;
}
Is there a way to do this using CSS or does it have to be done through JavaScript?
3
Answers
You can achieve this using the following jQuery:
This a simple way to do this. You can also try the more complex way of checking each child or parent but that would be not so clean.
By using the above method, it will return false for the condition if
.aboutEnvironment
is not present inside the other two classes.Remember this will only work if there is only one such element in the page if there are multiple such elements you need to use the child element and parent element feature of jQuery.
loop over
.Environment .interior_environment
and check whether any child has thataboutEnvironment
class or not. Based on that apply the condition.Working snippet:
Yes, There are several other ways please try below one: