Welcome to Part 3 of the CSS Mastery & Responsive Layouts Course. In this part, we will focus on the visual qualities of text and color.
A page’s typography determines its readability, structure, and professional look, while color selections define the branding and user mood. We will cover CSS color formats, font loading rules, typography properties, spacing constraints, and decoration overrides.
Chapter 22: CSS Color Formats & Color Math
CSS offers several ways to define colors. Let’s explore the underlying math and structures for each format.
22.1 Named Colors
CSS has 147 built-in color names (like red, blue, tomato, darkslateblue, rebeccapurple).
- Useful for testing, but too restrictive for actual branding.
22.2 Hexadecimal (Hex) Colors
A hex color code starts with # followed by 6 hexadecimal characters: #RRGGBB (Red, Green, Blue). Values range from 00 (no color) to ff (maximum color).
- Hexadecimal Base-16 Math: Hexadecimal uses digits
0-9and lettersa-f(representing values10-15).00in Hex = $0$ in Decimal (darkest)80in Hex = $128$ in Decimal (medium)ffin Hex = $255$ in Decimal (brightest)
- Hex Conversion Example: Take color
#4c1d95- Red:
4c$\rightarrow 4 \times 16 + 12 = 76$ (in decimal $0-255$) - Green:
1d$\rightarrow 1 \times 16 + 13 = 29$ - Blue:
95$\rightarrow 9 \times 16 + 5 = 149$ - This represents
rgb(76, 29, 149).
- Red:
- Short Hex (3 Digits):
#RGBexpands to#RRGGBB. E.g.,#f00resolves to#ff0000(pure red). - Transparency: You can add 2 extra characters for alpha opacity:
#ffffff80(50% opaque white) or#000000ff(100% opaque black).
22.3 RGB and RGBA Color System
Defines colors by specifying Red, Green, and Blue values from 0 to 255:
.card {
background-color: rgb(255, 255, 255);
border-color: rgba(0, 0, 0, 0.15); /* 15% opacity black */
}
22.4 HSL and HSLA (Hue, Saturation, Lightness)
HSL is highly intuitive because it mirrors how human eyes perceive color:
- Hue: Measured in degrees (
0to360) on a color wheel.- $0$ or $360$ = Red, $120$ = Green, $240$ = Blue.
- Saturation: Percentage value.
0%is grayscale,100%is fully saturated. - Lightness: Percentage value.
0%is black,100%is white.
.button-primary {
background-color: hsl(220, 90%, 56%); /* Clear bright blue */
}
22.5 Modern OKLCH Color Space & Display P3 Gamuts
Traditional color spaces like HSL suffer from a major design flaw: they do not account for human eye perception. For instance, yellow HSL (hsl(60, 100%, 50%)) looks much brighter to our eyes than blue HSL (hsl(240, 100%, 50%)), even though they both declare 50% lightness.
OKLCH fixes this by mapping colors uniformly based on human vision:
- O: Oklab color space.
- L: Lightness (perceived brightness, $0%$ to $100%$).
- C: Chroma (saturation/color purity, $0$ to $0.4$).
- H: Hue angle ($0$ to $360$ degrees).
/* Generates a vibrant, perceptually stable teal color */
.header-hero {
background-color: oklch(70% 0.15 160);
}
- Gamut & Display P3: OKLCH supports wide gamut colors outside the standard sRGB color space. When rendering on modern Apple or high-end Android screens, this exposes richer, more saturated shades that Hex color syntax cannot declare.
- Wide Gamut Fallback Strategy:
.accent-button { background-color: rgb(255, 0, 100); /* Fallback */ } @supports (color: color(display-p3 1 0 0.4)) { .accent-button { background-color: color(display-p3 1 0 0.4); /* Ultra-vibrant P3 red */ } }
22.6 Color Functions & Keywords
currentcolor: Acts like a CSS variable. It evaluates to the value of the elementscolorproperty. Extremely useful for SVG icons.color-mix(): Allows mixing two colors directly in the stylesheet:.accent { background-color: color-mix(in srgb, red 30%, blue 70%); }
Chapter 23: Drawing with Gradients
CSS Gradients are categorized as image values. They allow smooth transitions between multiple colors.
23.1 Linear Gradients (linear-gradient)
Transitions colors along a straight line. You can define angles or direction keywords.
/* Direction keyword (default is 'to bottom') */
.gradient-bar {
background-image: linear-gradient(to right, #2563eb, #9333ea);
}
/* Specific Angle */
.gradient-angle {
background-image: linear-gradient(135deg, red, yellow 30%, blue);
}
23.2 Radial Gradients (radial-gradient)
Transitions colors starting from a central point and expanding outward in a circular or elliptical shape.
.radial-container {
background-image: radial-gradient(circle at center, white 0%, #cbd5e1 100%);
}
23.3 Conic Gradients (conic-gradient)
Transitions colors rotated around a center point (like a color wheel or pie chart).
.pie-chart {
background-image: conic-gradient(red 0% 33%, blue 33% 66%, green 66% 100%);
border-radius: 50%;
width: 150px;
height: 150px;
}
Chapter 24: Typography Sizing Methodologies
Font sizing is the foundation of readable layout structures. Let’s look at absolute vs. relative units.
24.1 Absolute Sizing (px)
Pixels represent a fixed physical size on screens.
- Drawback: Pixel font sizing is bad for accessibility because users cannot scale text using their browser’s default font size settings.
24.2 Relative Sizing (rem vs em)
rem(Root EM): Scales relative to the<html>root element font size. In standard browsers, the default root size is16px.1rem= $16\text{px}$1.25rem= $20\text{px}$ ($1.25 \times 16$)0.875rem= $14\text{px}$ ($0.875 \times 16$)
em: Scales relative to the font-size of the element itself (or parent if not set). Often used for paddings or margins that should scale proportionally with font sizes.
/* Accessibility Reset */
html {
font-size: 100%; /* Resolves to 16px */
}
h1 {
font-size: 2.25rem; /* 36px */
margin-bottom: 0.5em; /* Spacing scales relative to h1 size (18px) */
}
24.3 Viewport Units (vw, vh, vmin, vmax)
1vw= 1% of the viewport width.1vh= 1% of the viewport height.- Useful for responsive fluid typography using the math function:
h1 { font-size: clamp(2rem, 4vw + 1rem, 4rem); }
Chapter 25: Fonts & Text Rendering Properties
Here is a breakdown of every property used to format text and control font rendering.
25.1 Font Families (font-family)
Lists preferred fonts and generic fallback families:
body {
font-family: "Outfit", system-ui, -apple-system, sans-serif;
}
25.2 Font Weight (font-weight)
Sets the thickness of the font. Values range from 100 (Thin) to 900 (Black):
.bold-text {
font-weight: 700; /* Bold */
}
25.3 Unitless Line Height (line-height)
Controls vertical line spacing. Always use unitless values (like 1.5) rather than pixels or percentages. Unitless numbers inherit dynamically based on the child elements font-size, avoiding layout overlapping bugs.
p {
font-size: 1rem;
line-height: 1.6; /* 1.6 times font-size (16px * 1.6 = 25.6px) */
}
25.4 Text Align (text-align)
Configures text alignment inside block containers:
left,right,center,justify(stretches lines to touch both margins).
25.5 Text Decoration (text-decoration)
Controls text underlines, lines through, and styles:
a {
text-decoration: underline wavy red 2px; /* shorthand modern format */
}
25.6 Spacing & Wrap Controls
letter-spacing: Spacing between characters.word-spacing: Spacing between words.white-space: Determines how spaces and line breaks are handled:nowrap: Keeps text on a single line.pre: Respects spaces and line breaks exactly as written.
text-transform: Swaps casing:uppercase,lowercase,capitalize.word-break: Swaps word breaking:normal,break-all(forces break anywhere),keep-all(no break).overflow-wrap: Configures wrapping:normal,break-word(wraps long words without breaking layouts).
25.7 Vertical Alignment (vertical-align)
Slices vertical positioning of inline-level elements relative to text lines:
- Values:
baseline,middle,sub,super,top,bottom. - Common use-case: Aligning an SVG icon inline next to a text label.
25.8 Font Rendering performance
-webkit-font-smoothing: Standard valueantialiasedrenders fonts smoother on macOS and iOS screens.text-rendering: Standard valueoptimizeLegibilityenables kerning and ligatures in complex text blocks.font-variant-ligatures: Standard valuecommon-ligaturesjoins characters like “fi”, “fl”, “ae” into visually attractive glyph shapes.font-kerning: Controls character spacing tables embedded in font files:normal(forces kerning).
Chapter 26: Web Fonts Loading & Variable Fonts
To load custom external fonts (like Google Fonts or self-hosted files), use the @font-face rule:
@font-face {
font-family: 'Open Sans';
src: url('/fonts/OpenSans-Regular.woff2') format('woff2'),
url('/fonts/OpenSans-Regular.woff') format('woff');
font-weight: 400;
font-style: normal;
font-display: swap; /* Performance tip: avoids invisible text layout shifts */
}
26.1 Font-Display Settings & Performance
The font-display descriptor determines how the browser displays text before the custom font file finishes loading:
block: Hides text (invisible) for up to 3 seconds. Causes FOIT (Flash of Invisible Text) which degrades user experience.swap: Instantly shows a system fallback font, then swaps to the custom font once loaded. Recommended for body text.fallback/optional: Uses fallback fonts if loading takes too long.
26.2 Variable Fonts (Modern Standard)
Traditional fonts require downloading separate files for each weight (Regular, Bold, Semi-bold). Variable Fonts package multiple weights, styles, and widths into a single small file.
font-variation-settings: Allows animating or declaring exact axis weights:.text-custom { font-family: 'Roboto Flex', sans-serif; font-variation-settings: 'wght' 550, 'wdth' 85; }
Chapter 27: Colors & Typography Practice
27.1 Practice Exercises
- Exercise 1: Create a button style with a linear-gradient background that shifts from deep blue to purple on hover, uses
remsizing, and implements a font fallback stack..btn-grad { font-family: "Inter", sans-serif; font-size: 1rem; padding: 0.75em 1.5em; border: none; color: white; background-image: linear-gradient(to right, #1e3a8a, #581c87); border-radius: 0.375rem; cursor: pointer; } .btn-grad:hover { background-image: linear-gradient(to right, #2563eb, #7c3aed); } - Exercise 2: Configure a paragraph styling that handles overflow gracefully inside a small sidebar card by forcing single-line display and showing ellipsis.
.card-teaser { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 0.875rem; } - Exercise 3: Write a
@font-faceconfiguration that loads a variable font and configures it to swap fallback fonts, styling a headline with custom weight and optical sizing.@font-face { font-family: 'Outfit Variable'; src: url('/fonts/Outfit-Variable.woff2') format('woff2-variations'); font-weight: 100 900; font-display: swap; } .headline-custom { font-family: 'Outfit Variable', sans-serif; font-variation-settings: 'wght' 800, 'opsz' 40; }
27.2 Self-Check Questions
- What is the main advantage of OKLCH colors over HSL colors?
- Answer: OKLCH is perceptually uniform. Changes in Hue do not cause artificial changes in perceived brightness, making it easier to maintain design contrast guidelines.
- Why is it better to use rem instead of px for font sizing?
- Answer: Accessibility.
remscales with the user’s browser base font size configurations, whereaspxlocks sizing to a fixed grid value.
- Answer: Accessibility.
- What does the swap value of font-display accomplish?
- Answer: It tells the browser to display a fallback system font immediately so the text remains readable, swapping to the custom font file as soon as the load completes.
- Why are unitless values recommended for line-height?
- Answer: Unitless numbers scale proportionally when child elements change font-size, preventing text overlapping layout errors.
- What is the difference between letters-spacing and word-spacing?
- Answer:
letter-spacingadjusts space between character nodes, whileword-spacingadjusts space between individual word strings.
- Answer:
- Does linear-gradient create a background-color or background-image value?
- Answer: It creates a
background-imagevalue, as gradients are treated as CSS image resources.
- Answer: It creates a
- How is conic-gradient different from radial-gradient?
- Answer: Conic-gradient rotates colors around a central axis (like a dial), whereas radial-gradient radiates colors in concentric circles outwards from the center.
- What does text-transform: capitalize do to a sentence?
- Answer: It converts the first character of each word inside the sentence to uppercase.
- What is the hex conversion of rgb(255, 255, 255)?
- Answer:
#ffffff.
- Answer:
- Which generic font family is optimized for reading code blocks?
- Answer:
monospace.
- Answer:
- What is the difference between font-style: italic and font-style: oblique?
- Answer:
italicuses a dedicated cursive script version of the typeface, whereasobliquetakes the normal roman character set and slants it mathematically.
- Answer:
- How do variable fonts improve site performance?
- Answer: They pack multiple weights, widths, and styles into a single file, reducing the number of individual HTTP requests for separate font weight files.
- What is a Display P3 color gamut?
- Answer: A wide-color-gamut space that contains 25% more color variations than traditional sRGB, displaying highly vibrant reds, greens, and pinks.
- What CSS property controls standard ligature joins (like “fi”)?
- Answer:
font-variant-ligatures.
- Answer:
- What is the purpose of the unicode-range property in @font-face?
- Answer: It tells the browser to download the font file only if the webpage contains characters inside the specified unicode range, optimizing character asset downloads.
Discussion
Loading comments...