Google

Wednesday, October 31, 2007

CSS Selectors

CHILD SELECTOR

Despite Internet Explorer 6 not supporting the CSS child selector, it's actually been used a lot as a way of hiding CSS commands from Internet Explorer. This is no longer possible as IE7 now understands the child selector. To understand, what is the child selector? Imagine the following HTML structure:

<div><p><span>Text goes here</span></p></div>

In the above example, the <p> is a child of the <div> and the <span> is a grandchild of the <div>. We can make the text in the <span> red by using the following CSS rule:


div span {color: red;}


This basically means that the contents of the <span> will be red, provided that the <span> is nested within a <div>. That <span> could be a child, grandchild, great-grandchild etc. of the <div>.


If we were however to use the following CSS code:


div>span {color: red;}


...Then the text within our <span> wouldn't turn red. This is because we've inserted the child selector between the div and span (the greater than sign), which basically means that our span has to be a child of a div. In the above example, the <span> is a grandchild of the <div>.


So, by using the child selector, we can assign rules to any HTML element that's a child (and not a grandchild) of another element. Let's say for example we want a top margin to be assigned to the first <div> in our body, but not to any others. Without the child selector we would be forced to assign a class or id to this <div> and reference that class or id in our CSS command. Now though, we can reference this <div>, and only this <div>, without the need for a class or id through the CSS:
body>div {margin-top: 10px;}



ADJACENT SELECTOR

The adjacent selector is another extremely useful CSS selector that up until now Internet Explorer hasn't understood. Fortunately, IE7 does understand it. The adjacent selector basically allows you to reference an HTML element that's adjacent to another element:


blockquote+p {margin-top: 0;}


The above CSS code basically says that any paragraph that's preceded by a quote shouldn't have a top margin. This is useful as you may always wish to cite the person making the quote in a paragraph after the quote and may want to get rid of the space between the paragraph and quote.


Another great example of when you may use the adjacent selector is in horizontal lists. Often, you may want to format the first item slightly differently to the other items in the list. So, if you wanted to assign a left border to each navigation item except for the first, you could use this CSS code:


li+li {border-left: 1px solid black;}


This basically means that any <li> that follows another <li> (i.e. all of them except the first) should have a left hand border.

No comments: