Do you know there are other ways of using CSS selectors? (Part 2)


Now that you have seen CSS base selectors, you might be wondering why one should bother with other selectors, since one can do everything with class and ID!
There’s nothing more professional than being able to use css rules appropriately and concisely. In this way, you will be able to improve the quality of your coding as well as shortening loading times of your webpages. Do you want to know how?

Using the universal selector

This selector is very powerful and it is represented by an asterisk ( * ). It can be read as “All the elements“. It is often used to “reset” the margin and the padding of all the elements:

* {
margin: 0;
padding: 0;
}

This is the equivalent of writing down all the HTML elements one after another, assigning them a zero margin and padding.

Frequently, the universal selector is misunderstood; in fact all the ID and class descriptions used in CSS:

#about { ..rules..}
.post { ..rules }

are equivalent to:

*#about { ..rules..}
*.post {..rules..}

Attribute Selectors

Attribute selectors, as the name suggests, allow one to apply styles to an element based on the name or value of the attribute. The 2.1 CSS selection list provides four different choices: selection based on the presence of an attribute, on the value of an attribute, on the value of a wordlist attribute and on an attribute that has a word ending with a dash. Let’s look at them one at a time.

Attribute-presence selector – element [attribute]

Thanks to this type of selector, you can apply styles to an element that is defined by a specific attribute, regardless of its value. For instance, consider the rule:

img[alt] {
border:5px solid red;
}

it must be read as “Select all the <img> elements that have the alt attribute and apply a red, 5 pixel-thick border to them”.

If I apply the previous rule to the following markup:

<img width="80" height="80" alt="First image" src="mia_immagine1.jpg"/>
<img width="80" height="80" alt="Second image" src="mia_immagine2.jpg"/>
<img width="80" height="80" alt="" src="mia_immagine3.jpg"/>
<img width="80" height="80"  src="mia_immagine4.jpg"/>

only the first three elements will have a red border, since they have an alt attribute (even though the third one in the image is empty), while the last one will appear out of sync with its border.

This selector is useful to make site navigation more consistent: in fact once you’ve created this rule a user will always expect to see a red border around images that have an alternate description. You could use specific element representations with a defined title attribute and you can use other ones for elements that have an attribute <code>lang</code> and so on.

You can use this rule to debug the website while it is being created: it’s an easy and rapid way to check which images the alt element is applied to.

Attribute value selector- element [attribute="value"]

This selector allows you to apply styles to all the elements that have an exact value attribute.

This is the rule:

input[type="text"]{
background-color: yellow;
}

it has to be read as, “Select all the input elements that have a type attribute exactly equal to text, then apply a yellow background”.

You can use this selector in many different scenarios. One we’ve already showed you in the example, which demonstrated how to select all the various elements in a form and to make their aspect uniform throughout the site.

Selecting a value attribute from a list – element[attribute~="value"]

This type of selector allows you to select the elements which have an attribute value composed of a list of words separated by a space. This might sound confusing. Basically, if one is defining a rule:

p[class~="highlighted"] {
line-height:1.2;
}

it is synonymous with “Select all the paragraphs with a class attribute which contains the highlighted word”. It’s not important where the highlighted word is placed, the important thing is that it is present in the attribute value list. You could end up with a similar scenario:

<p class="highlighted introduction">This introduction needs to be highlighted..</p>
<p class="postscriptum highlighted">This is a post scriptum and needs to be highlighted..</p>
<p class="editorial post highlighted">Instead this is an editorial and needs to be highlighted..</p>

All the paragraphs will be selected using the previous rule because their class attribute contains a highlighted word somewhere within it. When can this type of selector be useful?

Possibly you could use it to separate links that have a “rel” attribute. This is taken from the W3C website:

“This attribute describes the relationship from the document to the specified href link. The value of this attribute is composed of a list separated by link spaces.”

With this attribute we can define the relationship between a webpage and another page that is linked to it. Other than the predefined values (which allow one to specify whether a link takes one back to a site index or glossary) one can use attributes defined in XFNTM (XHTML Friends Network), which allow one to define one’s personal relations with the site owners of a linked website. For instance, it’s common to find a list of friends’ links on a blog, known as Blogroll. On our site you can find it like this:

<a href="http://valy.esempio.it" rel="sweetheart met">Valy's Blog</a>
<a href="http://nando.esempio.it" rel="friend co-worker">Nando</a>
...

