omg
omg

Reputation: 139872

when to leave space ,when not in CSS?

This is ok(without space):

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

This will not work(with space):

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

Why?

Upvotes: 4

Views: 215

Answers (7)

Pim Jager
Pim Jager

Reputation: 32119

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.

Upvotes: 1

David Thomas
David Thomas

Reputation: 253318

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.

Upvotes: 10

John Kugelman
John Kugelman

Reputation: 361645

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>

Upvotes: 2

Aduljr
Aduljr

Reputation: 214

spacing is meant to call different elements and not items related to one element. for example .highlight is not a separate element. While calling div table are all seperate elements

Upvotes: 2

PatrikAkerstrand
PatrikAkerstrand

Reputation: 45721

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

Upvotes: 2

Kees de Kooter
Kees de Kooter

Reputation: 7195

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.

Upvotes: 1

jimyi
jimyi

Reputation: 31191

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>

Upvotes: 3

Related Questions