Wednesday, February 1, 2012

CSS: The Universal Selector


By Richard York

The universal selector is an asterisk. When used alone, the universal selector tells the CSS interpreter to apply the CSS rule to all elements in the document. Figure 3-12 shows what a universal selector looks like.

Figure 3-12
This rule is applied to all elements contained in the document. The universal selector applies to everything, including form input fields and tables of data. It applies style to any and every element present in a document.
Try It Out-The Universal Selector
Example 3-2. To see how the universal selector works, follow these steps.
  1. Enter the following markup into your text editor:

    1. Save the preceding document as Example_3-2.html and load it into your favorite browser.
    2. Enter the following CSS into a new document in your text editor.
      
      body {
          font-family: sans-serif;
      }
      * {
          border: 1px solid yellowgreen;
          color: green;
          padding: 5px;
          font-weight: normal;
          font-size: 12px;
      }
      
    3. Save the preceding styles as Example_3-2.css. After loading Example 3-2 into your browser, you should see output similar to that of Figure 3-13.

      1. Figure 3-13
      Tip 
      Figure 3-13 shows the results from Mac Firefox. Safari 2.0 produces similar results; the difference being only the font color is applied to the form elements. Safari 2.0 does not support custom styling of form elements very well. However, later versions have made progress in this area. IE 6 and IE 7 also differ slightly from the output here, in that the elements are missing the top border, which is because of a bug in IE. While the results are not perfect from browser to browser, you get the idea of what the universal selector does.

      How It Works
      The concepts at play in Example 3-2 are very simple; the universal selector is included in the style sheet as an asterisk. The declarations in the rule that follow the asterisk are applied to all of the elements that appear in the document, provided that element is allowed to have the property in question applied. For instance, the and elements do not accept most visual styles (borders, padding, and dimensions, for example). The universal selector, alone, doesn’t have much practical application, although as previously mentioned, it can be helpful for debugging styles and highlighting element dimensions in complex documents. By applying a border to all elements, you are able to immediately see the space an element occupies.

      The universal selector can also be used with other kinds of selectors, such as contextual selectors, also known as descendant selectors.

Post a Comment