Styling the web with Cascading Style Sheets
CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of a document written in HTML or XML. CSS controls how elements are displayed on screen, paper, or in other media.
A CSS rule consists of a selector and a declaration block:
/* This is a CSS comment */
selector {
property: value; /* Declaration */
}
/* Make all h1 elements blue and centered */
h1 {
color: blue;
text-align: center;
}
Apply styles directly to HTML elements using the style attribute:
<h1 style="color: blue; text-align: center;">
This is a heading
</h1>
Note: Inline styles have the highest specificity and are hard to maintain. Use sparingly.
Place CSS rules inside a <style> element in the HTML document's <head>:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #f0f0f0;
}
h1 {
color: blue;
text-align: center;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
</body>
</html>
Link to an external CSS file (recommended approach):
/* In your HTML file */
<head>
<link rel="stylesheet" href="styles.css">
</head>
/* In styles.css */
body {
background-color: #f0f0f0;
}
h1 {
color: blue;
text-align: center;
}
External CSS is the most maintainable approach as it separates content from presentation.
Master these fundamental CSS concepts to build effective styles:
Selectors define which HTML elements to style:
| Selector | Example | Description |
|---|---|---|
| Element | p | Selects all <p> elements |
| Class | .intro | Selects all elements with class="intro" |
| ID | #header | Selects the element with id="header" |
| Attribute | a[target] | Selects all <a> elements with a target attribute |
| Descendant | div p | Selects all <p> elements inside <div> elements |
| Child | div > p | Selects all <p> elements where the parent is a <div> |
| Pseudo-class | a:hover | Selects links on mouse hover |
Every element is represented as a rectangular box with these properties:
.box {
width: 200px; /* Content width */
height: 100px; /* Content height */
padding: 20px; /* Space around content */
border: 5px solid blue; /* Border around padding */
margin: 30px; /* Space outside border */
box-sizing: border-box; /* Include padding/border in width/height */
}
.container {
display: flex;
justify-content: space-between; /* Horizontal alignment */
align-items: center; /* Vertical alignment */
gap: 10px; /* Space between items */
}
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}