Engo Engo - 1 year ago 65
CSS Question

Should I use element.myclass or .myclass in css?

I couldn't find explanation if I should use e.g.

in CSS in order to style my elements.

So, should I use

[p/span/div/h1/etc..].intro {
font-size: 10px;


.intro {
font-size: 10px;


I know the difference between these two, but I don't know which one I need to use.

Answer Source

I would argue this is a specificity question. And as such I would go with .intro before p|span|div.intro. Selectors with higher specificity win out.

.intro has a specificity of 0 0 0 1.

p.intro has a specificity of 0 0 1 1, which is higher than .intro.

Let's say .intro is:

.intro {
    color: green;

So any element with .intro will have green text. But you want all paragraphs to have orange text. You can create a new class like .p-intro or you can do:

p.intro {
    color: orange;

Which does increase specificity slightly over .p-intro but the one "big" benefit is that you don't have to go through all the markup to add/remove .p-intro to all paragraphs. By adding p to .intro in your CSS you have updated a whole site in one stroke.

I always try to use CSS selectors with the lowest specificity to get the job done. That way, later on, it's easier to update/extend the existing styles when the inevitable changes come about.

Note: See other answers for other benefits.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download