Using Different Selectors to Apply Styles






Using Different Selectors to Apply Styles

Problem

You want to use selectors to apply unique styles to different parts of a web page.

Solution

Use different kinds of selectors to target different portions of web pages that you want to style (see Figure):

<html>
 <head>
  <title>CSS Cookbook</title>
  <style type="text/css">
  <!--
  * {
   font-family: verdana, arial, sans-serif;
  }
   h1 {
   font-size: 120%;
  }
  #navigation {
   border: 1px solid black;
   padding: 40px;
  }
  li a {
   text-decoration: none;
  }
  p {
   font-size: 90%;
  }
  -->
  </style>  
 </head>
 <body>
  <h1>Title of Page</h1>
  <p>This is a sample paragraph with a 
<a href="http://csscookbook.com">link</a>. Lorem ipsum dolor sit amet, 
consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut 
laoreet dolore magna <em class="warning">aliquam erat volutpat</em>. Ut 
wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit 
lobortis nisl ut aliquip ex ea commodo consequat.<p>
   <ul id="navigation">
    <li><a href="http://csscookbook.com">Apples</a></li>
    <li><a href="http://csscookbook.com">Bananas</a></li>
    <li><a href="http://csscookbook.com">Cherries</a></li>
   </ul>
 </body>
</html>

Web page with CSS styles


Discussion

CSS allows for many, and sometimes ingenious, ways to pinpoint which elements of a web page should be styled.

To better understand how to select portions of a web page to use selectors, a developer needs to recognize that content marked up with HTML creates a structure. Although the elements used in an HTML may look like the jumbled order shown in Figure, there is a structure.

Elements used in the solution


This structure may be invisible to the visitor visiting the web page, but it's a crucial part of the rendering process that a browser goes through.

When a browser pulls a web page from the server and begins to display the page, the elements of the page are placed in a structure that is assembled by the browser software. Although this process of placing the elements in an organizational structure is more programming oriented, a good visual representation would be to view the structure much like an organizational chart at a company.

Using the HTML in the solution, Figure shows what the organizational chart would look like.

Elements used in the web page arranged in a top-down structure


Type selectors

Type selectors are selectors that name the element or HTML tag to style. The following rules would apply font styles to the h1 and p elements within a web page (see Figure):

h1 {
 font-size: 120%;
}
p {
 color: blue;
}  

The elements selected from the CSS rules


Note that some elements inherit their parent's property values. For example, the text in the paragraph is set to blue, as is the em element.


Class selectors

When you want to apply the same CSS rule many times to different elements, use the class selector.

For example, class selectors can be used to identify warnings with red color in a paragraph, as well as in a list item.

First, create a warning class selector preceded with a period, ".", which is also known as full stop:

<html>
 <head>
  <title>CSS Cookbook</title>
  <style type="text/css">
  <!--
  * {
   font-family: verdana, arial, sans-serif;
  }
  body {
  }
  h1 {
   font-size: 120%;
  }
  #navigation {
   border: 1px solid black;
   padding: 40px;
  }
  li a {
   text-decoration: none;
  }
  p {
   font-size: 90%;
  }
  .warning {
   font-weight: bold;
  }
  -->
  </style>
 </head>
 <body>
  <h1>Title of Page</h1>
  <p>This is a sample paragraph with a 
<a href="http://csscookbook.com">link</a>. Lorem ipsum dolor sit amet,
consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt
ut laoreet dolore magna <em class="warning">aliquam erat volutpat</em>. 
Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit 
lobortis nisl ut aliquip ex ea commodo consequat.<p>
   <ul id="navigation">
    <li><a href="http://csscookbook.com">Apples</a></li>
    <li><a href="http://csscookbook.com">Bananas</a></li>
    <li><a href="http://csscookbook.com">Cherries</a></li>
   </ul>
 </body>
</html>

Then add the class attribute to a link and a list item to style those elements, as you see in Figure:

<html>
 <head>
  <title>CSS Cookbook</title>
  <style type="text/css">
  <!--
  * {
   font-family: verdana, arial, sans-serif;
  }
h1 {
   font-size: 120%;
  }
  #navigation {
   border: 1px solid black;
   padding: 40px;
  }
  li a {
   text-decoration: none;
  }
  p {
   font-size: 90%;
  }
  .warning {
   font-weight: bold;
  }
  -->
  </style>
 </head>
 <body>
  <h1>Title of Page</h1>
  <p>This is a sample paragraph with a 
<a href="http://csscookbook.com" class="warning">link</a>. Lorem ipsum dolor 
sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt 
ut laoreet dolore magna <em class="warning">aliquam erat volutpat</em>. Ut wisi 
enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis 
nisl ut aliquip ex ea commodo consequat.<p>
   <ul id="navigation">
    <li class="warning"><a href="http://csscookbook.com">Apples</a></li>
    <li><a href="http://csscookbook.com">Bananas</a></li>
    <li><a href="http://csscookbook.com">Cherries</a></li>
   </ul>
 </body>
</html>  

The modified CSS rules on the web page


Look at these selectors in the structure of the web page; it would look like Figure.

The styled elements within the page structure


ID selectors

ID selectors resemble class selectors except that according to the specification they appear only once in the document. Often they appear in a div, but they can be used elsewhere. To create an ID selector, use the hash, "#", and then immediately place a label or name:

#navigation {
   border: 1px solid black;
   padding: 40px;
  }

Then add an id attribute with the value of navigation (see Figure):

