Do you know there are other ways of using css selectors? (Part 1)

This is a topic that is shunned by a lot of developers. The difference between a professional designer and an improvised one is in the use of selectors. CSS or stylesheets serve to define the way in which content is visualized on a multitude of devices (such as web browsers, pdas, fridges, etc.).

How can I apply these styles to a document, saving time while improving the quality of my work?

The answer is in the use of selectors. It’s going to take some time to explain all of this, so relax, have a cup of tea and make yourself ready; we assure you it will not be a loss of your time.

Let’s go over the basics: the Type selector

Let’s begin by looking at the type selector, which is one of the easiest to understand. An element is selected on the basis of its HTML tag, and a particular style is applied to all of the elements of that type present on the page. For instance, if you want to see the text inside the <li> elements of your page colored in yellow, you will have to write the following:

 li {color: yellow;} 

How do I add a blue background to the paragraphs? It’s easy:

 p {background-color: blue;} 

Class and ID selectors

Now you know how to change the look of the various elements on your webpage; this is an important step in learning styles other than the default one present in your web browser. What if you wanted to apply just one style to just one element, instead of applying it to all of the elements present on the page?

In this case, you can use class and ID attribute selectors, which can be joined to every element of a webpage. What’s the difference between the two? When should I apply the class selector over the ID one and vice versa?

It can be useful to think of ID as “IDentity”: just like your i.d. number which is unique, an ID can be associated to only one element within a webpage. On the other hand, class selectors can be applied to more than one element found inside a given webpage.

ID

To apply an ID attribute to an element, it’s enough to insert it right after the opening tag of the same element. For instance, to apply the ‘highlighted’ ID to a paragraph, all you have to write is:

<p id="highlighted">This paragraph will be written in red!</p>

