可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
It's well known that the id should be unique in html tags, so it can be referenced directly using:
#container
However I noticed that some developer will prefix it with the tag name like this:
div#container
Now is there a difference? Is it related to performance? Or is it best practice conventions? Or for easy code readability?
回答1:
div#container
will ensure you only select the element if it is a div
. Without the type selector, any element with that ID will be targeted. The type selector also adds specificity, but that's a minor thing.
Assuming you're following best practices and making sure your IDs are unique per page, you generally don't need to overqualify your ID selectors; having #container
should be enough. But if you have a very good reason to distinguish the element type, there are no rules preventing you from doing that (although frankly, given the whole nature of IDs, I don't see why the same ID should ever be assigned to different types of elements altogether).
回答2:
The basic difference is that with div#container
you may not target an element although there is an element with id=container
. For example if you have
<div id="container"></div>
then both will point the same element. But if you have
<p id="container"></p>
Then only the selector #container
will target it. The selector div#container
will not
回答3:
The difference between div#container
and #container
is that
#container
will only apply to element that has id="container"
While,
div#container
will only apply to DIV that has an id="container"
Although you it is considered best practice to only use an id once. And if you need to use certain CSS again, might as well use class.
回答4:
In html you may have a lot of other elements, such as span, table, etc, which may have the same id, for example "container". So this code:
#container: {....}
is a reference to all of them.
But when you write this:
div#container: {...}
You refer in a specific subcategory of those items. Also you may have a lot of divs. By this reference above, you target in a specific subcategory of divs elements.
回答5:
Ok I asked this question with a wrong assumptions as follow:
There will be only one HTM page, hence:
There should be only one ID (container)
There will be an internal CSS block for such page
Based on the above wrong assumptions, it's needless to include the tag name.
However, the correct assumptions should be:
You have a website with multiple pages
Although id(container) is unique in every page, however it might be assigned to different elements, e.g. div id="conainer"
in one page. And p id="container"
in another page
most probably there is an external css file or is file that serves all these pages.
Its based on those assumptions the benefit of being more specific prefixing the tag name will prevent abnormal behavior
This is almost the same answer of laaposto