CSS Fundamentals & Selectors

Part 1: Syntax, Selectors, Box Model, Typography, Colors, Units & Variables

1. CSS Syntax Basics

Rule Structure

A CSS rule consists of a selector and a declaration block.

selector {
  property: value;
  property2: value2;
}

Comments

CSS supports only block comments. No single-line comments.

/* This is a comment */
p { color: red; /* inline comment */ }

Ways to Add CSS

<!-- 1. Inline Style -->
<p style="color:red">Text</p>

<!-- 2. Internal Style -->
<style>
  p { color: red; }
</style>

<!-- 3. External Style -->
<link rel="stylesheet" href="style.css">

Cascade Priority (Low to High)

1. Browser default styles
2. External stylesheet
3. Internal stylesheet (<style>)
4. Inline styles (style="...")
5. !important declarations
6. !important in inline styles
Tip: Avoid !important in production. It makes debugging difficult.

2. CSS Selectors - Complete Guide

Basic Selectors

*         { }  /* Universal - selects ALL elements */
div       { }  /* Type - selects all <div> */
.class    { }  /* Class - selects class="class" */
#id       { }  /* ID - selects id="id" */
div, p    { }  /* Grouping - selects all <div> AND <p> */

Attribute Selectors

[href]            /* Has attribute */
[href="url"]      /* Exact match */
[class~="box"]    /* Contains word "box" */
[lang|="en"]      /* Starts with "en" or "en-" */
[href^="https"]   /* Starts with "https" */
[src$=".png"]     /* Ends with ".png" */
[title*="hello"]  /* Contains "hello" anywhere */
[type="text" i]   /* Case-insensitive match */

Combinator Selectors

div p     { }  /* Descendant - p inside div (any depth) */
div > p   { }  /* Child - p directly inside div */
div + p   { }  /* Adjacent Sibling - p right after div */
div ~ p   { }  /* General Sibling - all p after div */

/* Examples */
ul > li         /* Direct list items only */
h1 + p          /* First paragraph after h1 */
.card ~ .card   /* All cards after the first */

Pseudo-Classes - State & Interaction

a:hover          { }  /* Mouse over element */
a:active         { }  /* While being clicked */
a:visited        { }  /* Already visited link */
a:link           { }  /* Unvisited link */
input:focus      { }  /* Element has keyboard focus */
input:focus-visible { }  /* Keyboard focus (not mouse) */
div:focus-within { }  /* Contains a focused element */
input:checked    { }  /* Checked checkbox/radio */
input:disabled   { }  /* Disabled form element */
input:enabled    { }  /* Enabled form element */
input:required   { }  /* Has required attribute */
input:optional   { }  /* Does NOT have required */
input:valid      { }  /* Passes validation */
input:invalid    { }  /* Fails validation */
input:placeholder-shown { }  /* Placeholder is visible */
:target          { }  /* Element matching URL hash #id */
:root            { }  /* Document root (<html>) */

Pseudo-Classes - Structural

:first-child         /* First child of its parent */
:last-child          /* Last child of its parent */
:only-child          /* Only child of its parent */
:first-of-type       /* First of its type in parent */
:last-of-type        /* Last of its type in parent */
:only-of-type        /* Only one of its type in parent */
:empty               /* No children (including text) */

/* nth-child patterns */
:nth-child(3)        /* 3rd child */
:nth-child(odd)      /* 1st, 3rd, 5th... = :nth-child(2n+1) */
:nth-child(even)     /* 2nd, 4th, 6th... = :nth-child(2n) */
:nth-child(3n)       /* Every 3rd: 3, 6, 9... */
:nth-child(3n+1)     /* 1, 4, 7, 10... */
:nth-child(-n+3)     /* First 3 children */
:nth-child(n+4)      /* From 4th child onward */
:nth-last-child(2)   /* 2nd from end */
:nth-of-type(2)      /* 2nd of its type */
:nth-last-of-type(1) /* Last of its type */

