Space or no space between CSS selectors
CSS, xHTML and JavaScript can become very complicated, especially when code has had numerous, variously skilled developers working on it. To help understand what is going on in ever-growing code, it helps to understand the smallest details. Today my tip will be on spaces and the absence of said spaces in CSS selectors.
Scenario number one
1 2 3 | #content.favorite { font-weight: bold; } |
1 2 3 4 5 6 7 8 9 | <div id="content"> <p>Content</p> </div> <div id="content" class="favorite"> <p>Content</p> </div> <div id="content"> <p>Content</p> </div> |
In the above scenario, there is no space between the id content and the class favorite. These selectors target any element with the ID of content AND a class of favorite. In the HTML example, the second div would be given bold text per the styles.
Scenario number two
1 2 3 | #content .favorite { font-weight: bold; } |
1 2 3 4 5 6 7 8 9 10 11 12 | <div id="content"> <div id="content"> <p>Content</p> <p>Content</p> </div> <p class="favorite">Content</p> <p>Content</p> </div> <div id="content"> <p>Content</p> <p>Content</p> </div> |
In scenario number two, which differs from scenario one by a single space, the selectors target a child of the id content with a class of favorite. In the HTML example, the paragraph with the class favorite would be given a style of bold.
Lots of things can be accomplished by simply deleting the space between certain selectors especially when multiple classes are being used as seen in scenario number three.
Scenario number three
1 2 3 | .content.favorite { font-weight: bold; } |
1 2 3 4 5 6 7 8 9 | <div class="content"> <p>Content</p> </div> <div class="content favorite"> <p>Content</p> </div> <div class="content"> <p>Content</p> </div> |
The CSS in scenario number three gives the children in the div with both the classes content and favorite a style of bold.
For more reading on selectors, check out the very thorough selector page over at the W3C.
Leave a Reply