0

Just a quick one if anyone would be so kind. I'm baffled as to why I sometimes need to use an ancestor selector in order to effectively target a CSS class.

For instance, if I'm trying to hide an element with class .mobile-hide in a media query stylesheet:

<div id="container">
    <div id="parent">
        <div id="child1" class="social-icon">Facebook</div>
        <div id="child2" class="social-icon mobile-hide">Twitter (Hide Me)</div>
        <div id="child3" class="social-icon">Instagram</div>
    </div>
</div>

When I use simply:

.mobile-hide { display:none; }

in my stylesheet it does nothing. But when I use:

#container .mobile-hide { display:none; }

it works as expected and I cannot understand why.

j08691
  • 204,283
  • 31
  • 260
  • 272
Ben Clarke
  • 1,189
  • 4
  • 16
  • 30
  • 5
    This information is available elsewhere and is much better described here than any answer anybody can give you: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity – Adam Jenkins Dec 12 '14 at 17:15
  • 1
    Could be the specificity of the rule. Do you have other CSS rules that could be overriding that one? – j08691 Dec 12 '14 at 17:16
  • 1
    Style Precedence in CSS http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/ – Danijel Dec 12 '14 at 17:20
  • Thanks guys. The style precedence / specificity factor was the key here. Adding an `!important` rule solved the problem for me. – Ben Clarke Dec 12 '14 at 18:32
  • 1
    @BenClarke - `!important` is something you should try hard to never have to use in CSS, so this is the wrong way to solve your problem. – Adam Jenkins Dec 12 '14 at 19:53

2 Answers2

1

There is a display style set on .social-icon which is overriding the display for .mobile-hide. If you specify the container for .mobile-hide, then that style will take precedence over .social-icon since it is more specific.

Mike
  • 4,071
  • 21
  • 36
  • Many thanks Mike. Your answer helped me understand what was happening. You were right in that it's initial display style of `display:inline-block` was taking precedence. By adding an `!important` rule after the `display:none` it worked as expected. I know using `!important` is sometimes not recommended, but it seems to be fitting for this scenario. – Ben Clarke Dec 12 '14 at 18:29
0

Likely you have some other styling that has higher precedence in the first case. Precedence is based on specificity.

Here is some further information on the matter that may be useful: In which order are CSS styles applied?

Community
  • 1
  • 1
Roger
  • 10,851
  • 3
  • 26
  • 39
  • Link provided for convenience. According to you simply removing the link makes it answer instead of a comment. If you really want to be nitpicky then you should just mark this as a duplicate. – Roger Dec 12 '14 at 17:23