when to leave space ,when not in CSS?

前端 未结 7 1117
无人共我
无人共我 2021-01-19 19:04

This is ok(without space):

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

This will not work(with space):

l         


        
相关标签:
7条回答
  • 2021-01-19 19:31

    The latter selector won't work because the space implies the relationship (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's 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 should explain my use of the phrase "won't work." Clearly I used your phrasing, and I did so in error.

    It will work, it's just that it will select -as explained in the comment- an element that you don't have in your markup.

    0 讨论(0)
  • 2021-01-19 19:37

    You can think of li .highlight as having an implied * in it. It is equivalent to li *.highlight.

    • li.highlight matches an li element with a class of highlight: <li class="highlight">.
    • li .highlight with a space matches an element with class highlight which is inside of an li (a descendant): for example, the span in <li><strong>OMG <span class="highlight">NO WAY!</span></li>
    0 讨论(0)
  • 2021-01-19 19:39

    In the first case you select all li tags with class "highlight". In the second case you select children of li tags with class "highlight".

    You should read up on CSS selectors in the W3C specification.

    0 讨论(0)
  • 2021-01-19 19:40

    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>
    
    0 讨论(0)
  • 2021-01-19 19:40

    Without space you are selecting a li with the class highlight. With the sapce you are selecting a descandant of a li, where the descendant has a class highlight.

    0 讨论(0)
  • 2021-01-19 19:42

    Because space (in a selector) means descend down the DOM to find matching tags, so:

    • li.highlight
      • Means Find any list item with the class name highlight and apply this style
    • li .highlight
      • Means Find any element with the class name highlight, who's ancestor is a list item, and apply this style
    0 讨论(0)
提交回复
热议问题