CSS: Tag Matching (Selector) Tutorial

By Xah Lee. Date: . Last updated: .

This page is a beginner's tutorial on CSS tag matching syntax.

The following are most common patterns in using CSS. You should memorize them by heart.

Match Tag Names

Some common examples of setting appearance for HTML elements.

body {font-family:sans-serif}

h1,h2,h3,h4,h5,h6 {font-family:serif}

p {line-height:1.5}

blockquote {color:navy}

img {margin:1px}

Match Class Value

/* matches any tag of class “xyz”*/
.xyz {color:red}

the above will match both of the following:

<div class="xyz">…</div>
<span class="xyz">…</span>

Note: a HTML element can have more than one class. 〔➤see HTML: Multiple Class Attribute Values

Match Tag Name and Class Value

/* matches any div of class “xyz”*/
div.xyz {color:red}

the above will match

<div class="xyz">…</div>

Here's another example:

/* matches any span of class “ab”*/
span.ab {color:blue}

This will match:

<span class="ab">…</span>

Match a Tag's ID

/* matches any tag with id of “xyz”*/
#xyz {color:red}

the above will match any of:

<div id="xyz"></div>
<span id="xyz"></span>
<p id="xyz"></p>

Note: a tag's id should be unique on a page. A page cannot have two tags having the same id. A frame 〔➤see HTML: Split Windows; Frameset〕 or iframe 〔➤see HTML: Iframe〕 counts as separate pages.

Change Link Appearance

Example of removing the underline in links.

a:link {text-decoration:none}
a:visited {text-decoration:none}

〔➤see CSS: Text Decoration: Underline, Overline, Line-Through

Multiple Tags A, B, C

If you have multiple tags and want them all to have the same appearance, you can use comma.

For example, this:

span.x {font-weight:bold}
span.y {font-weight:bold}
span.z {font-weight:bold}

is equivalent to:

span.x, span.y, span.z {font-weight:bold}

Match Nested Tags

Sometimes, you want to match a tag only if it is nested inside another tag. You can use the space to specify this, like this:

div.abc span.xyz {color:red}

In the above example, any span.xyz inside div.abc will be matched.

Parent > Child

Sometimes you want to match a tag only if it is a immediate child of a given parent tag. You can use the > to specify a parent-child relationship.

Here's a example:

div > span {color:red}

In the following HTML code, the CSS code above will match the “upon” but not “you”.

once <span>upon</span> a time…
<footer>Thank <span>you</span> for reading</footer>

CSS Selector Syntax

For a complete list of tag matching syntax, see: CSS Selector Syntax.

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.