Lesson 2: Understanding selectors, specificity, and cascading CHAPTER 4 147
This style won’t apply to any elements until you specify the class name by using the class
attribute, as shown in the following example.
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title></title>
<link rel='stylesheet' type='text/css' href='Content/default.css' />
</head>
<body>
<input id='txtName' name='txtName' type='text' class='myStyle' />
<button id='btnOk' class='myStyle'>Ok</button>
<button id='btnSave'>Save</button>
<button id='btnCancel' class='myStyle'>Cancel</button>
</body>
</html>
In this example, the class attribute specifies the myStyle style on the text box and two
of the buttons. Named styles promote reuse because they can be used on any element as
needed.
Using the universal selector
If you want to apply a style to every element, you can use the asterisk (*) symbol. The follow-
ing example applies the style to every element in the HTML document.
* {
background-color: white;
color: gray;
}
You should avoid using the universal selector because of the performance cost.
Using descendant selectors
You might want to change the style of elements only if the elements are descendants of
another element. For example, you might want to remove the underline from hyperlinks if
they are presented in a list item. This can be done by specifying a selector chain, which is a
group of selectors that specify a path to the elements that interest you. The selector chain
specifies an ancestor element, followed by a space, and then specifies the descendant ele-
ment, as shown in the following example.
li a {
text-decoration: none;
}
This example removes the underline from every hyperlink that is a descendant of a list
item, regardless of whether the hyperlink is a child, grandchild, or distant descendant. You
can specify a selector chain with many descendant levels to provide a path to the elements
you wish to style. The following demonstrates multiple descendant levels; the underline is
Key
Te rms