The list of CSS Selectors

September 1, 2015

There are a ton of different CSS selectors out there. Here are the ones that I find extremely useful.

Element Selectors

If you ever want to style all elements of a certain type ( only recommended for a base stylesheet ) you should use plain element selectors.

a {
  /* Style all links */
  color: red;
}

img {
  /* Style all images */
  max-width: 100%;
}

ID and Class Selectors

Perhaps the most common of all selectors. Let’s say you have some HTML that looks like this:

<div id="foo">
  <span class="bar">Hello World</span>
</div>

If we want to add some styles to it. You can target the ID of foo and the class of bar this way:

#foo {
  width: 100px;
  height: 100px;
  background-color: red;
}

.bar {
  display: block;
  width: 25px;
  height: 25px;
  background-color: blue;
}

Pseudo Class Selectors

There are all sorts of great ways to select elements in a certain state or position. Although the browser support isn’t as great as some of the previously mentioned but pseudo selectors work in all current major browsers. They look like this:

/* Control what links look like when hovered */
a:hover {
  color: pink;
}

/* Control what links look like when active */
a:active {
  color: pink;
}

/* Control what links look like when visited */
a:visited {
  color: pink;
}

/* Alter the first list item in any list */
li:first-child {
  font-weight: bold;
}

/* Alter the last list item in any list */
li:last-child {
  font-weight: bold;
}

Relationship Selectors

Last but not least, I often see people use classes and IDs when relationship selectors would suffice. Say you have some HTML that looks like:

<div>
  <p>Foo</p>
  <p>Bar</p>
</div>
<p>Baz</p>
<p>Whatever comes after Baz</p>

Let’s target those elements!

/* Targets all paragraph descendants of every div */
/* In this case, Foo and Bar */
div p {
  color: red;
}

/* Targets the first paragraph child of every div */
/* In this case, Foo */
div > p {
  color: blue;
}

/* Targets the first paragraph sibling of each div */
/* In this case, Baz */
div + p {
  color: yellow;
}

/* Targets all paragraph tags that are siblings of every div */
/* In this case, Baz and whatever comes after Baz */
div ~ p {
  color: green;
}