Pseudo-Classes - Modern

/* :is() - matches any in the list (forgiving) */
:is(h1, h2, h3) { color: blue; }
/* Same as: h1, h2, h3 { color: blue; } */

/* Nested with :is() */
article :is(h1, h2, h3) { margin-top: 2em; }

/* :where() - like :is() but ZERO specificity */
:where(h1, h2, h3) { color: blue; }

/* :not() - negation */
p:not(.special) { color: gray; }
div:not(:first-child) { margin-top: 10px; }
:not(p, span) { }  /* Exclude multiple */

/* :has() - parent selector! */
div:has(> img) { padding: 0; }
form:has(:invalid) { border: 2px solid red; }
h1:has(+ p) { margin-bottom: 0; }

Pseudo-Elements

::before         /* Insert content before */
::after          /* Insert content after */
::first-line     /* First line of text */
::first-letter   /* First letter of text */
::selection      /* User-selected text */
::placeholder   /* Input placeholder text */
::marker         /* List item bullets/numbers */

/* Example: Adding decorative content */
.quote::before {
  content: "\201C";  /* Left double quote */
  font-size: 3em;
  color: var(--primary);
}

/* Clearfix with ::after */
.clearfix::after {
  content: "";
  display: table;
  clear: both;
}

Specificity (How Conflicts are Resolved)

Specificity is calculated as a 4-part score: inline, IDs, Classes, Elements

SelectorSpecificityScore
*0, 0, 0, 00
p0, 0, 0, 11
p.class0, 0, 1, 111
.class0, 0, 1, 010
#id0, 1, 0, 0100
#id .class p0, 1, 1, 1111
style="..."1, 0, 0, 01000
!importantOverrides everything (except other !important)
Remember: :is() and :not() take the specificity of their most specific argument. :where() always has 0 specificity. Pseudo-elements count as elements (0,0,0,1).

3. Box Model

Box Model Structure

/*
  +------------------------------+
  |          MARGIN               |
  |  +--------------------------+ |
  |  |        BORDER            | |
  |  |  +--------------------+  | |
  |  |  |     PADDING        |  | |
  |  |  |  +--------------+  |  | |
  |  |  |  |   CONTENT    |  |  | |
  |  |  |  +--------------+  |  | |
  |  |  +--------------------+  | |
  |  +--------------------------+ |
  +------------------------------+
*/

.box {
  width: 200px;
  height: 100px;
  padding: 20px;
  border: 2px solid #333;
  margin: 10px;
}

box-sizing

/* content-box (DEFAULT):
   Total width = width + padding + border
   200 + 40 + 4 = 244px */
.box {
  box-sizing: content-box;
  width: 200px;
  padding: 20px;
  border: 2px solid;
}

/* border-box:
   Total width = width (includes padding + border)
   200px total */
.box {
  box-sizing: border-box;
  width: 200px;
  padding: 20px;
  border: 2px solid;
}

/* BEST PRACTICE: Apply to all elements */
*, *::before, *::after {
  box-sizing: border-box;
}

Margin

/* Individual sides */
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;

/* Shorthand: top right bottom left (clockwise) */
margin: 10px 20px 10px 20px;

/* Shorthand: top-bottom left-right */
margin: 10px 20px;

/* Shorthand: top left-right bottom */
margin: 10px 20px 30px;

/* All sides same */
margin: 10px;

/* Auto centering (needs width) */
margin: 0 auto;

/* Negative margins (pull element) */
margin-top: -20px;
Margin Collapse: Vertical margins between siblings collapse (the larger wins). Horizontal margins never collapse.

Padding, Border & Outline

/* Padding - same shorthand as margin */
padding: 10px 20px;

/* Border */
border: 2px solid #333; /* width style color */
border-top: 3px dashed red;
border-radius: 10px;       /* Rounded corners */
border-radius: 50%;        /* Circle */
border-radius: 10px 0 10px 0; /* TL TR BR BL */

