How to Select Particular Segments for HTML5 and CSS3 Programming

By Andy Harris

Sometimes, you may want to select only particular segments on your HTML5 and CSS3 web page. Take a look at how you should refer to someone who doesn’t appreciate your web development prowess.

Defining more than one kind of paragraph

Apart from its cultural merit, this page is interesting because it has three different paragraph styles. The introductory paragraph is normal. The quote is set in italicized font, and the attribution is monospaced and right-aligned.

The quote in the following code was generated by a great site: the Shakespearean insult generator. Nothing is more satisfying than telling somebody off in iambic pentameter.

image0.jpg

<!DOCTYPE html>
<html lang = "en-US">
 <head>
 <meta charset = "UTF-8">
 <title>quote.html</title>
 <style type = "text/css">
  #quote {
  font: bold italic 130% Garamond, Comic Sans MS, fantasy;
  text-align: center;
  }
  #attribution {
  font: 80% monospace;
  text-align: right;
  }
 </style>
 </head>
 <body>
 <h1>Literature Quote of the Day</h1>
 <p>
  How to tell somebody off the classy way:
 </p>
 <p id = "quote">
  [Thou] leathern-jerkin, crystal-button, knot-pated,
  agate-ring, puke-stocking, caddis-garter, smooth-tongue, Spanish pouch!
 </p>
 <p id = "attribution">
  -William Shakespeare (Henry IV Part I)
 </p>
 </body>
</html>

Styling identified paragraphs

Until now, you’ve used CSS to apply a particular style to an element all across the page. For example, you can add a style to the tag, and that style applies to all the paragraphs on the page.

Sometimes (as in the Shakespeare insult page), you want to give one element more than one style. You can do this by naming each element and using the name in the CSS style sheet. Here’s how it works:

  1. Add an id attribute to each HTML element you want to modify.

    <p id = "attribution">
  2. Make a style in CSS.

    Use a pound sign followed by the element’s ID in CSS to specify you’re not talking about a tag type any more, but a specific element: For example, the CSS code contains the selector #attribution, meaning, “Apply this style to an element with the attribution id.”

     #attribution {
  3. Add the style.

    Create a style for displaying your named element. In this case, you want the paragraph with the attribution ID right-aligned, monospace, and a little smaller than normal. This style will be attached only to the specific element.

      #attribution {
      font: 80% monospace;
      text-align: right;
      }

The ID trick works great on any named element. IDs have to be unique, so this technique is best when you have a style you want to apply to only one element on the page. It doesn’t matter what HTML element it is. If it has the ID quote, the #quote style is applied to it. You can have both ID selectors and ordinary selectors in the same style sheet.