CSS Colors & Units

📚 Lesson 3 of 30  •  ⏱ 10 min read  •  Beginner

Color Formats

CSS
/* Named colors */
h1 { color: red; }
p  { color: tomato; }

/* Hex — #RRGGBB */
h1 { color: #6c63ff; }   /* purple */
p  { color: #333; }      /* shorthand for #333333 */

/* RGB — red green blue (0-255) */
h1 { color: rgb(108, 99, 255); }

/* RGBA — with alpha/transparency (0=transparent, 1=opaque) */
.overlay { background: rgba(0, 0, 0, 0.5); }  /* 50% black */

/* HSL — hue (0-360°) saturation% lightness% */
h1 { color: hsl(245, 100%, 70%); }

/* HSLA — with alpha */
.card { background: hsla(245, 100%, 70%, 0.15); }

/* Modern: hsl with / for alpha (CSS4) */
.card { background: hsl(245 100% 70% / 0.15); }

Opacity vs RGBA

CSS
/* opacity affects the WHOLE element including children */
.box { opacity: 0.5; }

/* rgba only affects the background — children stay visible */
.box { background: rgba(0, 0, 0, 0.5); }

CSS Units

Absolute Units

CSS
p { font-size: 16px; }   /* pixels — fixed, most common */
p { font-size: 12pt; }   /* points — mainly for print */

Relative Units — Use These for Responsive Design

CSS
/* rem — relative to ROOT html font-size (default 16px) */
p  { font-size: 1rem; }     /* = 16px */
h1 { font-size: 2rem; }     /* = 32px */
/* Best for font-size — scales if user changes browser font */

/* em — relative to PARENT element's font-size */
.card { font-size: 1.2em; }  /* 1.2× parent's font-size */
/* Can compound when nested — use carefully */

/* % — relative to parent's same property */
.col { width: 50%; }         /* half the parent's width */

/* Viewport units */
.hero { height: 100vh; }     /* 100% of viewport HEIGHT */
.banner { width: 100vw; }   /* 100% of viewport WIDTH */
h1 { font-size: 5vw; }       /* scales with browser width */

/* clamp(min, preferred, max) — responsive font without media queries */
h1 { font-size: clamp(1.5rem, 5vw, 3.5rem); }

CSS Custom Properties (quick preview)

CSS
:root {
  --primary: #6c63ff;
  --text: #333;
}
h1 { color: var(--primary); }
p  { color: var(--text); }