Fizzix
Fizzix

Reputation: 24375

Is it necessary to have a CSS selector of an ID within an ID?

For the purpose of this demo, I'll use a StackOverflow element for credibility.

If you sign out of SO, you can see a large call to action box at the top of the page. Even easier, just go to their new Portuguese version here - https://pt.stackoverflow.com/

Once you see the call to action box (captured below) go ahead and inspect it with developer tools.

enter image description here

On the div with the ID of hero-content, you will notice a style that I have pasted below:

#herobox #hero-content {
   background: #fff7d8;
   border: none;
}

I have done some research and as we all know, div ID's should be unique to the page. Although, if they are unique, why would a selector need to state an ID within an ID?

Upvotes: 2

Views: 62

Answers (2)

Quentin
Quentin

Reputation: 943579

There are a couple of reasons.

Stylesheets can be reused between HTML documents. You may wish to distinguish between #hero-content that is a descendant of #herobox one page and of #somethingelse on another page.

The more likely one in this case is specificity. Assuming, for example, that #hero-content is a <div>, a general rule to set the styling of #herobox div would be more specific that #herobox #hero-content. Adding an extra id selector would increase the specificity.

Upvotes: 3

alex
alex

Reputation: 490263

It might be simply to increase the specificity of that selector.

For example, the author may have wanted to override...

#hero-content { border: 2px solid #333; }

It could also be a side effect of a tool like LESS, where the author may have originally written...

#herobox {
    // Lots of other CSS.
    #hero-content {
        // ... 
    }
    // Lots of other CSS.
}

Upvotes: 2

Related Questions