<ul id="navigation">
 <li class="warning"><a href="http://csscookbook.com">Apples</a></li>
 <li><a href="http://csscookbook.com">Bananas</a></li>
 <li><a href="http://csscookbook.com">Cherries</a></li>
</ul>  

The unordered list element is styled


Descendant selectors

Descendant selectors come next in line and override the type and class selector styles. They typically have two elements with the second element being a descendant of the first:

                  li a {
 text-decoration: none;
}

Add the HTML in which a appears within li as you see in Figure:

<ul id="navigation">
 <li class="warning"><a href="http://csscookbook.com">Apples</a></li>
 <li><a href="http://csscookbook.com">Bananas</a></li>
 <li><a href="http://csscookbook.com">Cherries</a></li>
</ul>  

The links within the list items are selected


Child selectors

A child selector means that an element is styled if it is the direct descendant of its parent element. A child selector is signified by right-angled bracket often set between two type selectors as shown here:

p > strong {
  text-decoration: underline;
}

Only the strong element that isn't contained within another element, the p element in this case, is underlined (see Figure):

<div>
 <p>Nothing happens to this part of the sentence because this 
<strong>strong</strong> isn't the direct child of div.</p> 
 However, this <strong>strong</strong> is the child of div. 
Therefore, it receives the style dictated in the CSS rule.
</div>  

The affect of the child selector rule


To see which elements are affected by this CSS rule in an organizational chart, take a look at Figure.

The child selector highlighted in the markup structure


In Figures 1-14 and 1-15, the reason the first strong element is not underlined is because it was placed within the p element. If the direct parent-to-child relationship is not present, then the style won't hold. This is an easy, but powerful, difference between a child selector and descendent selector.

Universal selectors

Universal selectors are represented with an asterisk (*) and apply to all elements (see Figure). In the following code, every element containing HTML text would be styled with a Verdana, Arial, or some other sans-serif font:

* {
 font-family: Verdana, Arial, sans-serif;
} 

Every element gets styled with the universal selector


Adjacent sibling selectors

Adjacent siblings describe the relationship between two elements that are placed side-by-side within the flow of a web page's markup.

An adjacent sibling can be seen by the plus sign as shown here:

li + li {
 font-size: 200%;
}

The effect of this adjacent sibling rule is seen in Figure. Notice that only the second and third list item are styled since the second and third list item are placed side-by-side with another list item.

Adjacent sibling selectors only affect the ordered list because it appears after the unordered list


To see which elements are affected by this CSS rule showcasing adjacent sibling selectors in an organizational chart, take a look at Figure.

Showing which elements are being styled


Note that adjacent sibling selectors are not widely supported in modern browsers, most notably Internet Explorer 6 for Windows. Adjacent sibling selectors are supported in Mozilla, Firefox, Opera 5+, and Safari.


Attribute selectors

Attribute selectors have four ways to find an element that has a matching attribute. Take a look at examples of each option:


[attribute] - Search for matches based on the attribute.

a[href] { 
 text-decoration: none; 
}

Whenever href attribute appears within an a element in the HTML, the link won't have an underline.


[attribute=val] - Search for matches based on the value.

a[href="csscookbook.com"] { 
 text-decoration: none; 
}

Whenever a link that points to csscookbook.com appears in the HTML, the link won't have an underline.


[attribute~=val] - Search for matches that contain the space-separated attribute somewhere in the value.

a[title~="digital"] {
 text-decoration: none; 
}

Whenever "digital" appears in the title attribute of an anchor element, the link won't have an underline.


[attribute|=val] - Search for matches that contain the attribute with a hyphen.

a[href|="digital"] {
 text-decoration: none; 
}

Also, whenever "digital-" appears in the href attribute of an anchor element, the link won't have an underline.

Note that attribute selectors are not widely supported in modern browsers, most notably Internet Explorer 6 for Windows. Attribute selectors are supported in Mozilla, Firefox Opera 5+, and Safari.


Pseudo-classes

You may want to add style to items that aren't based on elements' name, attributes, or content. This example of pseudo-classes creates rollover effects:

a:link {
 color: blue;
}
a:visited {
 color: purple;
}
a:hover {
 color: red;
}
a:active {
 color: gray;
}

In this setup, a basic link appears in blue. As soon as the mouse pointer hovers over the link, it changes to red. During the clicking of the link, the link appears gray. When returning to the page with the link after visiting, the link appears purple.

Three other pseudo-classes include :first-child, :focus, and :lang(n).

Pseudo-elements

With most selectors, a developer makes use of elements and their arrangement within a web document to style a document. However, sometimes a developer can style an item within a web document that's not marked up by elements through the use of pseudo-elements. Pseudo-elements consist of :first-letter, :first-line, :before, and :after.

You can see an example of the following pseudo-element in:first-letter in Figure:

p:first-letter {
 font-size: 200%;
 font-weight: bold;
}  

The first letter is styled


Or you can use :first-line (see Figure) to style the entire first line. If the first line isn't a complete sentence or includes the start of a second sentence, :first-line still only impacts the first line.

The first line is styled


p:first-line {
 font-size: 200%;
 font-weight: bold;
}

See Also

The CSS 2.1 specification for selectors at http://www.w3.org/TR/CSS21/selector.html; Selectutorial, a tutorial of CSS selectors (http://css.maxdesign.com.au/selectutorial/); westciv browser selector support (http://westciv.com/style_master/academy/browser_support/selectors.html) shows the browsers that do and do not support specific selectors; and Appendix C for a listing of selectors.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows