Advanced CSS & CSS3 Selectors

10117000002CSS selectors can be extremely powerful. There are times when you need to target a group of items, and don’t want or need to give them a class or ID. Advanced selectors are great because they target an item based on type (div, a, span) or by location (inside div1) and give you more power over the style, without being forced to class or ID everything. Of course, if you don’t use these often, it can be a pain to remember, so I put together this handy list for easy reference. Let’s take a look at some basic selectors, as well as the new CSS3 selectors.

Universal

Targets everything. Example of removing a border from EVERY element would be:

* { border: none; }

By Type

Targets all elements using those types. For example, if you want all strong tags to also be white:

strong { color: #FFF; }

Selectors Using Classes

If you only wanted to target a link with the class of active:

a.active {}

You can also chain these together. If you wanted to target the link with a class of “active” and “pink” but not the a links with only the class “active”:

a.active.pink {}

Descending

Targets elements ONLY underneath certain elements. For example, if you wanted to target all h2 tags underneath a div named header:

#header h1 { }

Children

Targets only the children of the elements. Therefor, if you wanted to target ALL divs inside an unnumbered list:

ul>li div {}

Siblings

These work for two divs together (I really NEED to use this one more). For example. If you have an a tag and a div tag next to each other, underneath a parent. You can target the interactions between them:

div.home + a {}

Attributes + CSS3

In regular CSS, you can target items byt attribute, for example tags with titles:

a[title] {}

You can also use = or ~= to target specifically by word. For example, to specifically target ANY link element with the title “cool” in it:

a[title~=cool] {}

In CSS3, W3C adds a whole new dimension for selectors. You can now target just by the beginning, ending or middle of a string! For example. Let’s say you want to target EVERY h1 tag with a class beginning with “pe”:

h1[class^="pe"] {}

This would target:

<h1 class="peace">
<h1 class="peony">

But not:

<h1 class="papers">

You can switch this around by targeting the ending of a class by:

h1[class$="pe"] {}

Which would target:

<h1 class="tripe">

But not:

<h1 class="trip">

To attach a style to ANY class that has a string of letters in it:

h1[class*="pe"] {}

Would target every class on an h1 tag with the letters “pe”.