Unit 6 · Cascading Style Sheets (CSS)

6.2CSS Syntax

CSS
selector {
  property: value;
  property: value;
}

h1 {
  color: darkblue;
  font-size: 32px;
  text-align: center;
}
h1 { color: darkblue; font-size: 32px;}propertyvalueselector: which elements to styledeclaration: property: value;{ … } declaration block
A CSS rule: a selector followed by a declaration block of property: value pairs

Common values and units

TypeExamples
Colour namesred, tomato, navy
Hex#ff0000, #0a3d62
RGB and RGBArgb(255,0,0), rgba(0,0,0,0.5) (last is opacity)
HSLhsl(200, 70%, 50%)
Absolute lengthpx
Relative length%, em (relative to parent font size), rem (relative to root font size), vw and vh (percent of viewport width and height)

Frequently used properties

GroupProperties
Textcolor, font-family, font-size, font-weight, font-style, text-align, text-decoration, text-transform, line-height, letter-spacing
Backgroundbackground-color, background-image, background-size, background-repeat, background-position
Boxwidth, height, margin, padding, border, border-radius, box-shadow
Displaydisplay, visibility, overflow, opacity
Positionposition, top, left, right, bottom, z-index

The box model. Every element is a rectangular box made of four layers, from inside to outside: content, padding (space inside the border), border, margin (space outside).

marginspace outside the borderborderpaddingspace inside the bordercontenttext, images, child elementswith box-sizing: border-box, width = content + padding + border
The box model: content, padding, border and margin (from the inside out)
CSS
* { box-sizing: border-box; }  /* width includes padding and border: much easier maths */

.card {
  width: 300px;
  padding: 20px;              /* all four sides */
  border: 2px solid #333;
  margin: 10px 20px;          /* top-bottom 10px, left-right 20px */
}
/* Shorthand order for 4 values: top right bottom left (clockwise) */

Block versus inline. Block elements (div, p, h1) take a full line and accept width and height. Inline elements (span, a) flow within text and ignore width and height. display: inline-block combines both. display: none hides an element completely.