Mark Szymanski
Mark Szymanski

Reputation: 58060

Best practice for referring to classes in CSS

If you have an HTML page with a class in an element, for instance <div class="myClass">, would it be best to refer to it in the CSS as .myClass or div.myClass?

Upvotes: 3

Views: 368

Answers (4)

kenny_k
kenny_k

Reputation: 3980

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.

Upvotes: 2

Gert Grenander
Gert Grenander

Reputation: 17084

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. :)

Upvotes: 9

Dwayne Charrington
Dwayne Charrington

Reputation: 6622

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.

Upvotes: 1

Austin Fitzpatrick
Austin Fitzpatrick

Reputation: 7359

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.

Upvotes: 4

Related Questions