Web Development

Dr Derek Bridge
School of Computer Science & Information Technology
University College Cork

Lecture Objectives

  • learn about CSS custom properties (variables!)
  • learn to use custom properties to set up a 'theme' for a web site
  • see a case study

Warning

Fog of details ahead!

Do not 'learn off'.
Look-up when needed.

Colour Schemes

You'll probably pick a colour scheme: a small number of colours that you use throughout your web site.

To change the colour scheme, you may have to make changes to many CSS rules.

This is a case where CSS custom properties can help.

Repetition!


header, nav, aside, footer {
    color: black;
    background-color: lightgray;
}
        
main {
    color: white;
    background-color: green;
}
        
table {
    border: 1px solid green;
}
    

CSS Custom Properties

  • You are familiar with variables in Python.
  • CSS has something similar to variables, called custom properties:
    • They help us to avoid repetition in the stylesheet;
    • They can give meaningful names to complex properties to improve readability;
    • They can be set by JavaScript, e.g. for theme switching.

Defining a Custom Property

They must be defined within a CSS rule, e.g.:


html {
    --base-color: black;
    --base-bgcolor: lightgray;
    --main-color: white;
    --main-bgcolor: green;
}
    

Their name must begin with -- and, unlike the rest of CSS, their name is case-sensitive.

Using a Custom Property

The var function retrieves the value of the custom property, e.g.:


header, nav, aside, footer {
    color: var(--base-color);
    background-color: var(--base-bgcolor);
}
        
main {
    color: var(--main-color);
    background-color: var(--main-bgcolor);
}
        
table {
    border: 1px solid var(--main-bgcolor);
}
    

Themes

Use custom properties for more than just your colour scheme:

  • spacing: margins, padding
  • borders
  • fonts, especially font sizes

Case Study

G'luck!