I wrote the below html which contains a container and a box class. The box class has a p
tag as a child containing with some text.
.container {
width: 600px;
height: 100px;
background-color: aqua;
}
.container .box {
width: 500px;
height: 80px;
background-color: rgb(227, 243, 199);
}
.box {
width: 400px;
height: 50px;
background-color: coral;
}
<div class="container">
<div class="box">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Suscipit, mollitia.</p>
</div>
</div>
My question is :
Why the box class element is taking properties from .container .box
and not from .box
?
3
Answers
Because the
.container .box
selector is more specific than.box
.You can read more about that here: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
Also, you can check in DevTools by hovering CSS selectors in the
Styles
panel:If you want the styles from
.box
to take precedence over those in.container .box
, you have two options:Add one or more additional classes to the selector (second column in the Specificity calculation).
Note that if you only add one additional class, the specificity in both
.container .box
and.box.coral
(in my example below) is the same ((0,2,0)
), so the one that come latter takes precedence.Alternatively, a single
ID
selector will have a higher specificity ((1,0,0)
):In CSS if you define two selectors with the same properties, the more specific selector will be prioritize. In your case
.container .box
is more specific dans.box
.I recommend you the answers of this question : What is the order of precedence for CSS? and this article Specificity
Either way, the .box class will take the properties of the parent class.Try adding
<span></span>
.You can read more about this at https://ricardometring.com/css-class-inside-other-class.