Selectors define which part(s) of your (X)HTML document will be affected by the declarations you’ve specified. Several types of selectors are available in CSS. Note that some of them are not supported in all browsers.
Element Selectors
The most basic of all selectors is the element selector (you may have heard them called tag selectors). It is simply the name of an (X)HTML element, and—not surprisingly—it selects all of those elements in the document. Let’s look at the example:h1 {color: blue;}
h2 {color: green;}
We’ve used h1
and h2
as selectors. These are element selectors that select h1
and h2
elements within the (X)HTML document, respectively. Each rule indicates that the declarations in the declaration block should be applied to the selected element. So, in the previous example, all h1
elements in the page would be blue and all h2
elements would be green. Simple enough, right?
Class Selectors
So far we’ve been assigning styles exclusively to (X)HTML elements, using element selectors. But there are several other types of selectors, and the class and ID selectors may be next in line as far as usefulness. Modern markup often involves the assigning of classes and IDs to elements. Consider the following:
<h1 class="warning">Be careful!</h1>
<p class="warning">Every 108 minutes, the button must be pushed. Do not attempt to use the computer for anything other than pushing the button.</p>
Here, we’ve specified a class of warning to both the
h1
element and the p
(paragraph) element. This gives us a hook on which we can hang styles that is independent of the element type. In CSS, class selectors are indicated by a class name preceded by a period (.);
for example:.warning {color: red; font-weight: bold;}
This CSS will apply the styles noted in the declaration
(a red, bold font)
to all elements that have the class name warning. In our markup, both the h1 and the p
elements would become red and bold. We can join an element selector with a class selector like this:p.warning {color: red; font-weight: bold;}
This rule will assign the red color and bold weight only to paragraph elements that have been assigned the class warning. It will not apply to other type elements, even if they have the warning class assigned. So, the h1 in our previous markup would be ignored by this style rule, and it would not become red and bold. You can use these rules in combination to save yourself some typing. Take a look at this block of CSS code. We’ve got two style rules, and each has several of the same declarations:
p.warning {
color: red;
font-weight: bold
font-size: 11px;
font-family: Arial;
}
h1.warning {
color: red;
font-weight: bold
font-size: 24px;
font-family: Arial;
}
A more efficient way to write this is
.warning {
color: red;
font-weight: bold
font-size: 11px;
font-family: Arial;
}
h1.warning {
font-size: 24px;
}
Class selectors can also be chained together to target elements that have multiple class names. For example:
<h1 class="warning">Be careful!</h1>
<p class="warning help">Every 108 minutes, the button must be pushed. Do not attempt to use the computer for anything other than pushing the button.</p>
<p class="help">The code is 4-8-15-16-23-42.</p>
A
.warning
selector will target both the h1 and first p
elements, since both have the class value warning. A .help
selector will target both p
elements (both have a class value of help). A chained selector such as .warning.help
will select only the first paragraph, since it is the only element that has both classes (warning and help) assigned to it.ID Selectors
ID selectors are similar to class selectors, but they are prefaced by a pound sign
(#)
instead of a period. So, to select this div element:<div id="main-content">
<p>This is the main content of the page.</p>
</div>
we would need a selector like this:
#main-content {width: 400px;}
or this:
div#main-content {width: 400px;}
ID selectors cannot be chained together, since it is invalid to have more than one ID on a given element in (X)HTML. However, it is possible to chain class selectors and ID selectors, such as
div#main-content.error
.Descendant Selectors
Descendant selectors, sometimes called contextual selectors, allow you to create style rules that are effective only when an element is the descendant of another one. Descendant selectors are indicated by a space between two elements. As an example, you may want to style only
li
elements that are descendants of ul
lists (as opposed, say, to those who are part of ol lists). You’d do so like this:ul li { color: blue; }
This rule will make
li
text blue—but only when the li
is contained within a ul
element. So, in the following code, all li
elements would be blue:<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
<li>Item four has a nested list
<ol>
<li>Sub-item one</li>
<li>Sub-item two</li>
</ol>
</li>
</ul>
Even though the nested list in item four is an
ol
element, the blue color will still be applied to its list items because they are the descendants of a ul
. Descendant selectors can be useful in targeting items deep in your (X)HTML structure, even when they don’t have an ID or class assigned to them. By stringing together many elements, you can target strong elements inside cite elements inside blockquote elements inside div elements:div blockquote cite strong {color: orange;}
You can combine these with your class and ID selectors to get even more specific. Perhaps we want only
li
elements in ul
elements with a class of ingredients inside our div with the id value recipes:div#recipes ul.ingredients li {font-size 10px;}
As you can imagine, descendant selectors are powerful, and it’s no coincidence that descendant selectors are among the most-used types of CSS selectors.
Child Selectors
Child selectors are similar to descendant selectors, but they select only children rather than all ancestors. Child selectors are indicated by a greater-than sign
(>)
.Consider our example markup from earlier:
<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
<li>Item four has a nested list
<ol>
<li>Sub-item one</li>
<li>Sub-item two</li>
</ol>
</li>
</ul>
Whereas our descendant selector,
ul li {color: blue;}
, targeted all li
elements in this example, a similar child selector would only select the first four li
elements, as they are direct children of a ul
element:ul > li {color: blue}
It would not target those
li
elements in item four’s nested ol list.Adjacent Sibling Selectors
Adjacent sibling selectors allow you to target an element that immediately follows—and that has the same parent as—another element.
The concept of adjacent sibling selectors may sound a bit convoluted at first, but consider this example:
<body>
<h1>This is a header</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
Paragraphs, by default, have a margin of 1 em above and below them. A common style effect is to remove the top margin of a paragraph when it is immediately after a header. The adjacent sibling selector, which is indicated by a plus sign
(+)
, solves this problem for you:h1 + p {margin-top: 0;}
Although this is incredibly useful in theory, it’s not so useful in the real world. Internet Explorer version 6 and older doesn’t support this selector (Internet Explorer 7 does offer support for it, though). Including it in your styles doesn’t hurt anything—IE will simply ignore it. But those visitors using IE won’t see your adjacent sibling style rules, either. This selector doesn’t do a lot for you in the real world at the time of this writing, but it’s still smart to be aware of it, as someday it will come in handy.
Attribute Selectors
This selector, which is indicated by square brackets
([])
, allows you to target elements based on their attributes. You can select elements based on the presence of• An attribute in an element
• An exact attribute value within an element
• A partial attribute value within an element (for example, as a part of a URL)
• A particular attribute name and value combination (or part thereof) in an element
Particular Attribute Selector
Perhaps better named the “equal to or starts with” attribute selector, the partial attribute selector—with its pipe-equal
(|=)
syntax—matches attribute values that either match exactly or begin with the given text. For example:img[src|="vacation"] {float: left;}
would target any image whose src value begins with vacation. It would match
vacation/photo1.jpg
and vacation1.jpg
, but not /vacation/photo1.jpg.
Attribute selectors, like adjacent sibling selectors, would be more valuable if Internet Explorer 6 and lower supported them (again, they are supported in IE 7). Since it doesn’t, many web developers are forced to admire them from afar.
Daisy-Chaining Selectors
It’s important to note that all types of selectors can be combined and chained together. For example, take this style rule:
#primary-content div {color: orange}
This code would make for orange-colored text in any div elements that are inside the element with an id value of primary-content. This next rule is a bit more complex:
#primary-content div.story h1 {font-style: italic}
This code would italicize the contents of any h1 elements within divs with the class value story inside any elements with an id value of primary-content. Finally, let’s look at an over-the-top example, to show you just how complicated selectors can get:
#primary-content div.story h1 + ul > li a[href|="http://ourcompany.com"] em { font-weight: bold; }
This code would boldface all
em
elements contained in anchors whose href attribute begins with http://ourcompany.com and are descendants of an li element that is a child of a ul element that is an adjacent sibling of an h1 element that is a descendant of a div with the class named story assigned to it inside any element with an id value of primary-content. Seriously. Read it again, and follow along, right to left.Grouping Selectors
You can also group selectors together to avoid writing the same declaration block over and over again. For example, if all your headers are going to be bold and orange, you could do this:
h1 {
color: orange; font-weight: bold;
}
h2 {
color: orange; font-weight: bold;
}
h3 {
color: orange; font-weight: bold;
}
h4 {
color: orange; font-weight: bold;
}
h5 {
color: orange; font-weight: bold;
}
h6 {
color: orange; font-weight: bold;
}
Or, for more efficiency, you could comma-separate your selectors and attach them all to a single declaration block, like this:
h1, h2, h3, h4, h5, h6 {color: orange; font-weight: bold;}
Obviously this is much more efficient to write, and easier to manage later, if you decide you want all your headers green instead of orange.
Conclusion
CSS selectors range from simple to complex, and can be incredibly powerful when you begin to understand them fully. The key to writing efficient CSS is taking advantage of the hierarchical structure of (X)HTML documents. This involves getting especially friendly with descendant selectors. If you never become comfortable with the more advanced selectors, you’ll find you write the same style rules over and over again, and that you add way more classes and IDs to your markup than is really necessary.
Source: Ebook (Pro CSS Techniques) by Jeff Croft, Ian Lloyd, and Dan Rubin
9 comments :
This is a good refresher on CSS selectors, nice article :)
Very nice post and very well done. CSS Selectors are very important fundamentals when learning CSS. Thank you.
in the Class Selectors section, the first line of sample code has a reversed >
@Anonymous
Error rectified.
thank you! ;)
I'd say that the General Sibling Combinator (h1 ~ p) is a bit more useful than the Adjacent one. It would select all paragraphs next to an h1.
good article Rakesh. do you know if you can do descendant class selectors?
.class1 .class2
doesn't seem to work to select eg a li with class="class2" somewhere in a p with class="class1"
changing the selector to
*.class1 *.class2 doesn't work either
@anonymous
Descendant class selectors work just fine. You might have a problem with the CSS Specificity. In other words, there may be a style with more power over your li
Also, you may consider using markup other than an li inside the paragraph as it technically should be part of an ordered or unordered list.
I find very interesting this subject, thanks for sharing.
Post a Comment