1

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 ?

enter image description here

j08691
  • 204,283
  • 31
  • 260
  • 272

3 Answers3

2

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:

enter image description here

enter image description here

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>
Danziger
  • 19,628
  • 4
  • 53
  • 83
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

Nozomi
  • 56
  • 4
-2

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.