23/05/2020
Adding colour to a web page is fundamental to its visual appeal and user experience. Cascading Style Sheets (CSS) provide a versatile array of methods to inject vibrancy and meaning into your HTML elements, allowing for the styling of text, borders, backgrounds, and much more. This comprehensive guide will delve into the various ways colours can be defined and applied in CSS, alongside crucial considerations for effective and accessible colour usage.

What Can Be Coloured?
Virtually every HTML element can be styled with colour. The primary ways we interact with colour on an element are through its foreground content (like text) and its background. CSS offers specific properties to control these aspects:
Text Colouring
The appearance of text and its associated decorations can be precisely controlled:
color: This is the most fundamental property, defining the colour of the text content and any text decorations like underlines, overlines, or strikethroughs.background-color: Sets the background colour of the element where the text resides.text-shadow: Allows for the addition of shadows to text, enhancing readability or adding stylistic flair. The colour of the shadow is a key parameter here.text-decoration-color: While text decorations usually inherit their colour from thecolorproperty, this allows for an independent colour to be specified for them, offering finer control over underlines, etc.text-emphasis-color: Used primarily for East Asian typography, this property colours the emphasis marks applied to characters.caret-color: This property defines the colour of the text cursor, relevant for input fields and editable elements.
Box Colouring
Beyond text, the 'box model' of elements can also be coloured:
border-color(and related properties likeborder-left-color): Controls the colour of an element's border.background-color: As mentioned, this applies to the entire background area of an element's box, including padding.column-rule-color: Specifically used to colour the rule (line) that separates columns of text.outline-color: Defines the colour of an element's outline, which is drawn outside the border and often used for focus indicators.
Methods for Representing Colours in CSS
To translate the visual concept of colour into a format computers can understand, CSS employs several distinct methods for defining colour values. Each method offers a different approach to specifying hue, saturation, and lightness, or red, green, and blue components.
1. Colour Keywords
CSS defines a standard set of named colours, offering a simple and readable way to apply basic colours. These range from primary and secondary colours (like red, blue, orange) to various shades of grey (black, white, darkgray, lightgrey) and many other specific named colours like cornflowerblue and rebeccapurple.
Example:
p { color: navy; background-color: lightyellow; }While convenient, the limitation here is the fixed number of available keywords (around 140).
2. RGB Colour Values
The RGB (Red, Green, Blue) model is a foundational way to represent colours by specifying the intensity of each of these primary colours. CSS supports RGB in two main formats:
Hexadecimal Notation (Hex Codes)
Hex codes represent colours using a hexadecimal string, typically starting with a '#'. Each pair of hexadecimal digits represents the intensity of red, green, and blue, respectively, ranging from 00 (minimum intensity) to FF (maximum intensity).
#rrggbb: Defines an opaque colour with six hexadecimal digits. For example,#FF0000is pure red.#rrggbbaa: Includes an additional two digits for the alpha channel, controlling opacity.#FF000080would be a semi-transparent red (50% opaque).#rgb: A shorthand for six-digit hex codes where each digit is doubled (e.g.,#F00is equivalent to#FF0000).#rgba: Shorthand for eight-digit hex codes.#F008is equivalent to#FF000088(a red with 50% opacity).
Example:
.element { color: #336699; background-color: #f0f0f0; }Functional Notation (rgb() and rgba())
This method uses a function-like syntax. The rgb() function takes three arguments for red, green, and blue, which can be integers from 0 to 255 or percentages from 0% to 100%. The rgba() function adds a fourth argument for alpha transparency, a value between 0.0 (fully transparent) and 1.0 (fully opaque), or a percentage from 0% to 100%.

Example:
.element { color: rgb(255, 100, 0); /* Orange */ background-color: rgba(0, 0, 255, 0.5); /* Semi-transparent blue */ }3. HSL Colour Values
The HSL (Hue, Saturation, Lightness) model offers a more intuitive way to adjust colours, often preferred by designers. It breaks down colour into three components:
- Hue (H): Represents the colour itself, measured as an angle on a colour wheel (0° to 360°). 0° is red, 120° is green, 240° is blue. Units like degrees (
deg), turns (turn), radians (rad), or grads (grad) can be used. If no unit is specified, degrees are assumed. - Saturation (S): The intensity of the colour, expressed as a percentage. 0% is completely desaturated (a shade of grey), while 100% is the most vibrant version of the hue.
- Lightness (L): The brightness of the colour, also a percentage. 0% is black, 100% is white, and 50% represents the full, unadulterated colour.
HSL colours are defined using the hsl() function, with an optional hsla() for alpha transparency.
Example:
.element { color: hsl(120, 100%, 50%); /* Pure green */ background-color: hsla(30, 80%, 60%, 0.7); /* Semi-transparent yellowish-orange */ } 4. Other Colouring Technologies
While CSS is the primary tool for styling, other web technologies can also define or generate colours:
- Canvas API: Allows for pixel-level drawing within an HTML
<canvas>element, enabling dynamic colour generation and manipulation. - SVG (Scalable Vector Graphics): A vector image format that uses XML to describe graphics. Colours can be defined within SVG code using similar methods (keywords, hex, RGB, HSL) and embedded in HTML.
- WebGL: An API for rendering interactive 2D and 3D graphics within a web browser, based on OpenGL ES. It allows for complex colour rendering and effects.
Applying Colours in a Web Document
Colours are typically applied using either CSS stylesheets or dynamically via JavaScript.
Via CSS Stylesheets
This is the standard and most common method. Styles are written in separate .css files or within <style> tags in the HTML document's <head> section.
Example Breakdown
Consider the following HTML and CSS:
<div class="conteneur"> <div class="boite boiteGauche"> <p>Voici la première boîte.</p> </div> <div class="boite boiteDroite"> <p>Voici la seconde boîte.</p> </div> </div>.conteneur { width: 620px; height: 110px; margin: 0; padding: 10px; border: 6px solid mediumturquoise; } .boite { width: 290px; height: 100px; margin: 0; padding: 4px 6px; font: 28px "Marker Felt", "Zapfino", cursive; display: flex; justify-content: center; align-items: center; } .boiteGauche { float: left; background-color: rgb(245, 130, 130); /* Light red */ outline: 2px solid darkred; } .boiteDroite { float: right; background-color: hsl(270deg, 50%, 75%); /* Medium purple */ outline: 4px dashed rgb(110, 20, 120); /* Dark purple outline */ color: hsl(0deg, 100%, 100%); /* White text */ text-decoration: underline wavy #88ff88; /* Wavy green underline */ text-shadow: 2px 2px 3px black; } In this example:
- The
.conteneurhas a turquoise border. - Both boxes share common styles defined in
.boite. .boiteGauchehas a light red background and a dark red outline..boiteDroitefeatures a medium purple background, a dashed dark purple outline, white text, a wavy green underline, and a black text shadow.
Allowing User Colour Selection
HTML5 introduced the <input type="color"> element, providing a native browser interface for users to select colours. The selected colour is typically returned as a hexadecimal string.
Example: Live Border Colour Changer
This example uses HTML, CSS, and JavaScript to allow a user to change the border colour of a `div` in real-time.
<div id="box"> <label for="colorPicker">Border Colour:</label> <input type="color" value="#8888ff" id="colorPicker" /> <p id="output"></p> </div>#box { width: 500px; height: 200px; border: 2px solid #8888ff; padding: 4px 6px; font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif"; } let colorPicker = document.getElementById("colorPicker"); let box = document.getElementById("box"); let output = document.getElementById("output"); // Set initial border colour box.style.borderColor = colorPicker.value; // Update border colour as the picker changes colorPicker.addEventListener("input", function (event) { box.style.borderColor = event.target.value; }, false); // Display the chosen colour value when selection is finalized colorPicker.addEventListener("change", function (event) { output.innerText = "Chosen Colour: " + colorPicker.value; }, false); The JavaScript listens for the input event to update the border colour dynamically and the change event to display the final hex code.

The Art of Colour Selection
Choosing the right colours is crucial for a website's effectiveness and aesthetic. Poor colour choices can hinder usability, reduce attractiveness, and even make content inaccessible.
Finding the Right Colours
Several tools and strategies can aid in colour selection:
- Base Colour Selection: Start with a colour that naturally relates to your website's theme or content. Inspiration can be drawn from existing designs, imagery, or even emotional associations. Tools like browser extensions (e.g., ColorZilla) can help 'sample' colours from web pages.
- Building a Palette: Once a base colour is chosen, use colour theory tools to generate harmonious palettes. Many tools offer features to simulate how colours appear to people with various forms of colour blindness. Popular tools include the MDN Colour Picker, Paletton, and Adobe Color CC.
- Neutral Colours: Always include neutral colours like white, black, and shades of grey in your palette for balance and readability.
- Consistency: Use colours purposefully and sparingly to maintain a cohesive design. Accent colours should highlight important elements rather than being used ubiquitously.
Colours and Accessibility
Colour choices have significant accessibility implications. Ensuring sufficient contrast between text and background is paramount for readability, especially for users with visual impairments like colour blindness.
- Understand Colour Blindness: Familiarise yourself with different types of colour vision deficiency (e.g., red-green colour blindness).
- Never Rely on Colour Alone: Information should not be conveyed solely through colour. Use text labels, icons, or other visual cues in conjunction with colour to ensure all users can understand the information. For instance, use both colour and text to indicate success or failure states.
Example Palette Design (Mars Theme)
Imagine designing a website for a game set on Mars:
- Inspiration: Search for images of Mars.
- Base Colour: Use a colour picker to sample a rusty orange-red (e.g.,
#D79C7A). - Palette Generation: Use a tool like Paletton. Input the base colour and explore options like 'Monochromatic' (for variations) or 'Complementary' (for contrasting colours). Adding a complementary colour might yield something like
#508D7C(a teal). Exploring 'Triad' might give#556E8D(a blue-grey). - Refinement: Combine these colours with neutrals, ensuring adequate contrast for text. For example, a dark grey for text on a light beige background.
Key Considerations:
- Contrast Ratio: Aim for sufficient contrast between text and background. Tools are available to check WCAG (Web Content Accessibility Guidelines) contrast ratios.
- Visual Appeal: While accessibility is key, ensure the colours are aesthetically pleasing and fit the website's theme. Seek feedback on your colour choices.
FAQ
How do I use a colour name in CSS?
You can use predefined colour names directly with properties like color or background-color. For example: p { color: red; }. However, the selection of named colours is limited.
How do I change the colour of text?
Use the color CSS property. You can set it to a colour keyword, a hex code, or an RGB/HSL value.
<!DOCTYPE html> <html> <head> <style> body { color: red; } h1 { color: #00FF00; } /* Green */ p { color: rgb(0, 0, 255); } /* Blue */ </style> </head> <body> <h1>This heading will be green.</h1> <p>This paragraph will be blue.</p> The page body text is red. </body> </html>By mastering these colour representation and application techniques, you can create visually engaging, informative, and accessible web experiences.
If you want to read more articles similar to Mastering CSS Colours: From Basics to Best Practices, you can visit the Automotive category.
