What exactly is the element.class selector?

5

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

I noticed that the main difference is that the first could be read like this: "Element that has a child with class classe " and the second: "Element that contains class classe ". I would like explanations about this second, is that right?

    
asked by anonymous 11.04.2015 / 22:06

1 answer

7

In a brief explanation;

The elemento .classe is equal to elemento *.classe , the empty is an abbreviated use of the asterisk * , which is used to apply CSS to all elements, for example:

  • * {} applies style to any html element of the page
  • html > * applies to child elements of <html> , for example <head> and <body> , do not affect "grandchildren"
  • *.exemplo or .exemplo affect all elements that have the class attribute with the value exemplo separated by space from another, for example:

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

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

While elemento.classe is similar to the previous one, 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 sub for example, you can use :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 at:

11.04.2015 / 22:17