What is the difference between "element element" and "element>element" selectors?

Asked

Viewed 830 times

35

I was looking at the code of Twitter Bootstrap, and found this CSS:

.table-condensed > tfoot > tr > td {
  /* ... */
}

In the sense of functioning, what would be the difference of placing only one space between the elements, and placing the >?

1 answer

51


element element { ...

The space between two CSS elements is the descending selector.
Descendant is any element that is declared inside another.

element > element { ...

The > between two elements of css is the child selector.
Son is also descendant, but is the "direct descendant" specifically. That is, it is directly inserted in the previous element.

In practice:

When you write div span { ... }, you’re saying any span descending (within) of div, and acting in the span in the two cases below:

<div><span> bla bla </span></div>
<div><a><span> bla bla </span></a></div>

Now, when you use div > span { ... }, will affect only children of div, like this:

<div><span> bla bla </span></div>

The attributes will not be applied at other levels of descent, as in this case:

<div><a><span> bla bla </span></a></div>

Reason: the <span> in the latter case is "grandson" of <div>, that is, is descendant but is not son, because the son is the <a>.

See the example below:

div span {
  text-decoration: underline
}

div>span {
  color: red
}
<div>
  Div 1
  <span> Span 1 </span>
</div>
<div>
  <a>
    Div 2
    <span> Span 2 </span>
  </a>
</div>
<div>
  <a>
    Div 3
    <span> Span 3 </span>
  </a>
  <span> Span 4 </span>
</div>

<br>Notar que o sublinhado ficou em todos os spans, mas o vermelho somente quando o span é filho (descendente de primeiro nível) do div

Browser other questions tagged

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