DevNotes

DevNotes

@devnotes ·

CSS Part 1: How CSS styles a page

HTML says what things are. CSS says how they look: colours, sizes, spacing and layout.

Connect a stylesheet

Put your CSS in its own file, say style.css, and link it in the <head> of your HTML:

HTML
<link rel="stylesheet" href="style.css">

You can also write CSS inside a <style> tag, or straight on an element with style="...". A separate file keeps things tidy, though, and one file can style every page of your site.

A rule, piece by piece

CSS
h1 {  color: navy;  font-size: 40px;}
  • h1 is the selector. It picks which elements the rule applies to.
  • Inside the braces are declarations. Each one is a property, a colon, a value and a semicolon.
  • color sets the text colour and font-size sets its size.

CSS uses American spelling, so it's always color and center in your code, whatever you write elsewhere.

Miss a semicolon and the browser reads two declarations as one broken one, then drops both. The console stays quiet, but DevTools (below) shows the broken line crossed out with a warning sign, so when a style mysteriously does nothing, look there first.

Selectors: picking elements

CSS
p { }          /* every <p> */.card { }      /* every element with class="card" */#signup { }    /* the element with id="signup" */nav a { }      /* links that sit inside a <nav> */h1, h2 { }     /* every h1 and every h2 */

A dot means class and a hash means id. A space means "inside": nav a styles only the links somewhere inside a nav, and leaves every other link alone.

Do most of your styling with classes. They're reusable, and they don't fight each other the way ids do. The next part explains that fight.

States: hover and focus

Selectors can also pick an element in a certain state:

CSS
a:hover {  color: crimson;}
button:focus-visible {  outline: 3px solid orange;}

:hover applies while the mouse is over the element. :focus-visible applies when someone moves to it with the keyboard, using the Tab key. Never remove the focus outline without adding your own. People who use a keyboard rely on it to see where they are on the page.

DevTools: see what's happening

Right-click anything on a web page and choose Inspect. You'll see its HTML, and every CSS rule acting on it. You can change values right there and watch the page update. Nothing is saved, so experiment freely, then copy what works into your file.

It works on any website, which also makes it a great way to see how other people built things.

Comments

CSS
/* Header styles */

Try it

Open the page you built in HTML Part 5. Link a style.css, set a font on the body with font-family: sans-serif;, change the colour of the headings, and make the links change colour on hover.


Next: CSS Part 2: Which rule wins, and why

csswebdevbeginners

Join WIK to like and reply to DevNotes and see more like this.