User Tools

Site Tools


eg-146:lecture15

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:

  • font size and colour
  • layout properties such as positioning and float
  • print controls for deciding where page breaks should appear

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)

  • Various versions of CSS, but CSS 2 has widest support and CSS 3 is becoming widely supported in the current generation of browsers
  • CSS works best when using HTML in a standards-driven design approach.

Constructing a Style Rule

  • Single property:
h1 { color: red; }
  • Multiple properties:
h1 { color: red; background: yellow; }

See also Defining Selectors


<note>

  • Selector – name of an element, here h1
  • Declaration – ends in semicolon
h1 { declaration; }
  • Property – e.g. color
  • Value – separated from property by a colon:
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

  • It is a good idea to add comments to your style sheets so that you can remember what particularly complicated style rules are supposed to do.
  • CSS uses C-style block comments
/* images will have a solid red 4 pixel border */
 
img { border: 4px solid red}

<note tip>

  • Multiline comments are allowed
  • You can put comments around a style rule to hide it temporarily from a browser. Good for debugging!
  • Comments cannot be nested: /* /* this is illegal */ */
  • End of line comments are also possible as in:
img { border: 4px solid red} /* images will have a solid red 4 pixel border */

</note>

The Cascade: When Rules Collide

The Cascade: Inheritance

  • Inheritance: a CSS property affects the element defined by the selector and is inherited by its descendants:

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

  • Specificity: if there is more than one style that can be applied to a given element, the style which is the most specific wins.

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

  • Which style is applied if there are several styles all addressing same element?
  • Appearance of the style in the “Cascade” determines which style wins.
  • Rule is most locally applied style wins:
    • styles in external style sheets are overridden by
    • styles defined in head of document are overridden by
    • styles defined in internal style sheets are overridden by
    • styles defined in an element are overridden by
    • styles defined in user's own browser!

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.

  • Example: the display property can have values block, inline, list-item, or none.
  • Unlike HTML, such values do not need to be enclosed in quotes; in fact it is illegal to do so!

A Property's Value: Bare numbers

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

  • The most commonly used ones are line-height and z-index.
  • Others are mostly for print and aural style sheets.

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).

  • Example url(file.ext).
  • URLs are relative to the style sheet and not the HTML document that loads the style sheet!

Lengths and percentages

  • Many CSS properties take a length for their value.
  • All length values must contain a quantity and a unit, with no spaces between them
    • for example 3em or 10px
    • an exception is 0 which can be written without units.

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)

  • These should only be used when the size of the medium is known, e.g. when printing.

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>

  • There are several ways to specify colours for CSS properties.
  • First, and easiest, the value can be one of 16 predefined color names, but this limited range can get boring pretty quickly.
  • Here are the 16 predefined color names together with their hexdecimal codes.

</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

  • Hexadecimal values (00-FF): background-color: #7fffff
  • Decimal values (0-255): background-color: rgb(127,255,255)
  • Percentages: background-color: rgb(50%,100%,100%)

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

  • Just a text file with .css extension.
  • Contents are style declarations.

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>

  • You can also use @import inside an external style sheet, e.g. to load common settings prior to customization.
  • As it is ignored by older generation browsers, you can use @import to effectivley hide the advanced properties from browsers that don't support them.

</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!)

  • You can apply a style setting to a single element by using the style attribute.
<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

  • You can designate a style sheet to be used only for a particular output.
  • Uses media=“output in link or @media output { … } to group styles in styesheet.
  • Default is media=“all”

List of media types:

  • all – the default
  • aural – speech only
  • braille – for blind users, touch devices
  • handheld – for mobile devices, e.g. tables, phones, iPod touches, etc.
  • print
  • projection – e.g. slideshows for lectures
  • tty – “teletype” terminals, that is without graphics
  • tv – for smart TVs and set-top boxes

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>

  • Link without title attribute is always applied
  • First link with title is the default
  • Second or subsequent links with titles are available as choices

</note>

Learning from your Peers

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

Demo: www.swan.ac.uk

Defining Selectors

Constructing selectors

  • A selector can define up to five different criteria for choosing the elements that should be formatted:
    • The type or name of an element
    • The context in which the element is found
    • The class or id of an element
    • The pseudo-class of an element or the pseudo-element itself
    • Whether an element has certain attributes and values.
  • A selector can include any combination of these criteria.
  • In addition you can apply the same declaration to a group of 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

  • This selector will choose all of the h2 elements in the document (result)
h2 {
  color: #f00;
}

Selecting elements by class

  • This selector will choose all of the elements which have a class attribute equal to “project” (result):
.about {
  color: red;
}

Selecting elements by id

  • This selector will choose the element with an id equal to “gaudi” (result):
#gaudi {
  color: red;
}

Selecting Elements by Context

  • This selector selects all paragraphs that are children of the article with class “about” (result)
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

  • This descendent selector will only choose those p elements that are children2) of the article element of the about class. In order to qualify, they may not be contained within any other element (result):
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

  • This selector chooses only the p element that is the first child of the article element with the about class (result):
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

  • This selector chooses only those p elements which directly follow a sibling p element within an article with an about class (result):
article.about p+p  { 
  color: red;
}

Pseudo-elements: first line of an element

  • This selector will choose the first line of each p element (result):
p:first-line { 
  color: red;
}

Pseudo-elements: first letter of an element

  • This selector will choose the first letter of each p element (result):
p:first-letter {
  color:red;
}

Pseudo-elements: based on state

  • You can't specify in code what state a link (a element) will have, it is controlled by your visitors. You can however give visual feedback based on the state by use of the following pseudo-elements (result):
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

  • This selector will choose the section elements which have a class attribute (result):
section[class] { 
  color: red; 
}

You can also select based on value:active

  • attribute=“value” – selects attributes whose value is equal to value
  • attribute~=“value” – selects attributes whose value contains value
  • attribute|=“value” – selects attributes whose value equals or starts with value
  • attribute^=“value” – selects attributes whose value begins with value (new in CSS3)
  • attribute$=“value” – selects attributes whose value ends with value (new in CSS3)
  • attribute*=“value” – selects attributes whose value contains at least one match of value (new in CSS3)

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

  • You can also combine selectors each you need to be particularly precise (result):
.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

  • Formatting Text with Styles
  • Layout with Styles
1)
Not Safari or Chrome!
2)
Not grandchildren, great-grand children, and so on.
eg-146/lecture15.txt · Last modified: 2012/03/19 08:15 by eechris