← Web basics: HTML, CSS and JavaScript
Adding CSS to a page
Rules, selectors, properties and values, and where CSS lives.
CSS (Cascading Style Sheets) controls how a page looks. CSS is written as rules. A rule has a selector, which picks the elements to style, and a block in curly braces with one or more declarations. Each declaration is a property, a colon, a value and a semicolon, like color: green;. You can put CSS in a <style> element in the head (what we use in this course), in a separate .css file linked with <link rel="stylesheet" href="style.css">, or in a style attribute on one element.
<style>
body {
background-color: ivory;
}
h1 {
color: darkgreen;
font-size: 40px;
}
</style>Two rules. The first picks body and gives the whole page an ivory background. The second picks every h1 and sets two properties: its color and its size.
A missing semicolon or brace makes the browser skip part of your CSS silently, with no error message. If a style does not apply, check punctuation first.
A separate .css file is best for real sites, because many pages can share one file. The style attribute is handy for quick tests but hard to maintain.