The Sysadmin Notebook  

Sitemap

CSS Selectors

Syntax for CSS selectors

A CSS rule consists of two parts: a selector and a declaration. Declarations are enclosed in curly brackets: {attribute:value; attribute:value;} Specify an external stylesheet:
<link rel="stylesheet" href="css/style.css" type="text/css">

Selectors:

A type selector name the xhtml tag to be styled:
/* set paragraph colour */
p {
color: #000000;
}
Class selectors are prefixed with a '.' and can appear any number of times on a page.
/* Set color for items with attribute class="heading" to red*/
.heading {
color: #ff0000;
}
ID selectors are prefixed with a '#'. IDs can occur only once per html document.
/* set color for element with attribute id="title" to black */
#title {
color: #000000;
}
/* set color for h2 element with id="title" to white */
h2#title {
color: #ffffff;
}
Selectors can be styled as a group:
h1, h2, h3, h4, h5, h6 {
color: 00ff00;
}
Descendant selectors allow you to select elements when they are descendants of other elements:
/* Set color for list items in an ordered list in the navbar to blue: */
#navbar ol li {
color: #0000ff;
}
Child selectors allow you to select elements when they are direct child elements of other elements:
/* Set text decoration for links in lists: */
li > a {
text-decoration: none;
}
Universal selectors are represented with an asterisk and apply to all elements:
* {
font-family: Verdana, Arial, sans-serif;
}
Adjacent sibling selectors apply styles to elements that are placed at the same level on the same branch of the document hierarchy.
/* style is only applied to li elements that follow another li element */
li + li {
font-size: 200%
}
Attribute selectors allow styles to be applied to elements with the specified attribute
a[href] {
text-decoration: dotted;
}
Pseudo-class selectors (:link, :visited, :hover, :active, :focus, :first-child, :lang(n)).
#navbar ul li a:visited {
color:#00FF80;
}
Pseudo elements selectors: (:first-letter, :first-line, :before, :after).
p:first-line {
font-size: 200%;
}