Your First CSS
CSS turns your plain page into something colourful, and it only takes a few lines.
Where CSS Goes
The simplest way to add CSS is a <style> block inside the <head>:
Example
<head>
<title>Ayesha Khan</title>
<style>
h1 {
color: #b45309;
}
</style>
</head>How a CSS Rule Works
Example
h1 {
color: #b45309;
}| Part | In the example | Meaning |
|---|---|---|
| Selector | h1 | Which elements to style |
| Property | color | What to change |
| Value | #b45309 | The new setting |
Each property ends with a semicolon ;, and all the properties of one rule sit between curly brackets { }.
Colours and Backgrounds
Example
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #fff8e7;
}
h1 {
color: #b45309;
}
h2 {
color: white;
background-color: #f59e0b;
}
</style>
</head>
<body>
<h1>Ayesha Khan</h1>
<h2>About Me</h2>
<p>I love drawing and I want to design websites.</p>
</body>
</html>Try it Yourself »Colours can be names like orange, or HEX codes like #f59e0b. HEX codes give you millions of exact shades.
One rule styles every matching element. If you add ten <h2> headings, all ten become orange with white text, with no extra work.
Classes: Style Only Some Elements
Sometimes you want to style just one or two elements. Give them a class in HTML, and select the class with a dot in CSS.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: #fde68a;
}
.muted {
color: gray;
}
</style>
</head>
<body>
<p class="highlight">My goal: build my own website this year.</p>
<p class="muted">Last updated in October.</p>
<p>This paragraph has no class, so it stays normal.</p>
</body>
</html>Try it Yourself »Three Kinds of Selector
| Selector | Example | Selects |
|---|---|---|
| Element | p | Every <p> |
| Class | .highlight | Every element with class="highlight" |
| Id | #top | The one element with id="top" |
Update Your Page
Add a <style> block to the head of your index.html with a soft background colour for body and a strong colour for h1 and h2. Pick colours you like.
Exercise
Exercise
In CSS, how do you select all elements with class="card"?
