April 2012

Volume 27 Number 04

Web Dev Report - 5 Things Web Developers Need to Know About CSS

By Rachel Appel | April 2012

Because CSS is such a big spec, it’s common to overlook features that can help you cut down on script, style code and HTML, which in turn can make your projects easier to maintain. In this month’s column, I cover five facts about CSS that Web developers often forget to consider.

1. There are more selectors than just id, type and class

Element, class and id selectors are ubiquitous and well known—and included in every Web site. Many Web developers use only these selectors even though CSS has additional ones that allow you to code more precisely, avoiding redundant, nonreusable or hard-to-maintain code. Knowing the full range of CSS selectors lets you choose the ones that will help you reduce the amount of time you spend on tasks that aren’t essential to solving business problems.

Of the many selectors available, attribute selectors allow you to select one or more elements depending on the existence or value of one of the element’s attributes. Attribute selectors are especially valuable when you’re working with HTML form elements such as the ones shown in Figure 1.

input[type="submit"], input[type="button"]  {
    color:#333;
    background:#F5F5F5;
    border:1px solid #999;
    cursor:pointer;
    margin:.2em 0 2em 0;
    padding:.3em 1.8em;
    text-align:center;   
}

Figure 1 Input selectors target different type attributes

Syntactically, the comma separating the input elements in Figure 1 denotes that the rules inside the brackets apply to both submit and regular buttons. In other words, the comma allows you to list multiple elements to which you can apply styles. This is handy for the many times when you need to apply a set of rules to multiple, but not necessarily related, items to avoid duplicating code.

When you need more than a single or simple selector, whether an attribute, id, class or any other selector, you can use a CSS combinator to create complex CSS expressions. Four combinator types are described in Table 1.

Table 1 CSS Combinators

Combinator Syntax Description
Descendant A    B Selector B is a descendant of selector A. Notice that a single whitespace character is part of the syntax.
Child A > B Selector B is a direct child of selector A.
Adjacent/Sibling A + B Selector B is in the same node level as selector A.
General A ~ B Selector B follows selector A, though not necessarily immediately after.

As their name implies, combinators can be combined with selectors to make complex expressions in CSS. Writing expressions that are more complex means that you use less CSS overall because your selectors are much more precise.

2. Reduce script with CSS pseudo elements and classes

Pseudo elements and classes are also a great way to reduce code since they represent elements logically as well as physically. It’s customary to create JavaScript libraries that highlight alternating table rows or perform other UI niceties. Like most developers, you probably use the popular :hover pseudo-class for visual clues on a link’s mouse hover. Nevertheless, you might not know about the many other pseudo-element and pseudo-class features.

Pseudos come in two flavors: element and class. A CSS pseudo-element is a component of a standard HTML element, and a pseudo-class is a dynamic attribute that describes an element’s current state or causes a change of state.

Pseudo-elements map to physical components of an element, like so:

:first-line, :first-letter, :nth-child, :before, :after

Pseudo-classes describe element states and are logical and often dynamic. Here are some examples:

:hover, :active, :not, :first-of-type, :only-child, :empty

Regardless of the specifics of pseudo-elements and pseudo-classes, the syntax and application are essentially the same in both. Although the :hover pseudo-class is logical and dynamic, other pseudos, such as the :first-letter pseudo-element are static. The :first-letter pseudo-element physically styles only the first letter of its applied element before run time, as demonstrated in Figure 2.

p:first-letter {
    color:#990000;
    font-size:2em;
    font-weight:bold;
}

The :first-letter pseudo-element styles the first letter
Figure 2 The :first-letter pseudo-element styles the first letter

To do the same via script, you would need to select an element and then call multiple methods to manipulate the element at run time (e.g., getElementById, substr, and then addClass). Don’t forget that scripting for these types of tasks means you have to maintain the code in the future, and maintaining code that performs only styling detracts from the business rules you need to focus on.

You can review the complete list of pseudo-elements and pseudo-classes at W3C online.

3. Use CSS media queries for cross-platform content delivery

As more and more tablets, laptops, smart phones and other devices become available to the masses, many Web developers are anticipating a painful development experience serving up so many different forms of the same content and media. Fortunately, CSS media queries are a great way to deliver content across platforms and form factors.

Conceptually, CSS media queries are similar to browser feature detection, but instead of determining which features to support per user agent, media queries determine how to present the content based on the consuming user agent. There are also far fewer media types than browser capabilities. However, you can create some complex media query expressions to provide perfectly tailored content for individual users.

