开发者

Why does this CSS ID selector include the element type?

开发者 https://www.devze.com 2022-12-22 10:18 出处:网络
in some CSS code I found out this type of selector div#someid Is开发者_StackOverflow this formally correct?

in some CSS code I found out this type of selector

div#someid
  1. Is开发者_StackOverflow this formally correct?

  2. If the answer to (1) is YES, what's the need for the div selector before the #someid, shouldn't the id be unique in a valid web page?

Thanks!


  1. Yes it's correct.
  2. It might be because it makes the selector more specific. The more specific a selector it is the higher priority it is.


It is fine.

  • The stylesheet might be reused between pages which have the id on different elements
  • The explicit type provides information for the maintainer about the element
  • It makes the selector more specific, e.g. to override #other div.


The answer is they are the same but using the div in front of #id is superfluous and removing it does no harm while leaving it in only takes up space. Some may feel it makes the markup more readable, however, since it identifies the type of element the id is associated with.

I did read, once, that placing the div in front of the id may cause the browser to search through all divs first while just using #id does not but I'd have to look up that reference.


From what I understand, CSS will rank selectors based on how specific the selector is, if two rules apply to the same element,

ie

#someId{
color: black;
}
.someClass{
color: green;
}

And you had this div:

<div id="someId" class="someClass">

Then which wins? (There are rules in place to govern this particular example, I believe the ID would win anyway).

But say you had these rules:

.someClass{
color: black;
}
div.someOtherClass{
color: green;
}

Then I the second rule would trump it, because it's more specific.

However as David pointed out, ID's are generally rated a lot higher, so ID will win a lot of the time.

So there are two reasons I can see for using element#id selector

I) It's to trump some convoluted rule, ie div#canvas>div>div#main>div:last-child>div

II) So you know what element it is referring to, ie if your div had and id of "postcodeContainer" and you were trying to find it in the html file, it might be harder because you have to look at every element (unless you used your IDE's search/find option), where as div#postcodeContainer you know you are looking for a div element.


div#someid - select a div with id someid
#someid - select any type of element with id someid


One reason for having the tag selector is that it assumes some basic CSS, like it's a block tag with zero margins/padding.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号