CSS - Cascading Style Sheets
Welcome to the world of Cascading Style Sheets (CSS)! If you've ever wondered how websites get their attractive looks, their layouts, and their overall visual appeal, the answer is CSS. HTML provides the structure and content of a webpage, but it's CSS that breathes life into it, transforming plain text and images into a dynamic and engaging experience for the user.
Think of HTML as the building blocks of a house – the walls, the rooms, the doors. CSS, on the other hand, is the interior designer and exterior decorator. It decides the paint colours, the furniture placement, the type of flooring, the style of the windows, and even the landscaping. Without CSS, websites would look like unstyled documents, much like a basic text file.
What is CSS?
CSS stands for Cascading Style Sheets. It's a stylesheet language used to describe the presentation of a document written in a markup language. The most common use of CSS is to style web pages written in HTML and XHTML. CSS describes how elements should be rendered on screen, on paper, in speech, or on other media.
Why Use CSS?
The primary benefit of using CSS is to separate the content of a webpage (written in HTML) from its presentation (defined by CSS). This separation offers several advantages:
- Easier Maintenance: If you need to change the look of your entire website, you only need to edit the CSS file(s). This is far more efficient than changing the styling on every single HTML page.
- Faster Page Loads: By moving styling information to external CSS files, HTML files become smaller and load faster. Browsers can cache CSS files, meaning they only need to download them once, speeding up subsequent page visits.
- Improved Accessibility: CSS can be used to create different stylesheets for different devices or user preferences (e.g., a high-contrast stylesheet for visually impaired users).
- Consistent Design: CSS ensures a consistent look and feel across all pages of a website, reinforcing brand identity and improving user experience.
- More Control: CSS offers a vast array of properties to control layout, colours, fonts, spacing, and even animations, giving designers fine-grained control over the visual presentation.
How CSS Works: The Cascade
The "Cascading" in Cascading Style Sheets refers to the order in which CSS rules are applied. When multiple CSS rules apply to the same HTML element, the browser needs a way to determine which rule "wins" and gets applied. This is managed through a system of priorities:
- Importance: Rules marked with
!importanthave the highest priority. - Origin and Specificity: Rules from the author (your CSS) generally override rules from the user agent (browser defaults). Within author rules, more specific selectors have higher priority than less specific ones.
- Order: If two rules have the same importance, origin, and specificity, the rule that appears later in the CSS code (or in the HTML document if styles are inline) takes precedence.
Ways to Apply CSS
There are three main ways to incorporate CSS into your HTML documents:
- Inline Styles: Applied directly to an HTML element using the
styleattribute. This is generally discouraged for large projects as it mixes content and presentation.<p style="color: blue; font-size: 16px;">This text is blue and 16px.</p> - Internal Stylesheets: Placed within the
<style>tags in the<head>section of an HTML document. Useful for single-page styling.<head> <style> p { color: green; } </style> </head> - External Stylesheets: The most common and recommended method. CSS rules are written in a separate
.cssfile and linked to the HTML document using the<link>tag in the<head>section.<head> <link rel="stylesheet" href="styles.css"> </head>The
styles.cssfile would contain rules like:p { color: purple; }
Basic CSS Syntax
A CSS rule consists of a selector and a declaration block. The selector points to the HTML element you want to style, and the declaration block contains one or more declarations, each consisting of a property and a value.
selector {
property: value;
property: value;
}
Example:
p {
color: navy; /* 'p' is the selector, 'color' is the property, 'navy' is the value */
text-align: center; /* 'text-align' is the property, 'center' is the value */
}
Common CSS Properties and Concepts
Let's dive into some of the core CSS concepts you'll use daily.
Colours
Colours are fundamental to web design. CSS allows you to set the colour of text, backgrounds, borders, and more. There are several ways to specify colours in CSS:
Colour Values
- Keywords: Predefined colour names.
Common keywords include:color: red; background-color: lightblue;black,white,red,blue,green,yellow,transparent, etc. - RGB (Red, Green, Blue): Specifies colours using a combination of red, green, and blue values, ranging from 0 to 255.
color: rgb(255, 0, 0); /* Pure red */ background-color: rgb(0, 128, 0); /* Green */ - RGBA (Red, Green, Blue, Alpha): Similar to RGB but includes an alpha channel for transparency (0.0 for fully transparent, 1.0 for fully opaque).
background-color: rgba(0, 0, 255, 0.5); /* Semi-transparent blue */ - Hexadecimal (Hex): A six-digit hexadecimal code (
#RRGGBB) where each pair represents red, green, and blue values.
Shorthand hex codes likecolor: #FF0000; /* Pure red */ background-color: #008000; /* Green */#F00(for#FF0000) are also possible. - HSL (Hue, Saturation, Lightness): Represents colours based on a colour wheel (hue), intensity (saturation), and brightness (lightness).
color: hsl(0, 100%, 50%); /* Red */ background-color: hsl(120, 50%, 75%); /* Light green */ - HSLA (Hue, Saturation, Lightness, Alpha): HSL with an alpha channel for transparency.
background-color: hsla(240, 100%, 50%, 0.7); /* Semi-transparent blue */
Common Colour Properties
color: Sets the text colour.background-color: Sets the background colour of an element.border-color: Sets the colour of an element's border.
Backgrounds
Backgrounds add depth and visual interest to elements. CSS provides properties to control background images, colours, and their behaviour.
Background Properties
background-color: As discussed, sets a solid background colour.background-image: Applies an image as the background.background-image: url('images/background.jpg');background-repeat: Controls how an image repeats (or if it repeats).repeat(default): Repeats both horizontally and vertically.repeat-x: Repeats horizontally only.repeat-y: Repeats vertically only.no-repeat: The image does not repeat.
background-image: url('images/pattern.png'); background-repeat: repeat-x;background-position: Sets the initial position of the background image. Values can be keywords (top,center,bottom,left,right) or percentages/lengths.background-position: center top; /* Aligns image to the top center */ background-position: 50% 25%; /* Aligns image to 50% horizontally, 25% vertically */background-attachment: Determines if the background image scrolls with the page or remains fixed.scroll(default): The image scrolls with the element.fixed: The image is fixed relative to the viewport.local: The image scrolls with the element's content.
background-attachment: fixed;background-size: Resizes the background image.auto(default): Original size.cover: Scales the image to be as large as possible so that the background area is completely covered by the image. Some parts of the image may not be visible.contain: Scales the image to the largest possible size such that both its width and height can fit inside the content area.- Specific lengths or percentages (e.g.,
100px 50px,50% auto).
background-size: cover;
Shorthand `background` Property
You can combine most background properties into a single background property for brevity. The order matters:
background: color image repeat attachment position / size;
/* Equivalent to:
background-color: lightblue;
background-image: url('images/logo.png');
background-repeat: no-repeat;
background-position: center;
background-size: contain;
*/
background: lightblue url('images/logo.png') no-repeat center / contain;
Fonts
Typography plays a crucial role in readability and design. CSS offers extensive control over font families, sizes, weights, and styles.
Font Properties
font-family: Specifies the font for an element. It's best practice to provide a comma-separated list of fonts, including a generic fallback.font-family: Arial, Helvetica, sans-serif; /* Tries Arial first, then Helvetica, then any sans-serif font */ font-family: "Times New Roman", Times, serif;font-size: Sets the size of the font. Common units include:px(pixels): Absolute size.em: Relative to the parent element's font size.rem: Relative to the root element's (<html>) font size.%(percentage): Relative to the parent element's font size.- Keywords:
xx-small,x-small,small,medium,large,x-large,xx-large.
font-size: 16px; font-size: 1.2em; font-size: 1.5rem; font-size: 120%; font-size: large;font-weight: Sets the boldness of the font.- Keywords:
normal(default),bold,lighter,bolder. - Numeric values:
100to900(e.g.,400for normal,700for bold).
font-weight: bold; font-weight: 700;- Keywords:
font-style: Sets the font style.normal(default)italicoblique
font-style: italic;line-height: Specifies the space between lines of text. Can be a number (unitless, multiplied by the font size), length, or percentage.line-height: 1.5; /* Unitless, good for responsiveness */ line-height: 24px; line-height: 150%;text-decoration: Adds decorations like underlines, overlines, or line-throughs.none(default)underlineoverlineline-throughblink(rarely used, often not supported)
text-decoration: underline; a { text-decoration: none; } /* Remove underline from links */text-align: Aligns text within an element.left(default)rightcenterjustify(stretches text to fill the line)
text-align: justify;
Shorthand `font` Property
The font property is a shorthand for setting font-style, font-variant, font-weight, font-stretch, font-size, line-height, and font-family.
Important: font-size and font-family are mandatory when using the font shorthand.
/* Equivalent to:
font-style: italic;
font-weight: bold;
font-size: 16px;
line-height: 1.5;
font-family: Arial, sans-serif;
*/
font: italic bold 16px/1.5 Arial, sans-serif;
Borders
Borders are lines drawn around the edges of an element. They are part of the box model and can significantly impact layout and visual separation.
Border Properties
Each side of a border (top, right, bottom, left) can have its own style, width, and colour.
border-width: Sets the thickness of the border. Can use keywords (thin,medium,thick) or lengths (e.g.,1px,2px).border-width: 2px;border-style: Sets the type of line for the border. Must be set for a border to appear.none(default)soliddasheddotteddoublegroove,ridge,inset,outset(3D effects)
border-style: solid;border-color: Sets the colour of the border.border-color: #333;
Shorthand `border` Property
This is a very common shorthand to set all three properties for all four sides at once.
border: width style color;
border: 1px solid black;
Individual Side Properties
You can style each side individually:
border-top,border-right,border-bottom,border-left(shorthands for each side)border-top-width,border-top-style,border-top-color, etc.
border-bottom: 2px dashed red; /* Only the bottom border is styled */
Rounded Borders (`border-radius`)
This property creates rounded corners. It can take one to four values.
- One value: Applies to all corners.
- Two values: First value for top-left/bottom-right, second for top-right/bottom-left.
- Three values: First for top-left, second for top-right/bottom-left, third for bottom-right.
- Four values: Top-left, top-right, bottom-right, bottom-left (clockwise).
border-radius: 10px; /* All corners rounded by 10px */
border-radius: 15px 5px; /* 15px top-left/bottom-right, 5px top-right/bottom-left */
border-radius: 10px 20px 30px 40px; /* TL, TR, BR, BL */
You can also specify elliptical corners using two values separated by a slash (e.g., border-radius: 10px / 20px;).
The Box Model
Every HTML element can be thought of as a rectangular box. The CSS Box Model describes how these boxes are generated and how their dimensions and spacing are calculated. It consists of four main components:
- Content: The actual text, image, or other media.
- Padding: Space between the content and the border. It's transparent.
- Border: The line drawn around the padding and content.
- Margin: Space outside the border, separating the element from other elements. It's transparent.
The total space an element occupies on the page is calculated by adding its content width/height, padding, border, and margin.
Padding
Padding increases the space *inside* the border, between the border and the content.
padding-top,padding-right,padding-bottom,padding-left: Set padding for each side.padding: Shorthand property.- One value: Applies to all four sides.
- Two values: Top/bottom, left/right.
- Three values: Top, left/right, bottom.
- Four values: Top, right, bottom, left (clockwise).
.box {
padding: 20px; /* 20px on all sides */
padding: 10px 20px; /* 10px top/bottom, 20px left/right */
padding: 5px 10px 15px; /* 5px top, 10px left/right, 15px bottom */
padding: 5px 10px 15px 20px; /* 5px top, 10px right, 15px bottom, 20px left */
border: 1px solid black;
}
Margin
Margins create space *outside* the border, pushing other elements away.
margin-top,margin-right,margin-bottom,margin-left: Set margin for each side.margin: Shorthand property, works the same way as thepaddingshorthand.
.element {
margin: 15px;
border: 1px solid gray;
}
Margin Collapsing
A unique behaviour in CSS is margin collapsing. When two vertical margins (top or bottom) of adjacent elements meet, the larger margin is used, and the smaller one is effectively ignored. This also applies to the top margin of a child element and the bottom margin of its parent if there's no other content or padding between them.
`box-sizing` Property
By default, the width and height you set for an element only apply to its content area. Padding and border are added *on top* of that, making the element larger than specified. The box-sizing property changes this behaviour.
content-box(default):widthandheightapply only to the content. Padding and border are added to the total.border-box:widthandheightinclude content, padding, and border. Padding and border are drawn *inside* the element's specified width and height.
.my-element {
width: 200px;
padding: 20px;
border: 1px solid red;
box-sizing: content-box; /* Total width = 200 + 20 + 20 + 1 + 1 = 242px */
}
.my-element-better {
width: 200px;
padding: 20px;
border: 1px solid blue;
box-sizing: border-box; /* Total width = 200px. Padding and border are inside. */
}
It's common practice to set box-sizing: border-box; for all elements using a universal selector:
*, *::before, *::after { box-sizing: border-box; }
This makes layout calculations much more intuitive.
Positioning
The position property is one of the most powerful and sometimes tricky aspects of CSS. It controls how an element is positioned within the document flow and relative to other elements or the viewport.
Positioning Values
static(default):Elements are positioned according to the normal flow of the document. The
top,right,bottom,left, andz-indexproperties have no effect.relative:Elements are positioned according to the normal flow, and then *offset* relative to their normal position. The original space the element would have occupied is preserved. The
top,right,bottom,leftproperties are used to make the adjustment..relative-box { position: relative; top: 10px; /* Moves the box 10px down from its normal position */ left: 20px; /* Moves the box 20px right from its normal position */ }absolute:Elements are removed from the normal document flow. They are positioned relative to their *nearest positioned ancestor* (an ancestor with a position value other than
static). If no positioned ancestor exists, they are positioned relative to the initial containing block (usually the<html>element). The original space is *not* preserved..parent { position: relative; /* This makes it the positioning context for absolute children */ } .absolute-box { position: absolute; top: 50px; right: 30px; }fixed:Elements are removed from the normal document flow and are positioned relative to the *viewport* (the browser window). They remain in the same place even when the page is scrolled.
top,right,bottom,leftare used for positioning..fixed-header { position: fixed; top: 0; left: 0; width: 100%; background-color: white; padding: 10px; z-index: 1000; /* Ensures it stays on top */ }sticky:A hybrid of
relativeandfixed. The element is treated asrelativeuntil it scrolls to a specified threshold (defined bytop,right,bottom, orleft), at which point it becomes "stuck" and behaves likefixedrelative to its nearest scrolling ancestor or the viewport..sticky-sidebar { position: sticky; top: 20px; /* Sticks 20px from the top when scrolling reaches that point */ }
Offset Properties
When using position values other than static, you can use these properties to adjust the element's final position:
toprightbottomleft
These properties specify offsets from the edges of the containing block or the element's normal position.
`z-index`
For elements that are positioned (relative, absolute, fixed, sticky), z-index controls their stacking order – which element appears in front of another when they overlap.
- It accepts integer values. Higher numbers are stacked on top of lower numbers.
- It only affects *positioned* elements.
- If elements have the same
z-index, the one that appears later in the HTML source code is stacked on top.
.modal-background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
z-index: 999; /* Below the modal content */
}
.modal-content {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 20px;
z-index: 1000; /* On top of the background */
}
Class and ID Selectors
Selectors are the core of CSS, allowing you to target specific HTML elements for styling. While element selectors (like `p`, `h1`) target all instances of an element type, class and ID selectors provide more granular control.
Class Selectors
Classes allow you to group multiple elements that share common styling. An element can have multiple classes.
- HTML: Use the
classattribute. A class name can be applied to multiple elements.<p class="highlight important">This is important text.</p> <div class="highlight">This div also has the highlight class.</div> - CSS: Use a dot (
.) followed by the class name..highlight { background-color: yellow; padding: 5px; } .important { font-weight: bold; color: red; }
ID Selectors
IDs are used to identify a *single, unique* element on a page. An ID name should only be used once per HTML document.
- HTML: Use the
idattribute.<header id="main-header">...</header> <nav id="primary-navigation">...</nav> - CSS: Use a hash (
#) followed by the ID name.#main-header { background-color: #f0f0f0; padding: 20px; } #primary-navigation { border-bottom: 1px solid #ccc; }
Specificity
When multiple CSS rules target the same element, specificity determines which rule applies. IDs have higher specificity than classes, which have higher specificity than element selectors.
The general order of specificity (from lowest to highest) is:
- Element selectors (e.g.,
p) - Class selectors (e.g.,
.my-class), attribute selectors, pseudo-classes - ID selectors (e.g.,
#my-id) - Inline styles (
style="..."attribute) !importantdeclaration
Inline styles have the highest specificity, followed by IDs, then classes, then element types. Using !important overrides all other rules (but should be used with extreme caution).
/* Example: */
body { color: black; } /* Specificity: 1 */
p { color: blue; } /* Specificity: 1 */
.highlight { color: green; } /* Specificity: 10 */
#unique-paragraph { color: red; } /* Specificity: 100 */
/* If the HTML is: Text
*/
/* The text color will be orange (inline style wins) */
/* If style attribute is removed: */
/* The text color will be red (ID selector wins) */
/* If ID is also removed: */
/* The text color will be green (class selector wins) */
/* If class is also removed: */
/* The text color will be blue (element selector wins over body) */
Combining Selectors
You can combine selectors to target elements more precisely:
- Descendant Selector (space): Selects elements that are descendants of another element.
div p { color: purple; } /* Selects allinside
*/```- Child Selector (>): Selects elements that are direct children of another element.
ul > li { font-weight: bold; } /* Selects only- that are direct children of
- */
- Adjacent Sibling Selector (+): Selects an element that is immediately preceded by another element.
h2 + p { margin-top: 0; } /* Selects thethat immediately follows an
*/
- General Sibling Selector (~): Selects all elements that are siblings and follow another element.
h2 ~ p { color: gray; } /* Selects allthat are siblings of
and come after it */
Understanding these selectors, along with the box model, positioning, and the cascade, gives you the power to style almost any aspect of a webpage. Practice these concepts by building simple layouts and experimenting with different properties and values.
- Child Selector (>): Selects elements that are direct children of another element.