Sub topic 2
Absolute Units, Relative Units, and Typography
Assume you know basic HTML, CSS selectors, the cascade, and the box model. This chapter focuses on choosing CSS units and font families for adaptable layouts.
Absolute units and why `px` is common
An absolute unit has a fixed CSS value. The pixel (px) is the common absolute unit for borders, icons, and small details that should remain visually consistent.
.card {
border: 1px solid #c7cbd1;
border-radius: 8px;
padding: 24px;
}A CSS pixel is not always one physical screen pixel. Browsers adjust it for zoom and high-density displays. Avoid using px for every size, especially text, because users may change their browser’s default font size.
Relative units: `em`, `rem`, and percentages
Relative units scale from another value:
remis relative to the root element’s font size. It is useful for predictable page-wide sizing.emis relative to the current element’s font size. It is useful when padding should grow with text.%is usually relative to a parent property, such as a container’s width.
html {
font-size: 100%;
}
body {
font-size: 1rem;
}
.button {
font-size: 1.125rem;
padding: 0.5em 1em;
}
.content {
width: 80%;
}Viewport units and dynamic viewport sizes
Viewport units use the browser window as their reference. vw is one percent of the viewport width. vh is one percent of its height. dvh means dynamic viewport height and responds as mobile browser controls appear or disappear.
.hero {
min-height: 60dvh;
padding: 5vw;
}Fluid sizing with `clamp()`, `min()`, and `max()`
clamp(minimum, preferred, maximum) creates a bounded fluid value. min() chooses the smallest value, while max() chooses the largest.
h1 {
font-size: clamp(1.75rem, 1rem + 3vw, 3rem);
}
.page {
width: min(90%, 70rem);
padding: max(1rem, 3vw);
}Choosing font families and fallback stacks
A font stack lists preferred fonts followed by fallbacks. system-ui uses the operating system’s interface font, and sans-serif is a generic final fallback.
body {
font-family: Inter, system-ui, sans-serif;
line-height: 1.5;
}A fallback protects the layout when the preferred font is unavailable. Test long headings and buttons with fallback fonts because their widths can differ.
Exercise
Which unit is usually best for a page-wide body font size, and which unit makes button padding follow the button’s text size?
Show answer
Use rem for the body font size and em for padding that should scale with the button’s own font size.