CSS3 Tutorial: selectors

CSS3 selectors

The syntax of CSS is not difficult in itself, but it is extensive, because of which a stylesheet can look rather complicated. The large number of options within a CSS style sheet makes it possible to operate very precise in a (e.g. HTML, XHTML, XML or SVG ) document, almost with surgical precision. so that we can designate every elements in the document to apply styles on.

The main component of the CSS syntax is made up of so-called selectors. A selector is an element of the (e.g. HTML, XHTML, XML or SVG ) page on which we can apply a style. In the following CSS statement the 'body' is the selector on which we apply a particular style (also called rule) on the <body> element in the page.

body {
background-color:red;
}

We say that the body selector is aimed at the <body> element. The result of this statement is that the background color of the page will be red.
'background-color' is called a CSS property and 'red' is its value.

Multiple selectors can be grouped (chained), for example:

h1, div.header, img.logo[title]{
margin-top:20px;
}

1. Simple en combined selectors

The above rule is composed of a combined selector which consists of three simple selectors. The first simple selector focuses on an element (on the <h1> element), and is therefore referred to as a type selector. The second selector is a chain of two simple selectors: the div type selector linked (chained) to the class selector 'header'. Finally, the third selector is a chain of three simple selectors: img chained to logo chained to the attribute selector [title].

In the above example you can see how chaining leads to more precise identification of an element in a document. You can also see the various types of simple selectors subtly different. The following two CSS rules are therefore not equal:

div.header    
/* Single selector composed of two simple selectors. */
div, .header 
/*  Selector group (mind the ,) with two selectors, each consisting of
a simple selector.*/

The second rule is potentially applicable to many more elements than the first. It focuses on every <div> element, also on the <div> element with the class named 'header'. In contrast, the first rule is focused on only one element:

Let's see what kinds of selectors we can all come across in the world of CSS.

1.1. Type selector

The most common simple selector is the type selector which occurs in in rules that are applicable to elements in your (HTML, XML, SVG etc.) markup, for example:

h1,h2,h3,h4,h5,h6 { }
div { }
table { }
tr { }
td { }

Each element in the HTML or XML markup has a matching type selector that is written equally as the element except for the brackets < >. When the element names are case sensitive as in XML, then the matching type selector is too. The following two type selectors, refer to two different XML elements.


td { } /* focused on <td> elements  */
TD { }  /* focused on <TD> elements */

1.2. Universal type selector

The universal type selector is an asterisk (*). As the name implies, this selector focuses on all types of elements. For example:

* { border:1px solid #00f;} 
/* all elements on the page are outlined with a
solid border with thickness of 1px and color blue */ div * { border:1px solid #ff0;} /* all elements within a <div> element have a solid border with thickness 3px and color red*/

1.3. Attribute selectors

In most markup languages a lot of information is encoded by means of attributes, Such information may be in the URI of an image (<img src="images/logo.gif">), additional information in a title attribute (<abbr title="something_special">) or the destination of a hyperlink (<a
href = "http://en.wikipedia.org/wiki/something">). Using CSS attribute selectors, we have a powerful tool at our disposal to assign styles to elements based on the attributes of these elements. Some examples of four different types attribute selectors:

  1. an attribute selector as [title] selects all elements that have a 'title' attribute, like for example <abbr title="something">.
  2. [title = Daffodil] selects all elements that have a title attribute with value Daffodil. <abbr title="Daffodil">.
  3. [title ~ = hand] selects all elements that have a title attribute with in any case the word hands in it like <abbr title="second hand"> but not <abbr title="secondhand">.
  4. [lang |= en]. This less common attribute selector selects elements that have an attribute with a value which, in any case, the word "and" occurs connected with a dash (-) to another word, e.g. lang = "en-us" and lang = "en-uk".

Because attribute selectors are a kind of simple selectors, we can connect more of this kind of selectors (chaining) to a single line that meets all our criteria, for example: if we want to select those elements written in Dutch and quoted from a Wikipedia article about native plants then we can use the following CSS rule: [lang | = nl] [cite = "http://en.wikipedia.org /wiki/native plants "]. In addition to this possibility, there are three new attribute selectors defined in CSS3, called substring matching attribute selectors, which give us more options in selecting substrings in attribute values of elements:

  1. [title ^ = second] selects all elements that have a title attribute with at the beginning the substring 'second' in it, <abbr title="secondhand">, this time NOT connected by a hyphen, but in one word.
  2. [$ title = hands] selects all elements that have a title attribute with at the end the substring hands in it, <abbr title="secondhand"> again NOT connected by a hyphen, but but in one word.
  3. [title * = second] selects all elements that have a title attribute with anywhere the string "second" in it. Examples are <abbr title="secondhand"> and <abbr title="second choise">. The (sub) strings here may (but needn't) be connected here.

1.4. Id and class selectors

Ids, and classes are two attributes which may be used to select pieces of content, as well as to group them. The syntax, here as an example in a <p> element: <p id="left" class="main">.

p[id="left"]{
font-size:1.2em 
font-family: Arial, Verdana, sans-serif;
}

p[class="main"]{
margin-left:20px
}

This is entirely correct code, but instead of attributes selectors we rather use the so called id selectors and class selectors. The style rules in the above HTML page will look as follows:


p#left{
font-size:1.2em 
font-family: Arial, Verdana, sans-serif;
}

p.main {
margin-left:20px
}

If we want that ALL elements with the specified id and class are targeted (and not just in <p> elements), then we write:

#left{
font-size:1.2em 
font-family: Arial, Verdana, sans-serif;
}

.main 
{
margin-left:20px
}

2. Pseudo-classes

Just as attribute selectors pseudo-classes provide the ability to select elements with certain characteristics. We use the colon(:) to indicate the beginning of a pseudo-class selector. However, in contrast to the attribute selectors at which looked above, the pseudo-class selectors not only focus on attributes and attribute values of elements, but they can focus on elements, based on all kinds of criteria. The most familiar pseudo-classes are those that focus on the styling of hyperlinks, the :link and :visited pseudo-classes

2.1. Hyperlinks: the :link and :visited pseudo-classes

The: link pseudo-class targets, not surprisingly: hyperlinks. In (X)HTML this means: all <a> elements that contain a href attribute.

a:link { color: red; }

The: visited pseudo-class carries this concept one step further and focuses on hyperlinks that have already been visited, more precisely, on the links which have already been clicked and are in the browser cache.

2.2. The :hover, :active and :focus dynamic pseudo-classes

The so called dynamic pseudo-classes apply to elements in the page to which a particular user action was performed. In this way we know the :hover pseudo-class that focuses on hyperlinks on which a mouseover action occurs.
The :active pseudo-class focuses on elements that are currently "active", a condition which is freely interpreted by user agents, and usually concerns the fact that the user clicked on the hyperlink, but the mouse not been released yet.
The :focus pseudo-class targets on the element on the page that has the focus, for example, a form field in which you clicked the mouse, ready to fill in something.

2.3. The :lang() pseudo-class.

Earlier in this article we discussed the [lang |=en] attribute selector can be used to select elements based on the value of their lang attribute. More common, however, is to use the :lang () pseudo-class for this purpose. It is also the first CSS structure discussed in this tutorial, that uses a new kind of syntax, called the functions notation. The function notation is used in programming languages where functions are followed by (), in which so-called arguments or parameters can be placed in order to construct a valid selector, for example: :lang(en) for English or :lang(zh) for Chinese. Omitting the country code makes the CSS rule invalid. Using the mentioned: lang () pseudo-class you can provide texts written in a certain language of a desired style (such as large, color, or line-spacing) by which the text becomes more legible.

2.4. The :target pseudo-class

A known technique to "jump" to a specific position within a page is the application of a so-called anchor element at that position, e.g.<div id="flash">Books about Flash</div>. By clicking on a link with a URI to which a fragment identifier is associated, as in <a href="books.html#flash">, we can jump to the anchor element 'flash' on the page books.html, e.g.:

<!DOCTYPE html>
<meta charset="utf-8"><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head> <style> #flash:target { color : red } #flash:target:before { content : url(image.gif) } </style> <body> <a href="#flash">See our Flash books</a> ... <div id="flash">Books about Flash</div> </body> </html>

The target of the link, that is, the anchor element, is now being displayed in red and preceded by the image target.gif.

This possibility of styling target elements provides interesting possibilities for user interaction.

2.5. The :first-child or :last-child pseudo-classes

Using the: first-child and: last-child pseudo-classes you can simply add a special styling to the first or last element of a given element series.A common example is the navigation list in which the first and the last item of the menu must be provided with aberrant spacing or borders. Without the: first-child and: last-child pseudo-classes you were forced to add classes with names like "first and "last " to your markup, see the example below with characteristic code for a navigation list.

<nav>
<ul>
  <li class="first"><a href="../">Home</a></li>
  <li><a href="../products/">Products</a></li>
  <li><a href="../service/">Service</a></li>
  <li class="last"><a href="../contact/ ">Contact</a></li>
</ul>
</nav>

When using the: first-child pseudo-class and: last-child pseudo-class, the "first" and "last" classes are longer required. Just use nav li:first-child and nav li:last-child.

Below some more examples of the use of these pseudo-classes
/* Select the first h2 element within each div */
div h2:first-child
/* select the very last child element in the body*/
body > :last-child
/* select all elements thatare first children of their parents*/
:first-child
/* select all first the cells in the last row in tables */
tr:last-child td:first-child

It is important to know that only the :first-child pseudo-class is defined as part of CSS 2.1, while the :last-child pseudo-class is part of CSS3. Fortunately, both pseudo-classes are, in practice, well supported by most user agents. An exception is Internet Explorer 7, which only supports the first-child pseudo-class.

2.6. The nth-child(an+b) pseudo-class

The :nth-child(an+b) CSS pseudo-class matches the an+b th child element of its parent in the document tree.
a and b are constant values, n is a variable (starts at 0), and b is an offset value. For example

/*Mathes every <p> element of it's parent with an odd index namely 1,3,5,7,9 *.
p:nth-child(2n+1){
background:#f16529;
} 

/*The above rule van also be written as*.
p:nth-child(odd)

/*Mathes all the even rows in a table*.
tr:nth-child(2n)

/*Mathes all the even rows in a table*.
tr:nth-child(even)

/*Mathes every <span> element that is the first child of its parent*.
span:nth-child(1){
background:#f16529;
} 

/*Mathes every <span> element that is the first child of its parent*.
span:nth-child(0n+1)   

2.7. More pseudo-classes

There are more CSS3 pseudo-classes than the ones discussed above, such as the :left and :right, the :enabled and :disabled, the :checked pseudo-classes and more. For a full list of the pseudo-classes' see the page 'Selectors level3' of the W3C.

3. Pseudo-elements

Pseudo-elements are very similar to pseudo-classes in the sense that they expand the possibilities of CSS selectors, allowing styles to be applied more precisely to parts of the document. Unlike pseudo-classes, however, pseudo-elements select just fictional elements that do not actually exist in the markup.

3.1. The :first-letter pseudo-element

Something that is often found in web pages (as well as in books and magazines) is separate styling of the first letter of a paragraph, for example initials. Normally with CSS, you can only select the first letter of a paragraph when there is a tag with a class or id present in the markup, such as in the following example:

<p>
<span class="first-letter">W</span>ise men speak because 
they have something to say, fools because they have to say something.
</p>
Thanks to the :first-letter pseudo-element, the <span class="first-letter"> no longer needed and we can instead rewrite the above code as:
<p>Wise men speak because they have something to say, 
fools because they have to say something.</p>
with in the stylesheet the following line in which the: first-letter pseudo-element is inserted:
 p:first-letter { font- size: 1.5em; font-weight:bold }
 
Browsers will assume when reading the above CSS rule that an extra child element is present in the paragraph, even though, in reality, this is not the case.

3.2. The :first-line pseudo-element

The: first-line pseudo-element behaves like the: first-letter pseudo-element except that instead of the first letter (or number) it selects the first line (note: not the first sense). When the browser window is enlarged or reduced, then the beginning and end of the line are re-evaluated on the fly. Therefore there is no other possible markup equivalent to the :first-line pseudo-element as was the case with the: first-letter pseudo-element.

3.3. The :before and :after pseudo-elements

These pseudo-elements relate to the ability of CSS to render so called "pseudo-content". Read this, and about :before and: after pseudo-elements in the tutorial "Pseudo content".

3.4. The :selection pseudo-element

The ::selection CSS pseudo-element applies rules to the fragment of a document that has been selected ( with the mouse or another pointing device) by the user. This fragment can be highlighted or colored like so:

/* draw any selected text  blue on grey */
::selection { 
color: blue;  background: grey; 
}   
/* draw selected text in a paragraph red on black */
p::selection{
color: red;  background: black; 
} 
 

Note that only a few CSS properties can be used in a rule using ::selection in its selector: color, background, background-color and text-shadow. Note that, in particular, background-image is ignored, like any other property.

3.5. More about pseudo-elements

There is a difference in syntax in CSS2 and CSS3, with respect to pseudo-elements. In CSS2 pseudo-elements are written exactly the same written pseudo-classes, with a single colon(:) followed by the name of the pseudo-class. In CSS3 pseudo-elements, however, are written with a double colon (::)
In CSS2, you can either use : as ::. In CSS3, however, only ::

Read more about Pseudo-elements at http://www.w3.org/TR/css3-selectors/#pseudo-elements

4. Using combinators

4.1. Descendant combinator

The descendant combinator selects the elements targeted by the sequence of two or more simple selectors. In the following example, any <span> or <em> element that is nested within any <article> element will be rendered in red

article span, article em {
 color: red; 
}

4.2. Child combinator

The child combinator selects element on the right side of the bracket > if that element is an immediate child (thus not a grandchild, great-grandchild, or other descendant) of the element on the left side of the bracket.

section > div { 
background-color: blue;
}

4.3. Adjacent sibling combinator

The adjacent sibling combinator selects the element at the right side of the + sign if that element is the sibling immediately following the element at the left side of the + sign. For example, the next three rules are targeting certain element in the HTML fragment below

h3 + p /* Selects only the first paragraph. */ {
...
}
p + p /* Selects only the first two paragraphs. */{
...
}
p + article /* Selects only the first inner <article> element (comment). */{
...
}

<!DOCTYPE html >
<html>
<head>
<title>Adjacent Sibling Combinator Example</title>
</head>
<body>
<article>
    <h3>Lorem Ipsum</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
    <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem  accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab  illo inventore veritatis et quasi architecto beatae.</p>
    <article>
		<span>sed quia consequuntur magni dolores eos qui ratione voluptatem</span>
	</article>
	<article>
		<span>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut  fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem  sequi. </span>
	</article>
	<p>Aspernatur aut odit aut  fugit, sed quia consequuntur.</p>
</article>
</body>
</html>

4.4. General sibling combinator

The general sibling combinator, introduced in CSS3, is similar to the adjacent sibling combinator in that it selects the element on the right side of the tilde (~) sign if that element is a sibling that follows the element on the left side of the ~ sign. However, whereas the adjacent sibling combinator requires that the subject on the right immediately follow the subject on the left, the general sibling combinator doesn’t. The only requirement is that the two elements are siblings of one another and the subject on the left precedes the one on the right. Using the same document structure used in the previous examples, this means you could use the general sibling selector to similar but not identical effect, and you have a few more ways you could write the selectors. Instead of targeting only the first <p> element, you would target all of the <p> elements:

h3 ~ p /* Selects all of the paragraphs. */{
...
}
p ~ p /* Selects all of the paragraphs.*/{
...
}
p ~ article /* Selects only the inner 
element. */{ ... } h3 ~ article /* Selects all the inner <article> element (comments). */{ ... }

Leave a comment