Table of Contents

~~SLIDESHOW~~

Introduction to Cacscading Stylesheets (CSS)

Contact Hour 15: To be discussed on Monday 20th March, 2012.

Lecturer: Dr Chris P. Jobling.


The contents of these notes and all the examples are from Chapters 7–9 of Castro and Hyslop, HTML5 and CSS3: Visual Quickstart Guide, 7th Ed., PeachPit Press, 2012.

These notes are incomplete and you are invited to contribute to them by getting an account on this wiki.

Introduction to CSS

CSS Building Blocks

What is a Style Sheet? (1)

A style sheet is a text file that contains one or more rules that determine – through properties and values – how certain elements in a web page should be displayed.

What is a Style Sheet? (2)

There are CSS properties for controlling such basic formatting as:

What is a Style Sheet? (3)

There are also several dynamic properties such as visibility which are useful for creating drop-down menus and other interactive components.

What is a Style Sheet? (4)

Constructing a Style Rule

h1 { color: red; }
h1 { color: red; background: yellow; }

See also Defining Selectors


<note>

h1 { declaration; }
color: red;

</note>

Adding Comments to a Style Rule The Cascade: When Rules Collide A Property's Value CSS Colours

Adding Comments to a Style Rule

/* images will have a solid red 4 pixel border */
 
img { border: 4px solid red}

<note tip>

img { border: 4px solid red} /* images will have a solid red 4 pixel border */

</note>

The Cascade: When Rules Collide

The Cascade: Inheritance

Example 1

If

p { color: red; }

is used with

<p>I'm some <em>emphasized text</em> inside a red paragraph. What colour am I?</p>

Choices: 1 black; 2: red; 3: don't know.

Answer

2. I'm <html><span style=“color:red”>red</span></html>. The em element is a descendant of the red p so it will also be red.

If you want a yellow emphasis inside red paragraphs use:

p em { background-color: yellow; }

The Cascade: Specificity

Example 2

If:

p { color: red } p.group { color: blue } 
p#one { color: green } p#one { color: magenta }

What colour will each of the following paragraphs be? (choices 1: red; 2: blue; 3: green; 4: magenta)

<p>1. I'm a generic paragraph. What colour am I?</p>
 
<p class="group">2. I'm a group-class p paragraph. 
What colour am I?</p>
 
<p class="group" id="one">3. I'm a group-class p element with 
and id of one. What colour am I?</p>

Answers

<p>1. I'm a generic paragraph. I'm red! (1)</p>
 
<p class="group">2. I'm a group-class p paragraph.
 I will be blue (2)</p>
 
<p class="group" id="one">3. I'm a group-class p 
element with and id of one. There are four rules that 
could apply. The first two are overruled by the more 
specific last two. The position breaks the tie between these two: 
the one that appears later wins, and thus I am magenta! (4)</p>

Don't believe me? Try it yourself!

The Cascade: Location

The Cascade: Location

Any styles that are defined up to the point of an @import are overridden by the styles defined in the imported style sheet.

A Property's Value: Inherited

Use the inherit value when you want to explicitly state that a property will be the same as the element's parent.

A Property's Value: Predefined values

Most CSS properties have a few predefined values that can be used.

A Property's Value: Bare numbers

Very few CSS properties accept numbers without unit, e.g. 3.

A Property's Value: URLs

URLs are used for properties that allow you to set the location of another file (e.g. another stylesheet, or a background image).

Lengths and percentages

Lengths and percentages: Relative to font size

E.g. 2em meaning twice the size of the parent; 3ex meaning three times the height of an x character.

Lengths and percentages: Relative to resolution

E.g. 16px is the size of 16 pixels on the current resolution (most monitors display between 72 and 96 pixels per inch).

Lengths and percentages: Absolute units

These are self explanatory: inches (in), centimeters (cm), millimeters (mm), points (pt), and picas (pc)

Lengths and percentages: Percentages

E.g. 65% are relative to some other value. For a font-size 50% is same as 0.5em.

Lengths and percentages: Recommendations

In general, to cope with the variation of monitor resolution, etc, em and ex' or percentage units should be used in preference to pixel or absolute units. The only exception is stylesheets for print where in general the size of the medium is known (e.g. A4 is 8.27in x 11.69in) – but you are not likely to be dealing with print very often.

CSS Colors

<html> <table border=“1”> <tr>

<td style="background-color:aqua">Aqua<br />#00FFFF</td>
<td style="background-color:black;color:white">Black<br />#000000</td>
<td style="background-color:blue;color:white">Blue<br />#0000FF</td>
<td style="background-color:fuchsia">Fuchsia<br />FF00FF</td>

</tr> <tr>

<td style="background-color:gray">Gray<br />#808080</td>
<td style="background-color:green;color:white">Green<br />#008000</td>
<td style="background-color:lime">Lime<br />#00FF00</td>
<td style="background-color:maroon;color:white">Maroon<br />800000</td>

</tr> <tr>

<td style="background-color:navy;color:white">Navy<br />#000080</td>
<td style="background-color:olive;color:white">Olive<br />#808000</td>
<td style="background-color:purple;color:white">Purple<br />#8000080</td>
<td style="background-color:red">Red<br />FF0000</td>

</tr> <tr>

<td style="background-color:silver">Silver<br />#C0C0C0</td>
<td style="background-color:teal;color:white">Teal<br />#008080</td>
<td style="background-color:white;color:black">White<br />#FFFFFF</td>
<td style="background-color:yellow">Yellow<br />FFFF00</td>

</tr> </table> </html> * Note that the colour names and hexadecimal values are not case sensitive, not even in HTML.


<note>

</note>

Defining Colours with RGB Values

<html><table border=“1”><tr><td style=“background-color: #7fffff;”>To Get this Colour</td></tr></table></html> Use

See also the web safe colour palette (colours which look reasonable on most monitors) www.cookwood.com/html/colors/websafecolors.html.

Additional Colour Controls in CSS3

CSS3 introduces two additional ways to define colours:

/* Hue-Saturation-Lumonosity */
p color: hsl(H,S%,L%);
<code>
<code css>
/* alpha (transparency */
p.a color rgba(r%, b%, g%, a%);
p.b color hsla(H,S%,L%,A%);

See Castro and Hyslop for examples.


<note> For HSL, H is a number from 0 to 360 representing points on colour wheel that starts at red at 0/360 and goes through yellow at 60, green at 120, cyan at 180, blue at 240 and magenta at 300. S is the saturation as a percentage with low numbers moving towards grey, and for luminosity large percentages move towards white.

Alpha is transparency with low numbers being more see-through than high numbers. </note>

Colour Wheels and Colour Pickers

Bandon Mathis' HSL Color Picker: hslpicker.com

Pick a Hue from 0 to 360 and with saturation at 100 and luminosity at 50 and
you'll have the purest form of that color.
Reduce the saturation and you move towards gray. Increasing the luminosity
moves you towards white, decreasing it moves you towards black.

See also www.workwithcolor.com/hsl-color-picker-01

Working With Stylesheets

An External Style Sheet

Linking an external style sheet

<head>
  <meta charset="utf-8" />
  <title>La Casa Mil&agrave;</title>
  <link rel="stylesheet" href="base.css" />
</head>

An Internal Style sheet

Style commands put in header

<head>
  <meta charset="utf-8" />
  <title>La Casa Mil&agrave;</title>
  <style>
    img {color: red; border: solid; }
  </style>
<head>

Order is Important

* Local styles will always override any styles that are imported before the style tag. For example:

<head>
 <link rel="stylesheet" href="base.css />
 <style>
   border-style: dashed;
 </style>
</head>

May have a different effect from

<head>
 <style>
   border-style: dashed;
 </style>
 <link rel="stylesheet" href="base.css />
</head>

The code for bass.css is:

@charset "UTF-8";
 
/* A simple style sheet */
 
img {
  border: 4px solid red;
}

Aside: Importing External Style Sheets

* Import definitions from another style sheet (not recommended by Castro and Hyslop)

<head>
 <meta charset="utf-8" />
 <title>La Casa Mil&agrave;</title>
 <style />
   @import url("external.css")
   h1, h2 { color: red; }
 </style>
</head>

<note>

</note> <note warning> Relative URLs in style sheets are interpreted relative to the style sheet, not the HTML document. </note>

Aside: Applying Styles Locally (never do this!)

<blockquote cite="Richard III, Will Shakespeare" style="color: red;">
Now is the winter of our discontent<br />
made glorious summer by this Son of York!</blockquote>

Produces: <html> <blockquote cite=“Richard III, Will Shakespeare” style=“color: red;”> Now is the winter of our discontent<br /> made glorious summer by this Son of York!</blockquote> </code> </html>


<note warning> There is an exception to every rule and local style definitions should only be used for one-off changes or exceptions. Overuse (e.g. as in Word or Frontpage) makes HTML code hard to read and harder to maintain.</note>

Media-Specific Style Sheets


List of media types:

Alternate Style Sheets

<head>
    <meta charset="utf-8" />
    <title>La Casa Mil&agrave;</title>
    <!-- Base style sheet: always applied -->
    <link rel="stylesheet" href="base.css" />
    <!-- Preferred style sheet: default -->
    <link rel="stylesheet" href="preferred.css"  title="Dashed"/>
    <!-- Alternative style sheet -->
    <link rel="stylesheet" href="alternate.css"  title="Dotted" />
</head>

<note>

</note>

Learning from your Peers

Open the page. View source. Follow link to stylesheet.

Demo: www.swan.ac.uk

Defining Selectors

Constructing selectors

Another Example

To illustrate the various style selectors, and how the work, we apply the simple style declaration color: red, to various selections of an example document. Follow the links to Chapter 9: Defining Selectors to see these examples live.


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Antoni Gaud&iacute; &ndash; Introduction</title>
    <link rel="stylesheet" media="screen" href="nostyle.css" />
  </head>
  <body>
    <article id="gaudi" class="about">
      <h1 lang="es">Antoni Gaud&iacute;</h1>
      <p>
        Many tourists are drawn to Barcelona to see Antoni Gaud&iacute;'s incredible
        architecture.
      </p>
      <p>
        Barcelona <a href="http://www.gaudi2002.bcn.es/english/flash/home/GO.htm">celebrated</a> the 150th anniversary of Gaud&iacute;'s birth in 2002.
      </p>
      <section class="project">
        <h2 lang="es">La Casa Mil&agrave;</h2>
        <p>
          Gaud&iacute;'s work was essentially useful. La Casa Mil&agrave; is an apartment
          building and <em>real people</em> live there.
        </p>
      </section>
      <section class="project">
        <h2 lang="es">La Sagrada Fam&iacute;lia</h2>
        <p>
          The complicatedly named and curiously unfinished Expiatory Temple of the
          Sacred Family is the <em>most visited</em> building in Barcelona.
        </p>
      </section>
    </article>
  </body>
</html>

<note> It is important to note that only the style declaration is changing! </note>

A Catalogue of style selectors

I will demonstrate these in the lecture.


My cheat-sheet:

  1. Select by name: name.css
  2. Select by class: class.css
  3. Select by id: classid.css
  4. Select by context: context.css
  5. Selecting elements by parent: child.css
  6. Selecting the first child element: firstchild.css
  7. Selecting the first child element: firstchild2.css
  8. Selecting sibling elements: adjsibling.css
  9. Pseudo-elements: first line of an element: firstline.css
  10. Pseudo-elements: first letter of an element: firstletter.css
  11. Pseudo-elements: selecting elements based on state: state.css
  12. Selecting Elements based on Attributes: attribute.css
  13. Selecting groups of elements: group.css
  14. Combining selectors: combine.css

Selecting elements by name

h2 {
  color: #f00;
}

Selecting elements by class

.about {
  color: red;
}

Selecting elements by id

#gaudi {
  color: red;
}

Selecting Elements by Context

article.about p {
  color: red;
}

Other ways to get the same effect

Any p that is a descendant of any article. The least specific approach.

article p {
  color: red;
}

Any p that is a descendant of any element with the about class. The second most specific of the three.

.about p {
  color: red;
}

<note> All three selectors above provide the same effect, so only one of them is required to make the text red.

The second selector – article p {} – is preferred because it's the least specific. Generally speaking, [Castro and Hyslop] recommend making your selectors only as specific as necessary to yield the desired effect. That way, it's easier to override a selector with a more specific one for times when you want the style to deviate. </note>

Selecting elements by parent

article.about > p {
 color: red;
}

<note> Only the first two p elements are children of the artcle element with the about class. The other two p elements are children of the section elements within the article. </note>

Selecting the first child element

article.about p:first-child { 
  color: red;
}

<note> :first-child is a pseudo-class. In this case, nothing happens, because h1 not p is the first child element of the article with class about! </note>

Selecting the first child element (2)

article.about h1:first-child { 
  color: red;
}

h1 is the first child so this works

Selecting sibling elements

article.about p+p  { 
  color: red;
}

Pseudo-elements: first line of an element

p:first-line { 
  color: red;
}

Pseudo-elements: first letter of an element

p:first-letter {
  color:red;
}

Pseudo-elements: based on state

a:link { color: red; }
a:visited { color: orange; }
a:focus { color: purple; } 
a:hover { color: green; } 
a:active { color: blue; } 

Explanation: the link is shown in red. As the mouse moves over the link (hover) it changes to green. If link has focus (use tab key to achieve this) it turns purple. While you press the link (before you release) it is blue. When the link has been visited it turns orange.

Selecting elements based on attributes

section[class] { 
  color: red; 
}

You can also select based on value:active

See Tips on Pages 234–235 of Castro and Hyslop for examples of how to ue these

Groups of elements

You can select any number of individual selectors, as long as you separate each with a comma (result):

h1, 
h2 {
  color:red;
}

The selectors do not need to be on a line of their own, but many developers use this convention as it makes the style definition (and what elements it applies to) easier to read at a glance. Particularly when there are a lot!

Combining selectors

.project h2[lang|="es"] + p em {
  color: red;
}

Explanation “Chose only the e, elements that are found in the p elements that are immediately adjacent to h2 elements that have a lang attribute whose value begins with es inside any element with a class equal to project.

The example above is an extreme one to demonstrate what's possible. Following are a few ways you could achieve the same results, moving from least specific to most specific:

em {
  color: red;
}
.project em {
  color: red;
}
.about .project em {
  color: red;
}
#gaudi em {
  color: red;
}

Summary

Next

1)
Not Safari or Chrome!
2)
Not grandchildren, great-grand children, and so on.