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
?
Thanks in advance!
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
?
Thanks in advance!
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
.
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.
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. :)
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: