2

I'm trying to target some headers except those within a particular parent element. When I apply the styles below to the (abstracted) HTML below, the font size of both headers is impacted. What do I have wrong with the :not selector?

In this scenario I'm not able to modify the CSS selectors but need to make sure the HTML is crafted such that the selectors work as expected.

:not(#beginning) h4.small {
  font-size: .25rem;
}
<div id="beginning">
  <h4 class="small">Unaffected header</h4>
</div>

<div id="end">
  <h4 class="small">Affected header</h4>
</div>
justinraczak
  • 776
  • 2
  • 9
  • 24

1 Answers1

6

Use :not(#beginning) > h4.small instead. Your h4.small will always be a descendant somewhere within an element that doesn’t have the ID beginning. You want to select h4.small elements that aren’t children of the #beginning element.

:not(#beginning) > h4.small {
  font-size: .25rem;
}
<div id="beginning">
  <h4 class="small">Unaffected header</h4>
</div>

<div id="end">
  <h4 class="small">Affected header</h4>
</div>
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • 1
    I would also recommend using `div:not(#beginning) > h4.small`. From what I understand that would be much more performant as it doesn't have to check the `:not` against every element. – DrCord Sep 18 '19 at 20:56
  • Thanks for the answer. In this context I can't change the CSS selector - I need to work the HTML to work within the selector provided. If I understand your point, the h4.small inside div#beginning would still be affected because that h4 is still within some _other_ element that does not have the id of beginning. Is that right? That being the case, and bearing in mind the constraint on changing the CSS, I'm not sure how to craft an HTML structure that will have the CSS target the second header but not the first. – justinraczak Sep 18 '19 at 22:28
  • @justinraczak There’s no valid HTML to match this selector. Why can’t you change it? Where does it come from? – Sebastian Simon Sep 18 '19 at 22:40
  • It's part of an exercise for a class. I'm given the CSS selectors and need to craft HTML that would be selected by it. I spent an inordinate amount of time trying to figure out how to do it before turning to SO :/ – justinraczak Sep 18 '19 at 22:48
  • 2
    Then the answer is going to be no markup. If your instructor knows what they're teaching. Or they made a mistake and need to change the selector to what's mentioned in this answer. – hungerstar Sep 20 '19 at 17:11