Do I really need to put the html element before the class in CSS?

1

I do not know if this applies to everyone, but the only element I'm interested in is <div> . For example:

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

.clase1 { /*...*/ }

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

    
asked by anonymous 20.08.2018 / 22:34

2 answers

8

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

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 is no longer the case in the second case ( exemplo2 ), where only div s is selected.

For further deepening:

20.08.2018 / 22:40
3

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

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

In cases where CSS grows with many classes, I think it's better. If you are going to use this class in just one div, it would be better to create a id for the div, and use the rule just for it, like this:

No HTML:

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

In CSS:

#minhadiv { .... }

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

    
20.08.2018 / 22:40