CSS & Layout

Style and layout techniques for modern web apps

Selectors & Specificity

Target elements with selectors; conflicts resolved by specificity and source order.

SelectorExampleNotes
TypepAll paragraphs
Class.cardReusable style
ID#mainUnique element
Attributeinput[type=email]Filter by attributes
Pseudo-classa:hoverElement state
Pseudo-elementp::first-linePart of element

Specificity

Inline (1000) > ID (100) > Class/Attr/Pseudo-class (10) > Type (1). Avoid !important.

Cascade & Inheritance

  • Later rules override earlier ones if specificity ties.
  • Properties like color/font inherit to children; box properties do not.
  • Use initial, inherit, unset to control inheritance.

Box Model

Each element has content, padding, border, and margin. Use box-sizing:border-box for predictable sizing.

*,*::before,*::after{box-sizing:border-box}
.box{width:300px;padding:16px;border:2px solid #185a9d;margin:12px}
        

Units & Colors

  • Absolute: px; Relative: em, rem, %; Viewport: vw, vh.
  • Color formats: #RRGGBB, rgb(), hsl(); prefer HSL for readability.
  • Use CSS variables for theme: :root { --primary: #185a9d; }

Flexbox

  • One-dimensional layout (row or column)
  • Main axis alignment: justify-content; cross axis: align-items
  • Item control: flex shorthand = flex-grow flex-shrink flex-basis
.row{display:flex;gap:12px}
.row .item{flex:1}
.navbar{display:flex;justify-content:space-between;align-items:center}
        

CSS Grid

  • Two-dimensional layout: rows and columns
  • Responsive grids with repeat(auto-fit, minmax(220px,1fr))
.cards{display:grid;gap:16px;grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}
.layout{display:grid;grid-template-columns:320px 1fr;gap:24px}
        

Responsive Design

  • Mobile-first media queries: @media (min-width: 768px) { ... }
  • Fluid images: img { max-width: 100%; height: auto; }
  • Responsive type: clamp sizes, e.g., font-size: clamp(1rem, 2vw + 0.5rem, 1.5rem)

Typography

  • Use system fonts or web fonts with font-display: swap.
  • Line-length ~45–75 characters; line-height ~1.5 for readability.
  • Contrast and hierarchy using size, weight, and color.