简体   繁体   English

是否需要在ID中包含ID的CSS选择器?

[英]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. 出于本演示的目的,我将使用StackOverflow元素来提高可信度。

If you sign out of SO, you can see a large call to action box at the top of the page. 如果您退出SO,则会在页面顶部看到一个大型的号召性用语框。 Even easier, just go to their new Portuguese version here - https://pt.stackoverflow.com/ 甚至更容易,只需在此处转到其新的葡萄牙语版本-https: //pt.stackoverflow.com/

Once you see the call to action box (captured below) go ahead and inspect it with developer tools. 一旦看到号召性用语框(如下所示),请继续使用开发人员工具对其进行检查。

在此处输入图片说明

On the div with the ID of hero-content , you will notice a style that I have pasted below: 在ID为hero-content的div上,您会注意到我在下面粘贴的一种样式:

#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. 我已经进行了一些研究,众所周知,div ID对于该页面应该是唯一的。 Although, if they are unique, why would a selector need to state an ID within an ID? 虽然,如果它们是唯一的,为什么选择器需要在ID中声明ID?

There are a couple of reasons. 有两个原因。

Stylesheets can be reused between HTML documents. 样式表可以在HTML文档之间重用。 You may wish to distinguish between #hero-content that is a descendant of #herobox one page and of #somethingelse on another page. 你不妨来区分#hero-content就是后裔#herobox一个页面和#somethingelse另一页上。

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 . 例如,假设#hero-content<div> ,则设置#herobox div样式的一般规则#herobox #hero-content更具体。 Adding an extra id selector would increase the specificity. 添加额外的id选择器会增加特异性。

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... 这也可能是LESS之类的工具的副作用,在该工具中作者可能最初编写过...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM