CSS = Cascading Style Sheets
CSS is a rule-based language: you define the rules by specifying groups of styles that should be applied to particular elements.
One rule consists of selector and declaration block:
selector { /* <- e.g. class name */
property: value; /* <- declaration */
}
The position property determines where the element is rendered:
Also known as CSS Variables these allow to easily reuse values:
:root {
--primary-color: yellow; /* declare it, prefixed with double dash */
}
p {
color: var(--primary-color); /* access value with var() */
}
The DOM connects the HTML with JavaScript through an in-memory representation.
It represents the document with a logical tree.
We can use the style attribute to define styles for our HTML elements, using the following syntax:
Paragraph text in red.
Paragraph text in red.
We write a meaningful name into the class attribute:
Paragraph text in red.
Then we can reference this class in CSS prefixed with a dot:
Elements can have multiple classes, which applies multiple rules:
Paragraph text in red.
Why use classes instead of inline styles?
Classes aren't our only way to target elements. We can use different identifiers from our HTML as selector:
We can list multiple selectors separated with comma to apply the same rule to different elements:
p, li {
color: red;
}
Some elements should look different based on where they are.
li span { /* spans that are descendants of a li */
color: red;
}
li > span { /* spans that are direct children of a li */
color: red;
}
li + p { /* p that is an adjacent sibling of a li */
color: red;
}
We can combine selectors to target more specific elements:
div.banner li
#upload > button
h2 + ul li
body section p + p
We usually want to ensure a consistent UI across browsers without having to constantly overwrite default styles. We can …
Content: The actual content of the box, in which text, images and other child elements appear. Child elements are bound by this area.
Padding: Clears an area around the content, separating content and border. The padding is transparent.
Border: A border that goes around the padding and content. Backgrounds extend to the edge of this area/box. The border can be colored.
Margin: Clears an area outside the border to separate the element from its neighbors. The margin is transparent.
Vertical margins (top and bottom) of blocks are collapsed in 3 cases.
When there's no border, padding or content between outer and inner margin.
Top and bottom margin collapses on blocks with zero height and no border or padding.
How can we avoid collapsing issues?
When should I use which one?
Most of the slides are from our «CSS for Developers» course.
The full set of slides is available on GitHub.