Five Examples Using CSS Selectors

Putting various CSS selectors to the test.

Contents

  1. Alternating Paragraph Colours
  2. Selectively Styling Ordered Lists
  3. Selectively Styling Anchors
  4. Experiments with Multiple Classes
  5. Selecting with ID, Class, and Attribute

Alternating Paragraph Colours

You can see how my attempt looks here

<!DOCTYPE HTML>
<html>
  <head>
    <title>Alternating Paragraph Colours</title>
    <style>

      body {
        background-color: cornsilk;
      }

      .bar1 {
        background-color: white;
      }

      .bar2 {
        background-color: #f0fff7;
      }

    </style>
  </head>
  <body>
    <h1>Alternating Paragraph Colours</h1>
    <p class="bar1">Fac ergo, mi Lucili, quod
    aequitatem tuam decet, desine beneficium fortunae
    male interpretari: abstulit, sed dedit</p>

    <p class="bar2">Ideo amicis avide fruamur quia
    quamdiu contingere hoc possit incertum est.
    Cogitemus quam saepe illos reliquerimus in aliquam
    peregrinationem longinquam exituri, quam saepe
    eodem morantes loco non viderimus: intellegemus
    plus nos temporis in vivis perdidisse.</p>

    <p class="bar1">Feras autem hos qui
    neglegentissime amicos habent, miserrime lugent,
    nec amant quemquam nisi perdiderunt? ideoque
    tunc effusius maerent quia verentur ne dubium
    sit an amaverint; sera indicia affectus sui
    quaerunt.</p>

    <p class="bar2">Si habemus alios amicos, male de
    iiset meremur et existimamus, qui parum valent in
    unius elati solacium; si non habemus, maiorem
    iniuriam ipsi nobis fecimus quam a fortuna
    accepimus: illa unum abstulit, nos quemcumque non
    fecimus.</p>

    <p class="bar1">Deinde ne unum quidem nimis
    amavit qui plus quam unum amare non potuit. Si
    quis despoliatus amissa unica tunica complorare
    se malit quam circumspicere quomodo frigus
    effugiat et aliquid inveniat quo tegat scapulas,
    nonne tibi videatur stultissimus? Quem amabas
    extulisti: quaere quem ames. Satius est amicum
    reparare quam flere.</p>

    <p class="bar2">Scio pertritum iam hoc esse quod
    adiecturus sum, non ideo tamen praetermittam
    quia ab omnibus dictum est: finem dolendi
    etiam qui consilio non fecerat tempore invenit.
    Turpissimum autem est in homine prudente
    remedium maeroris lassitudo maerendi: malo
    relinquas dolorem quam ab illo relinquaris;
    et quam primum id facere desiste quod, etiam
    si voles, diu facere non poteris.</p>

    <p class="bar1">Annum feminis ad lugendum
    constituere maiores, non ut tam diu lugerent,
    sed ne diutius: viris nullum legitimum tempus
    est, quia nullum honestum. Quam tamen mihi ex
    illis mulierculis dabis vix retractis a rogo,
    vix a cadavere revulsis, cui lacrimae in totum
    mensem duraverint? Nulla res citius in odium
    venit quam dolor, qui recens consolatorem
    invenit et aliquos ad se adducit, inveteratus
    vero deridetur, nec immerito; aut enim
    simulatus aut stultus est.</p>

    <p class="bar2">Haec tibi scribo, is qui Annaeum
    Serenum carissimum mihi tam immodice flevi ut,
    quod minime velim, inter exempla sim eorum quos
    dolor vicit. Hodie tamen factum meum damno et
    intellego maximam mihi causam sic lugendi
    fuisse quod numquam cogitaveram mori eum ante
    me posse. Hoc unum mihi occurrebat, minorem
    esse et multo minorem - tamquam ordinem fata
    servarent!</p>
  </body>
</html>

Notes

  1. a style was applied to the body to give it a background colour;
  2. two classes (called bar1 and bar2) were created to style the paragraphs;
  3. the classes were alternately applied to the paragraphs.1

As a reminder, you have previously seen that HTML collapses any extra white space between text, so breaking the paragraph content over several lines (so it comfortably fits on the page) doesn’t affect the way it appears when rendered.

Selectively Styling Ordered Lists

You can see how my attempt looks here

<!DOCTYPE HTML>
<html>
  <head>
    <title>Selectively Styling Lists</title>
    <meta charset="utf-8" />

    <style>

      body {
        background-color: aliceblue;
      }

      li {
        margin: 16px;
      }

      [reversed] {
        background: lime;
      }

    </style>

  </head>
  <body>
    <h1>Selectively Styling Lists</h1>

    <h2>Top 5 Reasons to Learn HTML & CSS</h2>
    <ol>
      <li>It's fun!</li>
      <li>To be cool!</li>
      <li>Create your own webpages.</li>
      <li>Have a hobby.</li>
      <li>Indulge your curiosity.</li>
    </ol>

    <h2>Counting Down 5 Reasons to Learn HTML & CSS</h2>
    <ol reversed>
      <li>It's fun!</li>
      <li>To be cool!</li>
      <li>Create your own webpages.</li>
      <li>Have a hobby.</li>
      <li>Indulge your curiosity.</li>
    </ol>
  </body>
</html>

Notes

  1. a style was applied to the body to give it a background colour;
  2. a style was applied to the list items to space them out a bit more
  3. reverse ordered lists are selected for styling using an attribute selector. (It is also acceptable to style the reverse ordered list using a class.)

Selectively Styling Anchors

You can see how my attempt looks here

<!DOCTYPE HTML>
<html>
  <head>
    <title>Selectively Styling Anchors</title>
    <meta charset="utf-8" />

    <style>

      body {
        background-color: #FDF9FF;
      }

      li {
        margin: 24px;
      }

      [target] {
        padding: 7px;
        border: blue 3px solid;
        background: lightblue;
      }

      [download] {
        padding: 5px;
        background: yellow;
      }

    </style>
  </head>
  <body>
    <h1>Selectively Styling Anchors</h1>
    <p>You can choose to:</p>

    <ul>
      <li>View the
        <a href="/sample/18-styling-anchors.txt">
          source code.
        </a>
      </li>
      <li>View the
        <a href="/sample/18-styling-anchors.txt"
           target="_blank">source code</a>
        in a new tab.
      </li>
      <li>Download the
        <a href="/sample/18-styling-anchors.html"
          download>source code.</a>
      </li>
    </ul>
  </body>
</html>

Notes

  1. a style was applied to the body to give it a background colour;
  2. the anchors were structured using an unordered list. There is no requirement to do this. I did it because it gave a bit of structure.
  3. the list items were given a bit more margin. This was done after styling the links and deciding I needed more space.
  4. the anchor tags were selected and styled based on their attributes. You could have applied a class to each anchor as well. But I think using the attribute is better since that information is already part of the anchor. If you use a class, you need to add additional information to the tag.
  5. you will notice the source code for the first two points to a .txt file instead of an HTML file. This is because a browser will attempt to render HTML files as HTML (i.e. it will display it as an HTML page, not source code).
  6. I use relative links rather than a full URL. Obviously, whatever links you use will need to be appropriate for your environment.

Experiments with Multiple Classes

You can see how my attempt looks here

<!DOCTYPE HTML>
<html>
  <head>
    <title>Multiple Class Interaction</title>
    <meta charset="utf-8" />

    <style>

      body {
        background-color: #FFF9F4;
      }

      .class-1 {
        background-color: yellow;
        color: red;
      }

      .class-2 {
        background-color: silver;
      }

      .class-3 {
        background-color: lightgreen;
      }

    </style>
  </head>
  <body>
    <h1>Multiple Class Interaction</h1>
    <p class="class-1 class-2">
      This paragraph is styled with class-1 and class-2.
    </p>
    <p class="class-2 class-1">
      This pragraph is styled with class-2 and class-1.
    </p>
    <p class="class-1 class-3">
      This paragraph is styled with class-1 and class-3.
    </p>
    <p class="class-3 class-1">
      This paragraph is styled with class-3 and class-1.
    </p>
    <p class="class-2 class-3">
      This paragraph is styled with class-2 and class-3.
    </p>
    <p class="class-3 class-2">
      This paragraph is styled with class-3 and class-2.
    </p>
  </body>
</html>

Notes

  1. a style was applied to the body to give it a background colour;
  2. 3 simple classes were defined. All of them define a different background colour;
  3. the classes were mixed and matched on various paragraph elements;
  4. the order of application of classes to an element doesn’t matter – i.e., class-1 class-2 gives the same result as class-2 class-1;
  5. the order in which the classes are defined does matter. If you move the definition of class-1 after class-3, you will notice that the applied styles change. This is the cascading aspect of CSS. In general, the most recently seen attribute value is the one that is applied. It is a bit more complicated than that. We will explore this more in a future tutorial.

Selecting with ID, Class, and Attribute

You’ve seen that you can apply multiple styles to an element by using multiple classes. You can also apply multiple styles by using a variety of selectors.
You can see how my attempt looks here

<!DOCTYPE HTML>
<html>
  <head>
    <title>Multiple Attribute Styling</title>
    <meta charset="utf-8" />

    <style>

      body {
        background-color: ##F0FFFF;
      }

      .class {
        color: red;
      }

      #id {
        background-color: yellow;
      }

      [target] {
        border: 2px solid black;
      }

      a {
        margin: 50px;
        padding: 10px;
      }

    </style>
  </head>
  <body>
    <h1>Multiple Attribute Styling</h1>
    <p>Any styling selectors you define are applied
      to any and all elements that match the selector.
      So you can have multiple styles applied by
      multiple different selectors.
    </p>
    <p>The following element receives 4 different
      styles applied by 4 different selectors:
    </p>
    <a id="id" class="class"
       href="http://example.com" target=_blank>
      I wonder where this link goes?
    </a>
  </body>
</html>

Notes

  1. a style was applied to the body to give it a background colour;
  2. 4 different styles are defined. Each style uses a different selector;
  3. all of the styles combine on the anchor tag
  4. while classes are the main way to define styles, remember that there are other selectors as well. In a future, tutorial we will explore how the different styles combine when they overlap – i.e., two or more selectors style the same property differently.

  1. In a future tutorial, you will see how you can selectively style alternating paragraphs without needing to explicitly apply a class to each one.