These are the various flavours of selectors that can be used in CSS version 1. There are more selectors that can be used with version 2 of CSS. See the "Selectutoral" for more info.
Selecting a tag
All instances of a particular tag can be selected with a tag selector.
h1 { color: #700; }
blockquote { font-style: italic; }
This will change all <h1>
tags to dark red and the font in all <blockquote>
tags to italics. Even tags with a class with be selected. For example, <blockquote class="literary">
will be italic with the above style sheet.
Note that when styling XHTML, the tag name in the selector is case-sensitive.
Selecting a class
You can modify only tags with a particular class
by using a class selector.
ul.links { list-style-type: none; }
.subtle { color: #777; }
This will change the list style of all <ul class="links">
, but not <ul>
without class="links"
. Any tag with class="subtle"
will have its text colour changed to grey.
Selecting an ID
You can modify only tags with a particular id
by using a ID selector.
ul#contents { background-color: #ccc; }
#first { text-indent: 0em; }
This will change the background colour of the <ul id="contents">
, but not of any other <ul>
. Any tag with id="first"
will have its indentation modified.
Selecting a tag inside another
It is also possible to select an element only if it is inside another. This allows you to modify tags based on their context; they are called contextual selectors.
div#header ul { margin-left: 0em; }
li p { font-size: smaller; }
The first rule here will modify all <ul>
tags inside of the <div id="header">
…</div>
. Other <ul>
tags will be unaffected.
The second rule will change the font size of paragraphs that are inside of a list item, but not other paragraphs.
Selecting pseudo-classes
CSS1 defines several pseudo-classes that let tags in different states to be modified. These are used for the different states of links.
body { background-color: #fff; color: #000; } a:link { color: #00e; } a:visited { color: #518; } a:active { color: #f00; }
These will set colours for the page that are close to most browser's defaults. The a:link
selector modifies hyperlinks; a:visited
selects links that have already been viewed; a:active
selects a link as it is being clicked.
Selecting several things
Several of the above selectors can be combined to form a group selector.
h1, h2, h3, h4, h5, h6 { font-family: sans-serif; }
div#header, div#footer { background-color: #ffc; }
The first example will change the font family for all of the heading tags. The second changes the background colour for both <div id="header">
and <div id="footer">
.