Do you really need to specify the HTML element before the class in the selector of a CSS rule?

Asked

Viewed 93 times

3

I don’t know if that’s true for everyone, but the only element I’m interested in is <div>. For example:

div.classe1 { /*...*/ }

.clase1 { /*...*/ }

What is the difference between the two examples? I can do the same things with both cases.

2 answers

10


The difference is that in the first case, you will only select the divs containing the class classe1, unlike the second example, which will select any element with class classe1.

A brief example:

.exemplo1 {
  color: red;
}

div.exemplo2 {
  color: blue;
}
<span class="exemplo1">Sou um &lt;span&gt; com a classe `exemplo1`;</span>
<div class="exemplo1">Sou uma &lt;div&gt; com a classe `exemplo1`;</div>
<span class="exemplo2">Sou um &lt;span&gt; com a classe `exemplo2`;</span>
<div class="exemplo2">Sou uma &lt;div&gt; com a classe `exemplo2`;</div>

As you can see above, when we do not have an element selector preceding the class, all elements are selected. This no longer happens in the second case (exemplo2), in which only the divs are selected.

For further deepening:

4

If there are elements other than div with the same class, when using the information div.classe1{}, class shall be applied only to the element which is a div, and shall not be applied to other elements (p, span, for example).

I particularly prefer to use div.classe1{}, because when I see the CSS code, I can understand more quickly that that class is being applied to one or more elements that are a div.

In cases where CSS is growing a lot with several classes, I believe it is better. If you are going to use this class in just one div, it would be better to create one id for the div, and use the rule only for her, so:

In HTML:

<div id="minhadiv">Teste</div>

In the CSS:

#minhadiv { .... }

This way you apply the rule directly to the specific div with this id.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.