What exactly is the element.class selector?

Asked

Viewed 233 times

5

I was developing and one thing caught my attention: the rule elemento .classe is different from elemento.classe.

I realized that the main difference is that the first one could be read like this: "Element that has a child with class classe" and the second: "Element containing the class classe". I’d like an explanation about that second, that’s right?

1 answer

7


In a brief explanation;

The elemento .classe equivalent there is elemento *.classe, empty is "abbreviated" use of the asterisk *, which serves to apply CSS to all elements, for example:

  • * {} style any html element of the page
  • html > * apply to the children of <html>, for example <head> and <body>, do not affect the "grandchildren"
  • *.exemplo or .exemplo affect all elements having the attribute class with the value exemplo separated by other space, for example:

    <div class="test exemplo abc"></div>
    
  • div *.exemplo will affect any element within a <div> who owns the class:

    <div>
        <span class="test exemplo">test</span>
    </div>
    
    <div>
        <p>
           <span class="test exemplo">test</span>
        </p>
    </div>
    

Already the elemento.classe is similar to the previous, but with a specific element:

For example, span.test, will affect only the spans:

div span.exemplo {
    color: red;
}
<div>
    <p>
       <span class="test exemplo">Será afetado</span><br>
       <strong class="test exemplo">Não será afetado</strong><br>
       <sub class="test exemplo">Não será afetado</sub><br>
       <span class="test exemplo">Será afetado</span>
    </p>
</div>

Denying some elements

If you want any element to use a CSS rule, minus the sub for example, you can use the :not(), for example:

#main *.test:not(sub) {
    color: red;
}
<div id="main">
    <p>
       <span class="test exemplo">Será afetado</span><br>
       <strong class="test exemplo">Será afetado</strong><br>
       <sub class="test exemplo">Não erá afetado</sub><br>
    </p>
</div>

Read more on:

  • 1

    Excellent answer, took all the doubts I had, thank you :)

  • Thank you @Rafaelalmeida!

Browser other questions tagged

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