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).
.container {
width: 600px;
height: 100px;
background-color: aqua;
}
.container .box {
width: 500px;
height: 80px;
background-color: rgb(227, 243, 199);
}
.box.coral {
width: 400px;
height: 50px;
background-color: coral;
}
<div class="container">
<div class="box coral">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Suscipit, mollitia.</p>
</div>
</div>
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)
):
.container {
width: 600px;
height: 100px;
background-color: aqua;
}
.container .box {
width: 500px;
height: 80px;
background-color: rgb(227, 243, 199);
}
#coralBox {
width: 400px;
height: 50px;
background-color: coral;
}
<div class="container">
<div id="coralBox" class="box">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Suscipit, mollitia.</p>
</div>
</div>