HTML5 and CSS3 All-in-One For Dummies
Book image
Explore Book Buy On Amazon

Sometimes, you may want a number of elements on your HTML5 and CSS3 based web page to share similar styles. Take a look at this example to see this in action.

image0.jpg

The top three headings all have very similar styles. Creating three different styles would be tedious, so CSS includes a shortcut:

<!DOCTYPE html>
<html lang = "en-US">
 <head>
 <meta charset = "UTF-8">
 <title>multiStyle.html</title>
 <style type = "text/css">
  h1, h2, h3 {
  text-align: center;
  font-family: "Bradley Hand ITC", cursive;
  background-color: yellow;
  }
  h3 {
  font-family: monospace;
  }
 </style>
 </head>
 <body>
 <h1>H1 Heading</h1>
 <h2 id="tab1" >H2 Heading</h2>
 <h3>H3 Heading</h3>
 </body>
</html>

One style element (the one that begins h1, h2, h3) provides all the information for all three heading types. If you include more than one element in a style selector separated by commas, the style applies to all the elements in the list. In this example, the centered cursive font with a yellow background is applied to heading levels 1, 2, and 3 all in the same style.

If you want to make modifications, you can do so. Style rules are applied in order, so you can always start with the general rule and then modify specific elements later in the style if you wish.

If you have multiple elements in a selector rule, it makes a huge difference whether you use commas. If you separate elements with spaces (but no commas), CSS looks for an element nested within another element. If you include commas, CSS applies the rule to all the listed elements.

It's possible to get even more specific about selectors with punctuation. For example, the + selector describes sibling relationship. For example, look at the following rule:

h1+p

This targets only the paragraph that immediately follows a level-one headline. All other paragraphs will be ignored. There are other selectors as well, but the ones mentioned here will suffice for most applications.

You might wonder why developers need so many different kinds of selectors. You can use the tag name for most elements, and just apply a class or ID to any element that requires special attention. That's true, but one goal of CSS is to keep your HTML code as clean as possible. You want to use the structure of the page itself to help you determine the style.

About This Article

This article is from the book:

About the book author:

Andy Harris taught himself programming because it was fun. Today he teaches computer science, game development, and web programming at the university level; is a technology consultant for the state of Indiana; has helped people with disabilities to form their own web development companies; and works with families who wish to teach computing at home.

This article can be found in the category: