Watkins Web 3: Blog

Cheat Sheet: CSS Selectors

CSS selectors are the part of CSS syntax that “target” or “select” an HTML element or elements to be styled. In pseudo-code, a CSS statement look like this:

selector {
	property: value; /* declaration 1 */
	property: value; /* declaration 2 */
}

Use a tag name by itself to target a particular HTML element:

p {font-family:helvetica, arial; font-size:12px; line-height:18px;}
h2 {color:gray;}
div {padding:20px;}

Use a comma to target multiple HTML elements with a single expression:

ol, ul {list-style:none;}
p, h2, h3 {margin-bottom:10px;}

Target any HTML element of a particular class:

.warning {color:red;} /* matches <p class="warning">, <ul class="warning">, etc */
.intro {font-size:14px; line-height:18px;}
.caps {font-size:90%; letter-spacing:1px;}

Target any HTML element of a particular ID (should only match one element per page at most, since IDs must be unique to the page):

#sidebar {float:right; width: 30%;}

Target a particular HTML element of a particular class:

p.warning {color:red;}
div#sidebar {float:right; width: 30%;}

Target a particular HTML that has multiple classes:

p.warning.intro {font-weight:bold;} /* matches <p class="warning intro"> and <p class="warning intro awesome"> but NOT <p class="warning">*/

Use descendency to target elements that appear inside of others:

#main p {font-size:12px; line-height:16px;}
#main ul {list-style:circle;}
#sidebar ul {list-style:disc;}

Combine these techniques to get more granular control over your elements:

#main p.warning {color:red;}
#sidebar p.warning {background-color:red; padding:2px; color:white;}
#sidebar p.warning.intro {background-color: orange;}

Use a colon to indicate pseudo-classes. Here are the most common:

a:hover		{border-color:red;} /* invoked on mouse-over */
a:active	{border-color:orange;} /* invoked during mouse-down */
input:focus {background-color:yellow;} /* invoked while cursor is in the field */
li:first-child {margin-left:0;} /* targets the first list item in a set of list items */

Use the attribute selector to target elements of a particular attribute:

img[alt] {border-color:red; } /* matches all images that HAVE an alt attribute */
input[type="text"] {padding:2px;} /* matches all inputs whose type is "text" */