开发者

Best practice for referring to classes in CSS

If you have an HTML page with a class in an elemen开发者_运维技巧t, for instance <div class="myClass">, would it be best to refer to it in the CSS as .myClass or div.myClass?


div.myClass makes the style declaration more specific. In other words, it takes higher priority. So, it's sometimes a good thing to specify it in order to avoid CSS conflicts when you've got many developers onboard a project and people add classes like there's no tomorrow. In other words, if you've got Bob adding:

.myClass {
  color: red;
}

and Sarah adds:

div.myClass {
  color: blue;
}

Sarah's class will trump Bob's class when you've got:

<div class="myClass">Sarah FTW</div>

You can get make it even more specific by specifying it with the ID, but that's sort of outside the scope of your question. :)


Unless you're going to give something (a non-div) the class "myClass" and style it differently, you should just go with .myClass.

For example, if all .error are color:red, but div.error are background:red as well, you may set up the file to include styles for both .error and div.error.


I believe it's best to never broaden the scope beyond what your intentions are - use div.myClass if you're only going to apply this class to div's. This has at least 2 benefits:

  • If you use .myClass, and then accidentally create a.myClass, you'll have your .myClass styles applied to all links of class myClass, causing you unnecessary debugging headaches.
  • Your CSS will be much more readable. You, or someone else looking over it will be able to see that myClass is applied to divs, and won't have to painstakingly search through every HTML document to see what it's used for.


Using div.myClass would be slower performance wise as opposed to just going .myClass. Always target an element directly when possible, this applies to everything. Rather than obtaining the parent element and then using that to target child elements which will impact performance always use ID's and classes when possible.

CSS performance isn't really something most web developers take into consideration, which is a shame because badly written CSS can easily lock up a web browser and cause all kinds of issues for the end-user.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