Sub topic 2
Understand CSS Rules and Build a Flexible Header
Assume you can write basic HTML, use selectors, and link a stylesheet. This chapter explains how CSS decides which rule applies, then uses that model to create consistent spacing, typography, and navigation.
Understand the cascade, specificity, and inheritance
When several CSS rules match one element, the cascade chooses the winning declaration. Browser styles have lower priority than author styles. Within your stylesheet, importance, specificity, and source order matter.
Specificity measures how precisely a selector targets an element. An ID selector such as #about beats a class selector such as .intro, which beats an element selector such as p. If two matching selectors have equal specificity, the later declaration wins.
Some properties inherit from a parent. Text color and font family usually inherit. Margin, padding, and borders do not.
Control spacing with the box model
Every element is a box made of content, padding, border, and margin. Padding creates space inside the border. Margin creates space outside it. By default, width applies only to the content area.
Set box-sizing: border-box so declared widths include padding and borders. This makes layouts easier to predict.
Set typography and color
Choose a readable system font, a comfortable line height, and colors with enough contrast. Use rem for spacing and type so the page responds to the user’s text-size settings.
Keep your design consistent with custom properties
Custom properties store reusable values. Define them on :root, then read them with var().
:root {
--text: #1f2933;
--accent: #0b5cad;
--space: 1rem;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 0;
color: var(--text);
font-family: system-ui, sans-serif;
line-height: 1.6;
}
main {
max-width: 60rem;
margin: 0 auto;
padding: calc(var(--space) * 2) var(--space);
}Lay out navigation with Flexbox
Flexbox lays out items along one direction. Make the navigation list a flex container, remove bullets, and use gap for even spacing.
nav ul {
display: flex;
justify-content: center;
gap: 1.5rem;
margin: 0;
padding: var(--space);
list-style: none;
}Exercise
A paragraph matches p { color: black; } and .intro { color: navy; }. Which color wins, and why?
Show answer
Navy wins because the class selector has greater specificity than the element selector.