When to leave space, not CSS?

This is normal (no space):

li.highlight{ background:#FF9900 none repeat scroll 0 0; } 

This will not work (with a space):

 li .highlight{ background:#FF9900 none repeat scroll 0 0; } 

Why?

+4
source share
7 answers

The last selector will not work, because space implies a connection (in this case, a descendant) between the selectors.

 li.highlight /* defines an element of 'li' with a classname of 'highlight' */ li .highlight /* defines an element of class 'highlight' that contained within an li element */ li > .highlight /* as pointed out by Neil (in comments), this would select an element of class highlight that is an immediate child/descendant of an li */ 

I have to explain that my use of the phrase β€œwill not work”. Obviously, I used your wording, and I did it by mistake.

It will work, it just selects - explained in the commentary - an element that you do not have in your markup.

+10
source

First example:

 <li class="highlight">this will be highlighted</li> 

Second example:

 <li class="highlight"> <span class="highlight">this will be higlighted</span> <span>this won't be.</span> </li> 
+3
source

Since space (in the selector) means going down the DOM to find the appropriate tags, like so:

  • li.highlight
    • So Find a list item with a distinguished class name and apply this style
  • li.highlight
    • Means Find any element with the name of the class that is the ancestor of the list element and apply this style
+2
source

An interval is designed to call different elements, not elements associated with a single element. e.g. .Highlight is not a separate item. When a div table is called, all individual elements

+2
source

You can think of li .highlight as implied * in it. This is equivalent to li *.highlight .

  • li.highlight corresponds to the li element with the highlight class: <li class="highlight"> .
  • li .highlight with a space corresponds to an element with the highlight class that is inside li (child): for example, span in <li><strong>OMG <span class="highlight">NO WAY!</span></li>
+2
source

Without a space, you select li with a class highlight. With sapce, you select descandant li, where the child has class highlighting.

+1
source

In the first case, you select all the li tags with the "highlight" class. In the second case, you select child tags li with the class "highlight".

You should read the CSS selector in the W3C specification .

+1
source

Source: https://habr.com/ru/post/1286711/


All Articles