Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

Selectors 163

8


In this case, tags that appear within

tags will be italicized. If a tag
appears inside a list item, the contents will be rendered in boldface. Let’s add in one
more rule:


cite { color: green; }
p cite { font-style: italic; font-weight: normal; }
li cite { font-style: normal; font-weight: bold; }


In this case, we have one rule that applies to all tags, and the two others that
you’ve already seen. In this case, the contents of all tags will be green, and the
appropriately nested tags will take on those styles, too. Here’s one final example:


cite { color: green; }
p cite { font-style: italic; font-weight: normal; color: red; }
li cite { font-style: normal; font-weight: bold; color: blue; }


In this case, the nested styles override the default style for the tag because they
are a more specific style definition. The contents of tags that don’t meet the crite-
ria of the nested rules will appear in green. The nested rules will override the color speci-
fied in the less-specific rule, so for tags that are inside

tags, the contents will
be red. Inside list items, the contents will be blue.


The ability to override property settings by using more specific selectors is what provides
the ability to set styles with the precision of the style attribute from a style sheet. This is
called CSS specificity.


Classes and IDs


Sometimes selecting by tag (even using contextual selectors) isn’t specific enough for
your needs, and you must create your own classifications for use with CSS. There are
two attributes supported by all HTML tags : class and id. The class attribute is used to
classify elements, and the id attribute is for assigning identifiers to unique elements.


To apply a selector to a class, use a leading. in the class name in your style sheet. So, if
you have a tag like this


Some text.

then you write the rule like this


.imprtnt { color: red; font-weight: bold; }


Any element with the class imprtnt will appear in bold red text. If you want to give this
treatment to only important

s, you can include the element name along with the
class name in your rule.


div.imprtnt { color: red; font-weight: bold; }
p.imprtnt { color: blue; font-weight: bold; }

Free download pdf