/* Border styles: */
/* solid | dashed | dotted | double |
   groove | ridge | inset | outset | none */

/* Outline (doesn't affect layout!) */
outline: 2px solid blue;
outline-offset: 4px; /* Space from border */

Width & Height

width: 300px;
height: 200px;
min-width: 100px;
max-width: 800px;
min-height: 50px;
max-height: 600px;

/* Viewport units */
width: 100vw;   /* Full viewport width */
height: 100vh;  /* Full viewport height */

/* Intrinsic sizing */
width: fit-content;
width: min-content;
width: max-content;
width: auto;

4. Typography

Font Family & Stacks

/* Generic families */
font-family: serif;
font-family: sans-serif;
font-family: monospace;
font-family: cursive;
font-family: fantasy;

/* Font stack (fallback chain) */
font-family: 'Helvetica Neue', Arial, sans-serif;

/* System font stack (native look) */
font-family: system-ui, -apple-system,
  'Segoe UI', Roboto, sans-serif;

/* Monospace stack */
font-family: 'Cascadia Code', 'Fira Code',
  'JetBrains Mono', monospace;

Font Size, Weight & Style

/* Font size */
font-size: 16px;    /* Absolute */
font-size: 1.2em;   /* Relative to parent */
font-size: 1.2rem;  /* Relative to root */
font-size: 120%;    /* Percent of parent */
font-size: clamp(14px, 2vw, 22px); /* Fluid */

/* Font weight */
font-weight: normal;  /* = 400 */
font-weight: bold;    /* = 700 */
font-weight: 100;     /* Thin */
font-weight: 300;     /* Light */
font-weight: 500;     /* Medium */
font-weight: 900;     /* Black */

/* Font style */
font-style: normal;
font-style: italic;
font-style: oblique 14deg;

Text Properties

text-align: left | center | right | justify;
text-decoration: none | underline | overline | line-through;
text-transform: uppercase | lowercase | capitalize | none;
text-indent: 2em;
text-shadow: 2px 2px 4px rgba(0,0,0,0.5);

/* Spacing */
line-height: 1.6;       /* Unitless (recommended) */
letter-spacing: 0.05em;
word-spacing: 0.1em;

/* Overflow handling */
text-overflow: ellipsis; /* Needs overflow:hidden */
white-space: nowrap;
word-break: break-all;
overflow-wrap: break-word;
hyphens: auto;

Font Shorthand & @font-face

/* Font shorthand:
   font: style weight size/line-height family */
font: italic 700 16px/1.5 Arial, sans-serif;
font: bold 2em/1.4 Georgia, serif;

/* @font-face - load custom fonts */
@font-face {
  font-family: 'MyFont';
  src: url('font.woff2') format('woff2'),
       url('font.woff') format('woff');
  font-weight: 400;
  font-style: normal;
  font-display: swap; /* Show fallback while loading */
}