You can easily identify a media query in a .css file or <style> tag by searching for @media rules as shown in Figure 3.

@media handheld {
  body
  {
    font-size: 10pt;
    background-color: #5c87b2;   
  }
}
@media screen {
  body { font-size: 18pt }
}
@media screen, print {
  body { line-height: 1.2 }
}

Figure 3 Media queries for handheld, print and screen

As you can see from the selectors in Figure 3, media queries are a way to designate multiple styles for corresponding device types. There are more media types than are explained in Figure 3: all, braille, embossed, handheld, print, projection, screen, speech, tty and tv.

4. CSS is very specific about style

Specificity is an important concept in CSS that lets you avoid a “battle of the styles” between elements. When you’re dealing with external, page-level and inline styles, things can get tricky.  

Fortunately, CSS has a simple rule about style hierarchy: The style rule closest to the element wins, so the browser applies that style to the element. That means that the pecking order for style application is inline styles > page level > style sheet files.

The unordered list featured in Figure 4 and Figure 5 is a great example of CSS inheritance in action. The code in Figure 4 renders an unordered list with a green border, purple background and white text. The children of the list, the list item tags, inherit the background and text color attributes, while some attributes, such as the border attribute, are non-inheritable.

The CSS

ul 
<style type="text/css"> 
 {
    width:150px; 
    border:5px solid #090;  
    background-color:#909;  
    color:#fff;
}
</style>

The HTML

<ul>
    <li>
      List item one
    </li>
    <li>
      List item two
    </li>
    <li>
      List item three
    </li>
</ul>

The results

Each list item inherits colors but not borders
Figure 4 Each list item inherits colors but not borders

Notice that in Figure 4 the border renders around the entire list, not around the individual list items, showing that the list items didn’t inherit that attribute.

Modifying only the CSS by inserting a selector for the <li> element that resets the colors and border creates a completely new look to the list, as illustrated in Figure 5.

The CSS

<style type="text/css"> 
 ul 
{
    width:150px;
    border:1px solid #090;
    background-color:#909;
    color:#fff;
}
li
{
    width:100px;
    border:1px solid #099;
    background-color:#009;
    color:#fff;
}  
</style>

The HTML

<ul>
    <li>
      List item one
    </li>
    <li>
      List item two
    </li>
    <li>
      List item three
    </li>
</ul>

The results

Inheritance and specificity in action
Figure 5 Inheritance and specificity in action

The combination of the element widths and background colors in Figure 5 demonstrates that the style specific to the child list items is the one that the browser uses.

CSS specificity enables you to determine when and to which element you should apply your styles, while taking advantage of inheritance and the wide application of styles to children elements without requiring you to create rules particularly for that purpose.

5. Level the playing field with CSS resets

Every browser renders elements in its own default way. Because of this, many developers choose to use a CSS reset, a style sheet that resets the common, staple elements to your preferred values.

CSS resets can be part of the main style sheet or on their own in a separate .css file, usually named Reset.css. Figure 6 shows a sample CSS reset.

html, body, div, span, applet, object, iframe, 
h1, h2, h3, h4, h5, h6, p, blockquote, pre, 
a, abbr, acronym, address, big, cite, code, 
del, dfn, em, font, img, ins, kbd, q, s, samp, 
small, strike, strong, sub, sup, tt, var, 
dl, dt, dd, ol, ul, li, 
fieldset, form, label, legend, 
table, caption, tbody, tfoot, thead, tr, th, td { 
    margin: 0; 
    padding: 0; 
    border: 0; 
    outline: 0; 
    font-weight: inherit; 
    font-style: inherit; 
    font-size: 100%; 
    font-family: inherit; 
    vertical-align: baseline; 
}

Figure 6 Sample CSS reset

If you don’t want to do the legwork yourself and create a CSS reset, you can download and modify Normalize CSS on GitHub as an alternative. The important thing about CSS resets is that you’re in control of the style baseline.

Wrapping Up

Knowing more about the features of CSS can make a Web developer’s life easier. Developers love to reduce code, and CSS pseudos and media queries help you do just that, as do selector tricks such as using combinators and advanced expressions. Finally, don’t forget to take advantage of the CSS style hierarachy and to use CSS resets to control the defaults in your Web pages.


Rachel Appel is a developer evangelist at Microsoft New York City. You can reach her via her Web site at http://rachelappel.comor by e-mail at rachel.appel@microsoft.com. *You can also follow her latest updates on Twitter at @rachelappel.*