In order to recall an element with an ID on a style sheet, all you have to do is insert the pound symbol (#) in front of the ID. So in this case the rule is the following:

#highlighted { color:red; }

Simple isn’t it? In this way the paragraph with the “highlighted” ID attribute will be of a shiny red color!

Class

As we’ve said before, each ID attribute must be unique. Therefore, if you want to highlight two paragraphs instead of one, you will have to define and apply more than one ID to the elements:

<p id="highlighted1">This paragraph will be written in red!</p>
<p id="highlighted2">This paragraph will also be shown in red!</p>

Followed by the application of these CSS rules:

 #highlighted1 { color:red; } #highlighted2 { color:red; } 

As you can see, it’s not very functional. And if you were to change colors from red to yellow, you would have to edit two different rules, meaning more work to do!

This is when class comes in handy. A class can be applied to more than one element without causing any problems. The procedure involves steps similar to the ones used for IDs, the only exception being the “keyword” that is used:

<h2>I'm a title</h2>
<p class="highlighted">This paragraph will be written in red!</p>
<p class="highlighted">This paragraph will also be shown in red!</p>

Instead of using the pound symbol (#)  to select elements having a class attribute within the stylesheet, you have to use a point, followed by a class name:

.highlighted { color:red; }

Combining class and ID with type selectors

You might be wondering what would happen if you were to apply the “highlighted” class to other elements?

<h2 class="highlighted">This space is for a title which will be shown in red!</h2>
<p class="highlighted">This paragraph will be written in red!</p>
<p class="highlighted">This paragraph will also be shown in red!</p>

Then you should know that the text of all these elements will be turned into a red color. In order to have only the paragraphs changed into red, you can combine classes with type selectors, so you could have something having a similar rule:

p.highlighted { color:red; }

The previous rule must be read like this: “Apply the color red to all of the paragraphs with ‘highlighted’ class attribute.”

Now with this rule only the paragraph will be shown in red, while the title will be visualized normally even though it has a “highlighted” class assigned to it. Thus to apply a class to only a certain type of elements, all you have to do is have the element name followed by a point and class name.

The same can be said for the ID attribute. If you have an <h2> with an ID “title”, you will be able to select it by having the element name followed by pound and the ID value, like you see in the following instance:

<h2 id="title">This space is for an important title</h2>
h2#title { font-size: 28px; }

The size of the h2 element with “title” id (and only this) will have to be changed to 28 pixels.

Remember that the general rules always apply: it’s important that you attribute IDs to single, unique elements, while class is added to repeating elements.

“Structural” selectors

Next we will look at selectors that are formed on the basis of the structure of a document. Before we look at this, let’s see how an HTML page is structured.

Document tree

Let’s look at this simple webpage which talks about something which I love: pizza!

<html>
  <head>
    <title>Neapolitan pizza</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" >
  </head>
  <body>
    <div id="introduction">
      <h1 class="highlighted">Neapolitan pizza</h1>
      <p>The pizza is very simple to prepare, but few people can claim to cook the real Neapolitan pizza.</p>
      <p>This tradition is passed down from generation to generation, and as my grandmother used to say: <q cite="http://nonnamaria.esempio.it" lang="it">The pizza is an art, and you can not learn from books</q></p>
    </div>
    <div>
      <h2>How to do a pizza</h2>
      <h3>Ingredients</h3>
      <ul>
        <li>Warm water</li>
        <li>Flour</li>
        <li>Yeast</li>
        <li>Salt</li>
        <li>Basil</li>
        <li><strong>So much love</strong> :) </li>
      </ul>
      <p class="highlighted">As you see, it's very easy! Here are the simple <strong> </ strong> simple steps to prepare a pizza:</p>
      <ol>
        <li>Place the flour in the bowl, combine the yeast a glass of warm water.</li>
        <li>Once the yeast is dissolved add one tablespoon of olive oil and mix vigorously.</li>
        <li>If the stuffing is soft add more flour; instead, is very hard to add more water and knead again.</li>
        <li>The loaf should appear smooth and uniform. Waiting to happen leavening.</li>
      </ol>
    </div>
  </body>
</html>

As you can see, the page is structured using various HTML tags: <body>, <h1>, <p> and so on. Furthermore, some elements have attributes such as cite or lang which are for the <q> element.

All of the tags are placed one within the other, so a multi-leveled structure is formed. Such structure is commonly known as “tree” because of its resemblance to an upside-down tree. The “top” of the tree, known as root element, or <html>, contains all of the elements found within the sublevels. This applies to all of the elements, until you reach those at the bottom, known as “sheets”, which do not contain any other elements.

albero del documento

Similarly to a genealogy tree, one must establish kinship relations between various tree tags of a given document. Thus, the <html> tag will be the “grandparent” of <title> and great-grandparent of <h1>. Similarly, <h1> will be the child of <div> that has an introduction id.

Descendant selector

The first type of selector we will look at is the descendant selector. Thanks to this type of selector, it’s possible to apply styles to elements that are “descendant” from others. All you have to do is write the various elements separated by a space on the stylesheet, beginning from the ancestor to the descendant. For instance:

div li { font-weight: bold; }

This rule must be read from right to left, written like this: “Select all the <li> elements, which descend from element <div> and change the text into bold”. Note that descendant refers to children, nephews, grandnephews, etc. So in this case both <ul> and <ol> elements are selected being that they are both at a lower level in comparison to div.

Child selector

Let’s continue with the child selector. This one selects elements that are the offspring or children of another element. Using it is simple, all you have to do is separate the various elements with a >, like in the example below:

 p > strong {color: red;} 

This rule must be interpreted as, “select all the <strong> elements, only if they are children of <p> element, and then make them red”. Therefore, all of the other <strong> elements that are on the webpage will not be influenced by this rule.

Adjacent selectors

Now we will move on to something a little more complicated that was first introduced with CSS2. The adjacent element selector applies a style only to the elements that are adjacent to one another. In writing this rule, all that you need to do is add the “+” symbol in-between the adjacent elements:

 h2 + p {color: blue;} 

Here’s a practical example showing you its use:

<h2>This space is for a title</h2>
<p>This is for the paragraph following the title. It would like to be shown in blue!</p>

You might think that the easiest way to change the paragraph is to assign a class or ID to the blue text.

Using the adjacent selector you don’t have to edit your HTML page, rather you can just write this simple rule:

 h2 + p { color:blue; } 

In this way, you’ve made the necessary changes to the paragraph and at the same time you were able to save some valuable space and time. The rule we have just looked at must be read in the following way, “Select the paragraph, but only if this one follows the <h2> title in the HTML page, and turn it blue”.

Exercises

I’ve prepared a series of exercises, to help you familiarize yourself with the selectors you’ve just learned today. For each exercise, we will show you the CSS request; and for HTML you should refer to the pizza webpage. These will be simple requests, similar to the ones we’ve looked at in this article, so don’t be afraid.

The exercises are arranged from easiest to hardest. For the first ones, you will have to apply a simple rule, while for the last ones a little bit of lateral thinking will be needed. Are you ready?

  1. Turn all the paragraphs red.
  2. Turn the background of the “introduction” ID element red.
  3. Turn the <h1> element with “highlighted” class grey.
  4. Turn the strong element into red, but only if it’s child of a paragraph.
  5. Turn the h3 element into green, only if it’s preceded by an h2 element.
  6. Turn the background of a paragraph into green, but only if it’s preceded by an ul element, which in turn is child of the div element.
  7. Turn the li elements –except for the first one – found within the ul and ol lists yellow.
  8. Turn the last element of the ul list into blue.

Other articles in our guide:

Maybe you are interested for..

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:

17 comments

  1. Buddy Love

Trackback e pingback

  1. uberVU - social comments
    Social comments and analytics for this post... This post was mentioned on Twitter by yiw: RT @YIW Do you know there …
  2. 2010-03-15 유용한 링크 | We are connected
    [...] Do you know there are other ways of using css selectors? (Part 1) [...]
  3. Rémi Garcia – Blog » Les sélecteurs en CSS3
    [...] Le deuxième article par Your Inspiration Web est le premier d’une série dont la suite est à paraître, et …
  4. Do you know there are other ways of using css selectors? (Part 1) | Design Newz
    [...] Do you know there are other ways of using css selectors? (Part 1) [...]
  5. Do you know there are other ways of using CSS selectors? (Part 2) | Your Inspiration Web
    [...] This pseudo-class is very interesting (combined with its antagonist :last-child which we will cover in a future article on …
  6. Do you know there are other ways of using CSS selectors? (Part 3) | Your Inspiration Web
    [...] Do you know there are other ways of using css selectors? (Part 1) [...]
  7. Why you should know the new CSS3 selectors? | Your Inspiration Web
    [...] Do you know there are other ways of using css selectors? (Part 1) [...]

Leave a Reply

Current month ye@r day *