I could color the element with ‘sweetheart’ attribute (which should be unique) in red and then show a cellphone icon next to my work contact list:

a[rel~="sweetheart"]{
color:red;
}
a[rel~="co-worker"]{
padding-left:18px;
background:#FFF url(work.png) center left no-repeat;
}

In this way (with a semantic markup).

For more information, you can visit the official site of the XFN project.

Selecting an attribute that has a word followed by a dash – element[attribute|="value"]

This is one of the least used selectors (similar to pseudo-class :lang) but it can be of interest to us here. Basically it selects all the elements having an attribute which has a word or a word followed by a dash ( – ).

It might seem strange that we are using this type of selector but you must remember that this selector selects links that have the href lang attribute.

This attribute can be used only if the href attribute is defined and it’s useful to specify the language of the linked site. For instance, if we apply to a markup:

<a href="http://american-site.example.com" hreflang="en-US">American site</a>
<a href="http://english-site.esempio.com" hreflang="en">English site</a>
<a href="http://example.site.it">Example site</a>

the following rule:

a[hreflang|="en"]{
color:yellow;
}

the first two links will become yellow since the attribute hreflang has been defined and in both cases it begins with either en or en-.

I know you might be thinking that this selector is limited in functions since the hreflang attribute is not popular; however there are other places where it can be used.

For example, you could make all the class names referring to images to begin with “img-”. In this case you could select all the mentioned classes using the following rule:

img[class|="img"]{
..here CSS class declarations begin with img or img-..
}

Pseudo-classes and pseudo-elements

Using these selectors you can apply styles to elements only when a defined condition exists or when an element is placed in a specific location within the document. All the pseudo-classes and pseudo-elements begin with a column (:) and can be preceded by an element selector.

The only rule you have to follow is that they have to terminate the selector in the following way:

:link {...rules..} /*correct*/
a:link {...rules...} /*correct*/
#header p:first-child {...rules...} /*correct*/
p:first-line em {..rules...} /*wrong*/

Taking into account the above rule, it can be said that pseudo-classes and pseudo-elements are selectors just like the rest of them, so they can be combined with descendant selectors: child, adjacent, and other pseudo-classes and pseudo-elements.

Let’s take a closer look!

:link and :visited pseudo-classes

Browsing the web you should have noticed how links are by default in two colors: blue and purple once a link is clicked.

This is a default setting which somehow derives from the first browser “Mosaic”, certainly this arrangement does not work on all the web pages. If you have a dark background, you might want to color your links in white and also eliminate the underline effect on the link. You can achieve all this using the :link and :visited pseudo-classes.

The :link pseudo-class can be applied to all links not yet visited:

a:link {
text-decoration:none;
font-weight:bold;
}

With this rule we’ve eliminated the underline of the link and turned it into a bold font.

The :visited pseudo-class is applied to all the links that have been visited through a specific browser:

a:visited {
text-decoration:line-through; /*slash a visited links*/
}

I could also make the same visited and unvisited links, so as to avoid any change after the visit, as follows:

a:link , a:visited{
text-decoration:none;
color: black;
font-weight:bold;
}

Using this technique you risk making the page less readable; a user would not be able to distinguish which links he or she has visited and which ones he or she hasn’t.

:Active, :hover and :focus pseudo-classes

Let’s turn our attention to “dynamic” pseudo-classes. They are named this way because the styles applied through selectors become visible only when a user has made a specific movement or action:

  • :hover => the user hovers the pointer over an element’s area;
  • :active => an element is selected with a mouse click;
  • :focus => it applies to an element that was clicked on by a user or it was selected using the keyboard (Tab or shift+Tab);

It’s important to note that these pseudo-classes are applied not only to links (as many believe it to be), but to all elements. Let’s say you would like to highlight a paragraph with a yellow background when you hover the mouse over it:

p:hover {
background-color:#ffff99;
}

The most common use is to apply such properties to links. Many websites use different styles for links which are not visited, visited, upon mouse hover, upon mouse click or when they are selected using the keyboard. The rules that you have to apply are the following:

a:link    { color: red }                            /* Link not visited */
a:visited { color: blue }                         /* Link visited   */
a:hover   { color: yellow }                     /* Mouse hover*/
a:active  { color: lime }                        /* Mouse click    */
a:focus   { background-color: #ACE;}     /* Selection with the keyboard */

In this case the order is very important, due to a CSS property knows as “Waterfall”, which we will cover in a future article. A lot of people keep track of them by using a combination of capitalized letters, to create a word or a phrase that represents a pseudo-class. As an example, consider the following phrase “LoVe HAte”.

:First-child pseudo-class

This pseudo-class is very interesting (combined with its antagonist :last-child which we will cover in a future article on CSS3 selectors): select an element only when it’s the first child of the parent element (did you read the previous article?).

p:first-child {
color: blue;
}

The syntax can be quite difficult to read: this selector must be read as “Turn blue the text of each paragraph which is the first child” and not as, “select the first child of paragraphs and turn the text blue”. Thus if we apply it to this markup:

<div>
<p>Pizza is a dish that is easy to prepare, but few people can actually say they can cook the real naples-style pizza.</p>
</div>
<div id="recipe">
<h2>Preparing pizza</h2>
<p>As you can see, it's very simple! Here are the <strong>simple</strong> steps needed to prepare a great pizza:</p>
</div>

only the first paragraph will be turned into blue, since the first child of the “recipe” div is the title of the <h2> second level and not of the paragraph. Also, the strong element will not be turned blue because it’s the first child of the paragraph.

:Lang pseudo-class

The :lang pseudo-class is one of the least used, as we’ve said before but we believe it will become gain popularity in the near future. Basically, select all the elements that are written in a certain language. How can CSS determine which language it is? It’s simple, by analyzing the document looking for all the elements with a defined lang attribute, and control if the specified language is the same as the one fixed in the stylesheet.

Let’s take a verse from Walk Whitman’s “O Captain! My Captain!”:

<blockquote lang="en">
<pre>
<pre>Here Captain! dear father!
This arm beneath your head;
It is some dream that on the deck,
You've fallen cold and dead.
</pre>
</blockquote>

If you want to italicize all the cited English text, all you have to write is:

blockquote:lang(en) {
font-style:italic;
}

:First-line, :first-letter pseudo-elements

These selectors serve a simple function: they allow you to select either the first line or the first letter of an element. These selectors partly derive from some common methods used in typography:

:first-letter is used to simulate a “drop-cap” effect, meaning that the first letter of the first paragraph has a different style compared to the rest of the paragraph (a Medieval-looking style).

For instance, you can increase its size and change the color:

p:first-letter{
font: bold 65px Georgia, "Times New Roman", Times, serif;
color:#003366;
}

:first-line, on the other hand, is often used to increase the size of the first line of text, like newspapers:

p:first-line{
font-size:120%;
}

Obviously, “first-line” is a relative measure: on a monitor with 800×600 resolution, the first line of the paragraph will contain less words compared to on a widescreen monitor. Therefore, if you’re looking to build a website that looks exactly the same everywhere (which is practically impossible), it should be better not using this font.

At this point it is best to note that (with the introduction of IE8), there’s been a widespread diffusion of 2.1 selectors, supported fully by web browsers (on this page you can find a list of the various selectors).

Support for selectors has been limited though, bringing about a rise and diffusion of hacks. This is why we believe a serious professional should try to improve his or her work by using all of the available selectors and avoid justifying their use by saying, “Browser X does not support it”.

Other articles in our guide:

Maybe you are interested for..

Are you using all of the available css selectors?

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags: ,

The Author

Fond of web design, takes delight in creating (X)HTML+CSS layouts. A maniac of polished and tidy codes, the type of person you find in your house straightening the paintings hanging on the wall. He has made his mind of becoming a web designer with a capital “w”, and spends entire nights awake in order to make his dream come true.

Author's web site | Other articles written by

Related Posts

You may be interested in the following articles:

13 comments

  1. Nicolas

Trackback e pingback

  1. uberVU - social comments
    Social comments and analytics for this post... This post was mentioned on Twitter by paulmilford: RT @hulldo: Do you know there …
  2. Do you know there are other ways of using CSS selectors? (Part 3) | Your Inspiration Web
    [...] If you are new here, you might want to subscribe to the RSS feed for updates on this topic. …
  3. How to export a psd into xhtml and css without losing your soul? (Part 2) | Your Inspiration Web
    [...] We will use a value attribute selector to eliminate this hassle using a technique that is professional and that …
  4. Why you should know the new CSS3 selectors? | Your Inspiration Web
    [...] Do you know there are other ways of using css selectors? (Part 2) [...]

Leave a Reply

Current day month ye@r *