13 June 2011
You should have a good understanding of HTML and know the basics of CSS, such as how to create a style rule and the role of CSS properties.
Intermediate
Note: You don't need specific software to write CSS. Any text editor will do. However, the code hints and the ability to see the results of your style rules in Live view make Dreamweaver CS5.5 a good choice. You should also download the sample files to test the examples in a variety of browsers.
Using cascading style sheets (CSS) is now widely accepted as the correct way to lay out and style web pages. One of the secrets of success with CSS is knowing which selectors to use. There's more than just classes and IDs. In fact, CSS3 defines nearly 40 selectors, allowing you to target styles accurately without the need to clog up your HTML markup with unnecessary classes. The latest versions of browsers, including Internet Explorer (IE) 9, support all CSS3 selectors. Older browsers, including IE 7 and IE 8, support a handful of extremely useful CSS3 selectors, plus most—if not all—CSS2.1 selectors.
The only browser with limited support for selectors is IE 6. So, unless you have an obligation to continue supporting IE 6, you can start expanding the range of selectors in your CSS right away. Even if you don't use the new selectors in your style sheets, you'll find them invaluable in jQuery, which uses standard CSS syntax to select elements and add dynamic features to them with JavaScript.
In Part 1 of this two-part tutorial series, you'll learn about the most widely supported CSS selectors. Part 2 will cover advanced selectors that require the most recent browser versions.
With nearly 40 selectors in CSS3, there's a danger of being spoiled for choice. But most of the new selectors are easy to understand. For example, the :first-of-type and :last-of-type pseudo-classes make it easy to add specific styles to the first or last paragraph or list item. Several new pseudo-classes make it possible to style elements dependent on their position in a series. Let's say you want to apply a different background color to alternate rows in a table. Just use tr:nth-child(odd) as your selector. It not only selects each odd row, but it also adjusts the backgrounds automatically if you add an extra row in the middle of the table.
Part 2 of this tutorial series will cover the new pseudo-classes. Before that, let's review the CSS selectors that have been supported by browsers for many years.
The following selectors are supported by all visual browsers, including IE 6:
h1 redefines the default style of <h1> tags, and p redefines the default style of all <p> tags. A particularly efficient use of type selectors is to set the default font and color on the <body> like this:body {
background-color: #EEF2EF;
color: #000;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}
This redefines the font family and text color for every element on the page without the need for classes. You can override these properties in more specific rules. For example, you can change the color and font for headings by grouping type selectors as a comma-separated list like this (other types of selectors can be grouped in the same way):
h1, h2, h3 {
color: #069;
font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif;
}
class attribute in its opening HTML tag. The selector is created by prefixing the class name with a period (dot). For example, the following style rule floats to the left and adds a right margin to any element that has class="floatleft" in its opening tag (it's particularly useful for images):.floatleft {
float: left;
margin-right: 8px;
}
Class names cannot include spaces, and the only punctuation characters permitted are the hyphen (-) and the underscore (_). The name cannot begin with a number or a hyphen immediately followed by a number.
wrapper" in its opening tag to 760 pixels and centers it:#wrapper {
width: 760px;
margin: 0 auto;
}
Note: The same ID should never be used for more than one element in a web page (although you can use it in other pages). Although browsers still apply your styles if you break this rule, reusing the same ID within a page causes problems with JavaScript. If you want to use the same name multiple times, consider using a class instead.
You can achieve a great deal with these basic selectors alone. Figure 1 shows the effect created by the preceding style rules on a simple page (basic_selectors.html in the example files for this tutorial).
In addition to these basic selectors, all visual browsers support link pseudo-classes, the :first-letter and :first-line pseudo-elements, and descendant selectors. The pseudo-classes and pseudo-elements are so called because they apply styles to elements based on their state or position in the document, rather than on how they're marked up in the HTML. You apply a pseudo-class or pseudo-element by appending it to a basic selector. For example, a:link applies the :link pseudo-class to <a> tags, and p:first-letter applies the :first-letter pseudo-element to <p> tags.
Let's take a quick look at each category.
:hover.It's important to use these pseudo-classes in the same order as listed here because they inherit properties from each other. Many web designers use the mnemonic LoVe-HAte to remember the correct order. Because of the way property values are inherited, it's a good idea to create a basic rule for common properties and override those that you want to change like this:
a {
font-weight: bold;
text-decoration: none;
}
a:link {
color: #D04757;
}
a:visited {
color: #DC7B75;
}
a:hover, a:active {
color: #547C7B;
text-decoration: underline;
}
Figure 2 shows the effect of applying these styles (the code is in links.html). The top link is unvisited, the second one is being hovered over, and the third one is a slightly paler shade of pink to indicate that it has been visited.
p:first-line {
font-variant: small-caps;
}
The :first-letter pseudo-element: As the name suggests, this selects the first letter of the specified element without the need to wrap the letter in a <span>. In theory, this is useful for creating drop caps. Unfortunately, browsers are inconsistent in the way they handle the :first-letter pseudo-element. In first-letter.html, there's a style rule that looks like this:
p:first-letter {
font-size:48px;
line-height: 1.2;
padding:2px 10px 2px 10px;
float: left;
margin-right: 5px;
background-color:#069;
color:#fff;
}
In most browsers, this produces a drop cap on each paragraph as shown in Figure 4.
However, Firefox (including version 4) and IE 6 ignore the first paragraph and put a much smaller amount of vertical space above and below the letter, as shown in Figure 5.
The reason for ignoring the first paragraph is presumably because the image is the first element inside the paragraph. It's not a major problem, as long as you remember to test your styles in multiple browsers to ensure the design looks acceptable.
Note: In a real-world situation, you would probably never apply the :first-line and :first-letter pseudo-elements to every paragraph on a page. These examples are purely designed to show how the selectors work. By combining these pseudo-elements with a more advanced selector, you could apply the style to a single paragraph.
<blockquote> element:blockquote p {
font-size: 13px;
}
You can also use descendant selectors to apply different styles to links in a specific part of a page. The following rules apply to links inside an element that has the ID sidebar:
#sidebar a:link {
color: #063;
}
#sidebar a:visited {
color: #0C6;
}
#sidebar a:hover, #sidebar a:active {
color: #F90;
}
Figure 6 displays the effect of these rules (the code is in descendant.html).
Note: Descendant selectors for links inherit properties defined in the main link styles, so there's no need to specify font-weight or text-decoration again. However, the descendant selectors are more specific, which is why the different colors are applied.
IE 7 considerably expanded the range of supported selectors to include not only most CSS2.1 selectors, but also a handful of extremely useful ones that are now part of CSS3. These include child selectors, attribute selectors, and a couple of sibling selectors.
(>) between the selectors for the parent and child elements. For example, the following style rule applies to all paragraphs that are children of an element with the ID sidebar:#sidebar > p {
font-style: italic;
}
Figure 7 shows the difference between using a child selector and a descendant selector. In the screenshot on the left, the child selector in the preceding code block applies italics to only the first and last paragraphs, because they are the only paragraphs that are direct children of the sidebar <div>. The paragraphs inside the <blockquote> are not affected, because they're at a deeper level of the HTML structure (the code is in child.html).
In the screenshot on the right of Figure 7, the greater-than sign has been removed from between #sidebar and p, turning it into a descendant selector, which affects paragraphs at all levels inside the sidebar.
E represents a selector, attr represents the name of the attribute, and val represents the attribute's value.E[attr]: This matches any E element that contains the attr attribute in its opening tag (whatever the value).E[attr=val]: This matches any E element where the attr attribute has the exact value val.E[attr^=val]: This matches any E element where the value of the attr attribute begins with val.E[attr$=val]: This matches any E element where the value of the attr attribute ends with val.E[attr*=val]: This matches any E element where val appears anywhere in the value of the attr attribute.E[attr~=val]: This matches any E element where the value of the attr attribute is a list of space separated values, one of which is exactly equal to val.Because of lack of support in IE 6, attribute selectors have been greatly overlooked, but they can be extremely useful. For example, most form elements use the <input> tag. But if you want to set a specific width for text input fields, using input as a type (tag) selector has a disastrous effect on other form elements. Figure 8 shows what happens when you use the following style rule in a form (the code is in attribute-exact_01.html):
input {
width: 250px;
}
To apply the style only to text input fields, use an attribute selector to match the type attribute with the exact value "text" like this (the code is in attribute-exact_02.html):
input[type=text] {
width: 250px;
}
Note: In most cases, you don't need to enclose the attribute's value in quotes, although it doesn't matter if you do. However, you must use quotes if the value contains spaces or punctuation.
Figure 9 shows the result: the width is applied only to the text fields. The radio buttons and submit button are unaffected.
Using attribute selectors that look for a partial match at the beginning or end of a value allows you to apply different styles to external links and to links that point to particular types of files. The styles in attribute-partial.html contain the following selectors:
a[href^=http] {
background-image:url(images/external_link.png);
background-position:right center;
background-repeat:no-repeat;
padding-right: 15px;
}
a[href$='.pdf'] {
background-image:url(images/pdf_icon.png);
background-position:right center;
background-repeat:no-repeat;
padding-right: 40px;
}
Note: Because .pdf contains punctuation (a period), the value needs to be wrapped in single or double quotes.
The first attribute selector matches "http" at the beginning of an <a> tag's href attribute—in other words, it identifies links to external sites. The second attribute selector matches .pdf at the end of an href attribute, identifying PDF files. These rules automatically add background images as a visual clue to indicate what the user should expect when following a link, as shown in Figure 10.
E[attr|=val]: This matches any E element with the attr attribute that has a value exactly matching val or that begins with val immediately followed by a hyphen.
The main purpose of this attribute selector is to match language codes and subcodes, such as en (English), en-us (American English), en-gb (British English), es-mx (Mexican Spanish), and so on. You're unlikely to need it unless you build multilingual websites.
p {
text-indent: 40px;
margin-top: .25em;
margin-bottom: .25em;
}
The adjacent sibling combinator is used to suppress the indent on paragraphs that that immediately follow headings (see Figure 11).
h1 + p, h2 + p {
text-indent: 0;
}
Note: Nothing can come between the two elements when using the adjacent sibling combinator. If you want to target the first paragraph after a heading, but don't know if any other element is likely to intervene, you need to use the: first-of-type pseudo-class, which is covered in Part 2 this tutorial.
h2 ~ p {
font-style:italic;
}
This italicizes the text in all paragraphs that follow an <h2> heading and are at the same level of the document. As Figure 12 shows, it doesn't matter what comes between the heading and the paragraphs. The style rule affects all paragraphs that are siblings of the <h2> heading.
This isn't the most useful selector, but it demonstrates the level of control that you can gain through a solid understanding of CSS selectors.
:hover pseudo-class works only on links. In IE 7 and all other browsers, it can also be applied to other elements without the need to wrap the element in a link. The code in hover-ie7.html applies a background color to a <blockquote> element like this:blockquote:hover {
background-color:#CCC;
}
Mousing over the <blockquote> in any browser except IE 6 changes its background color to light gray (see Figure 13).
This is a trivial example of using the :hover pseudo-class without a link. In browsers that support CSS3 transforms, you can use it to scale images without the need for JavaScript. There's an example in hover_scale.html in the files for this tutorial. If you view it in the most recent version of any visual browser, you'll see that the #images img:hover style rule scales the image to its full size when you mouse over it (see Figure 14). When you mouse away from an image, it returns to its original size.
If you study the style rules in hover_scale.html, you'll see that different styles are applied to the individual images using attribute selectors, such as img[src$='sushi.jpg'], rather than IDs.
Although most browsers started supporting the full range of CSS3 selectors several years ago, it took until the release of IE 8 in March 2009 for Internet Explorer to finally support the much smaller set in CSS2.1. This section covers the last four selectors to be added by IE 8:
:hover pseudo-class like this (the code is in links_focus.html):a:hover, a:active, a:focus {
color: #547C7B;
text-decoration: underline;
}
Adding the :focus pseudo-class to your link styles like this ensures that the current link is recognizable when someone uses the Tab key to move from link to link.
<div>:
<div lang="fr">
<p>Asseyez-vous là.</p>
</div>
The lang attribute indicates that all the contents of the <div> is in French. The paragraph is italicized using the following style rule:
<div>:
<div lang="fr">
<p>Asseyez-vous là.</p>
</div>
The lang attribute indicates that all the contents of the <div> is in French. The paragraph is italicized using the following style rule:
p:lang(fr) {
font-style: italic;
}
However, the following style rule would not work because the <p> tag doesn't contain the lang attribute:
p[lang|=fr] {
font-style: italic; /* Doesn't work */
}
To italicize the text, you would need to use this:
div[lang|=fr] {
font-style: italic; /* This works */
}
This is because the lang attribute is in the opening <div> tag, and the style rule applies to all elements nested inside. The difference is quite subtle, but you don't need to worry about it unless you're working with multilingual documents.
content property, these pseudo-elements add generated content before or after the element to which they're applied. The content property is extremely versatile. It accepts as its value literal text (in quotes), images using the same url() function as for background-image, and content generated from an attribute in the element's opening tag. To get the value of an attribute, you pass the attribute name to the attr() function. You can also use a combination of all three. The styles in generated_content.html contain the following selector:
a[href^=http]:after {
content: ' (' attr(href) ') ';
color: #000;
font-weight: normal;
}
This combines the :after pseudo-element with an attribute selector that finds external links (ones that begin with http). The value of the content property consists of an opening parenthesis preceded by a space. This is followed by attr(href), which displays the value of the href attribute. Finally, there's a closing parenthesis followed by a space. This results in the URL of the link being displayed in parentheses after the link text (see Figure 15).
That concludes Part 1 of this overview of CSS selectors. In Part 2, you'll learn about the more advanced selectors introduced in CSS3: pseudo-classes and pseudo-elements.
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.
Tutorials and samples |
| 04/23/2012 | Resolution/Compatibility/liquid layout |
|---|---|
| 04/20/2012 | using local/testing server with cs5 inserting images look fine in the split screen but do not show |
| 04/18/2012 | Ap Div help |
| 04/23/2012 | Updating |