2

Here is the CSS:

.parent div {
height: 25px;
width: 25%;
}

.child {
width: 50% !important;
height: 50px !important;
}

Here is the HTML:

<body>
<div class="parent">
    <div class="child">
        <p>CHILD</p>
    </div>
</div>
</body>

Browsers execute CSS from top to bottom. I read about CSS hyerarchy, and according to it, as I specificate the class it should apply its code. Anyway, it applies the .parent div code.. What am I getting wrong?

4 Answers4

2

Be more specific with your css and remove all your !importants:

.parent div.child {
    width: 50%;
    height: 50px;
}

should work just fine

Jack
  • 3,271
  • 11
  • 48
  • 57
1

You are using .parent div, that means it will apply the styling on all divs nested inside the .parent class

<div class="parent">
  <p>This will not be affected as it's not div tag</p>
  <span>This will not be affected as it's not div tag</span>
  <div>This will be affected</div>
  <div class="child">This affects also</div>
</div>

That's why it apply the styles of .child class with !important only, cause you have to override child class.

Here are some variations you could use:

.parent {
  height: 25px;
  width: 25%;
}

.child {
  width: 50%;
  height: 50px;
}
.parent {
  height: 25px;
  width: 25%;
}

.parent .child {
  width: 50%;
  height: 50px;
}
aspirinemaga
  • 3,753
  • 10
  • 52
  • 95
1

!important is used to essentially override any other CSS rules which may be also applicable to the elements where the !important is being applied.This can ensure that no other css rules which affect the same attributes are applied thus ensuring that the style marked !important is the one that applies.

As other have stated the reason for the your issue stems from your application of css selectors & combinators

More reading: https://www.w3schools.com/css/css_combinators.asp

d0rf47
  • 409
  • 8
  • 20
1

.parent div has higher specificity than .child.

However, if you used .parent .child instead of just .child, then that has higher specificity that .parent div, so you do not need to add !important, like so:

.parent .child {
   width: 50%;
   height: 50px;
}

Some helpful readings on CSS specificity:

Frank Fajardo
  • 7,034
  • 1
  • 29
  • 47