/* Truncate text with ellipsis */
.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* Multi-line truncate */
.line-clamp {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

5. Colors

Color Formats

/* Named Colors */
color: red;
color: tomato;
color: transparent;    /* Fully transparent */
color: currentColor;   /* Inherits current text color */

/* Hexadecimal */
color: #ff6347;         /* 6-digit hex */
color: #f63;             /* 3-digit shorthand (= #ff6633) */
color: #ff634780;       /* 8-digit hex with alpha */
color: #f637;           /* 4-digit shorthand with alpha */

/* RGB / RGBA */
color: rgb(255, 99, 71);
color: rgba(255, 99, 71, 0.5);    /* 50% opacity */
color: rgb(255 99 71 / 50%);     /* Modern syntax */

/* HSL / HSLA (Hue, Saturation, Lightness) */
color: hsl(9, 100%, 64%);         /* Hue: 0-360, S & L: 0-100% */
color: hsla(9, 100%, 64%, 0.5);
color: hsl(9 100% 64% / 50%);     /* Modern syntax */

/* Opacity (affects entire element + children) */
opacity: 0.5;    /* 0 = invisible, 1 = fully visible */

Short Named Colors (Useful for CSS Battle)

NameHexCharsNameHexChars
red#ff00003tan#d2b48c3
gold#ffd7004cyan#00ffff4
blue#0000ff4gray#8080804
lime#00ff004navy#0000804
pink#ffc0cb4peru#cd853f4
plum#dda0dd4teal#0080804
aqua#00ffff4snow#fffafa4
coral#ff7f505wheat#f5deb35
olive#8080005ivory#fffff05
khaki#f0e68c5linen#faf0e65

6. CSS Units

All CSS Units Explained

UnitTypeDescriptionExample
pxAbsolutePixels (1/96 of 1 inch)font-size: 16px
emRelativeRelative to parent's font-sizepadding: 1.5em
remRelativeRelative to root (<html>) font-sizemargin: 2rem
%RelativeRelative to parent's sizewidth: 50%
vwViewport1% of viewport widthwidth: 100vw
vhViewport1% of viewport heightheight: 100vh
vminViewport1% of smaller viewport dimensionfont-size: 5vmin
vmaxViewport1% of larger viewport dimensionwidth: 50vmax
chRelativeWidth of the "0" charactermax-width: 60ch
exRelativeHeight of the "x" charactermargin: 1ex
frGridFraction of available space (grid only)grid-template-columns: 1fr 2fr
cmAbsoluteCentimeterswidth: 10cm
mmAbsoluteMillimeterswidth: 100mm
inAbsoluteInches (1in = 96px)width: 2in
ptAbsolutePoints (1pt = 1/72 inch)font-size: 12pt
pcAbsolutePicas (1pc = 12pt)font-size: 1pc

calc() Function

/* Mix different units */
width: calc(100% - 40px);
height: calc(100vh - 60px);
font-size: calc(1rem + 0.5vw);
margin: calc(var(--gap) * 2);

/* Operators: + - * / */
/* IMPORTANT: spaces required around + and - */
width: calc(100%/3);     /* OK */
width: calc(100% - 10px); /* OK */
width: calc(100%-10px);  /* BROKEN! */

/* Nesting */
width: calc(100% - calc(2 * 20px));

min(), max(), clamp()

/* min() - picks the smallest value */
width: min(90%, 800px);
/* At most 800px, but shrinks on small screens */

/* max() - picks the largest value */
width: max(300px, 50%);
/* At least 300px, grows on large screens */

/* clamp(min, preferred, max) */
font-size: clamp(14px, 2.5vw, 24px);
/* Never below 14px, never above 24px,
   scales with viewport in between */

width: clamp(300px, 50%, 800px);
/* Responsive width with min/max bounds */

7. CSS Custom Properties (Variables)

Declaring & Using Variables

/* Declare on :root for global scope */
:root {
  --primary: #6c63ff;
  --text-color: #333;
  --spacing: 16px;
  --font: 'Inter', sans-serif;
  --shadow: 0 2px 10px rgba(0,0,0,0.1);
}

/* Use with var() */
.card {
  color: var(--text-color);
  padding: var(--spacing);
  font-family: var(--font);
  box-shadow: var(--shadow);
}

/* With fallback value */
color: var(--undefined, #000);
color: var(--a, var(--b, red));

Scope & Overriding

/* Variables are inherited */
:root {
  --bg: white;
  --text: black;
}

/* Override in a scope */
.dark-theme {
  --bg: #1a1a2e;
  --text: #e4e4e7;
}

/* Media query overrides */
@media (prefers-color-scheme: dark) {
  :root {
    --bg: #1a1a2e;
    --text: #e4e4e7;
  }
}

/* Use in calc() */
.box {
  padding: calc(var(--spacing) * 2);
  margin-bottom: calc(var(--spacing) / 2);
}

/* Use in shorthand */
.box {
  border: 2px solid var(--primary);
  background: var(--bg);
}