Learn/HTML, CSS & JS/5. Styling with CSS
Lesson 5 of 8
Sign in

HTML, CSS & JS, lesson 5

Styling with CSS

HTML says what things are. CSS (Cascading Style Sheets) says how they look. A CSS file is a list of rules. Each rule has a selector that picks elements, and declarations that set properties:

Selectors

  • p selects every <p> (a type selector).
  • .card selects every element with class="card". Classes are reusable labels you add in HTML; an element can have several: class="card featured".
  • #total selects the one element with id="total".
  • .card h2 selects <h2> elements a (a selector).

One exercise to try what you just read.

Exercise 1

Style the card

Press Ctrl Enter or Check to test your code.

inside
.card
descendant

When two rules set the same property, the more specific selector wins (id beats class beats type), and if they're equal, the one written later wins. That's the "cascading" part.

The box model

Every element is a box. From inside out:

  • content, the text or image itself,
  • padding, space inside the border,
  • border,
  • margin, space outside, pushing other boxes away.

Add box-sizing: border-box and width includes padding and border, which is much easier to reason about.

Colors and units

Colors can be names (tomato), hex (#ff6347) or functions like rgb(255 99 71). Sizes use px, or rem (relative to the root font size), which respects people's font settings.

Further reading

  • MDN: CSS first steps
  • MDN: Basic selectors
  • MDN: The box model

Write CSS (in the style.css tab) so that:

  1. Every h1 has the color rgb(180, 83, 9).
  2. The element with class card has 16px padding on all sides.
  3. .card has a solid border that is 2px wide.
  4. The element with id price is bold (font-weight: 700).

Don't change the HTML.

h1 {
  color: #b45309;
  font-size: 2.5rem;
}
.card {
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 12px;
  margin-bottom: 24px;
}