CSS logoCSS BEGINNER

CSS

Complete CSS fundamentals reference covering selectors, box model, typography, colors, positioning, variables, and modern CSS features

12 min read
cssselectorsbox-modelpositioningvariablescustom-propertiestypographycolorsresponsive

Selectors & Specificity

Target elements with selectors and understand the cascade

Selectors

All the ways to target HTML elements with CSS

css
💡 :has() is a game-changer — it lets you style a parent based on its children
⚡ Use :is() to group selectors without repeating shared styles; :where() is the same but with 0 specificity
📌 Prefer :focus-visible over :focus for keyboard-only focus rings (better UX)
🟢 See also: CSS Flexbox, CSS Grid, and CSS Animations sheets for layout and motion
selectorscombinatorspseudo

Cascade & Specificity

How CSS determines which styles win when rules conflict

css
💡 Specificity is scored as ID-CLASS-ELEMENT — the higher score wins, left to right
⚡ :where() has 0 specificity — useful for defaults that should be easy to override
📌 Avoid !important — it breaks the cascade and makes debugging painful
🟢 @layer gives you control over cascade order without fighting specificity wars
specificitycascadeinheritance

Box Model

How elements are sized with content, padding, border, and margin

Box Model & Box Sizing

Content, padding, border, margin, and how box-sizing changes the calculation

css
💡 Always use box-sizing: border-box globally — it makes width actually mean total width
⚡ margin-inline: auto centers a block element horizontally (works in all modern browsers)
📌 Vertical margins collapse — two 20px margins between elements becomes 20px, not 40px
🟢 aspect-ratio: 16/9 maintains proportions without the old padding-top hack
box-modelpaddingmarginsizing

Spacing Patterns

Common margin and padding shorthand patterns and spacing techniques

css
💡 display: grid; place-items: center is the shortest way to center anything
⚡ gap works in both flex and grid — replaces margin hacks between items
📌 margin-inline: auto centers horizontally; margin: auto in grid/flex centers both axes
🟢 Build a spacing scale with CSS variables for consistent design system spacing
spacingmargincenteringgap

Typography

Font properties, text styling, and web fonts

Fonts & Text

Font properties, text alignment, spacing, and web font loading

css
💡 Use rem for font sizes (relative to root) — predictable and accessible when users change browser defaults
⚡ clamp(min, preferred, max) makes fluid typography easy — no media queries needed
📌 font-display: swap prevents invisible text while web fonts load (FOUT over FOIT)
🟢 text-wrap: balance evens out heading line lengths — great for narrow containers
typographyfontstext

Lists & Counters

Style ordered/unordered lists, custom markers, and CSS counters

css
💡 list-style: none + padding: 0 is the standard reset for navigation menus
⚡ ::marker pseudo-element lets you style bullet/number color and size independently
📌 CSS counters auto-number without using <ol> — great for steps, figures, and headings
🟢 Custom string list-style-type accepts any string: emojis, arrows, check marks
listsmarkerscounters

Colors & Backgrounds

Color formats, gradients, and background properties

Colors & Backgrounds

Color formats, opacity, gradients, and background sizing

css
💡 oklch() produces perceptually even colors — better for design systems than hsl
⚡ Use rgb(0 0 0 / 50%) for transparent backgrounds — doesn't affect child elements like opacity does
📌 background-size: cover fills the element; contain fits the whole image inside
🟢 Layer a dark gradient over an image for readable text on photo backgrounds
colorsbackgroundsgradients

Gradients

Linear, radial, and conic gradients for backgrounds and text

css
💡 Hard color stops at the same position create sharp lines — great for geometric patterns
⚡ Gradient text: background-clip: text + color: transparent reveals the gradient through text
📌 Conic gradients with border-radius: 50% create instant pie charts in pure CSS
🟢 repeating-linear-gradient creates stripes, checkerboards, and geometric patterns
gradientlinearradialconic

Positioning

Control element placement with position, z-index, and stacking

Position & z-index

Static, relative, absolute, fixed, and sticky positioning

css
💡 Absolute positioning needs a positioned ancestor (relative parent) — otherwise it uses the viewport
⚡ position: sticky is perfect for sidebars, table headers, and section headings
📌 z-index only works on positioned elements — static elements ignore it
🟢 inset: 0 is shorthand for top: 0; right: 0; bottom: 0; left: 0
positionz-indexstickyabsolute

Transforms

Move, rotate, scale, and skew elements with CSS transforms

css
💡 Transforms are GPU-accelerated — translateX/Y and scale are very performant for animations
⚡ transform: translateY(-4px) on hover creates a subtle lift effect — better than changing margin
📌 Transform order matters — translate then rotate gives different results than rotate then translate
🟢 Use perspective on the parent for 3D effects, and backface-visibility: hidden for flip cards
transformrotatescaletranslate

Display & Visibility

Control how elements render and whether they are visible

Display & Visibility

Block, inline, none, visibility, and opacity

css
💡 display: none removes from layout AND accessibility — use .sr-only to hide visually but keep for screen readers
⚡ object-fit: cover on images is like background-size: cover but for img/video elements
📌 inline elements ignore width, height, and vertical margin — use inline-block if you need those
🟢 See the CSS Flexbox and CSS Grid sheets for complete layout system references
displayvisibilityhide

Cursor, Pointer Events & User Select

Control mouse cursor appearance and element interactivity

css
💡 pointer-events: none makes an element click-through — clicks pass to elements behind it
⚡ cursor: grab + cursor: grabbing on :active gives proper drag feedback
📌 user-select: none on buttons and UI chrome prevents accidental text selection
🟢 Combine opacity: 0.5 + cursor: not-allowed + pointer-events: none for disabled states
cursorpointer-eventsuser-select

Borders, Shadows & Effects

Borders, rounded corners, shadows, and visual effects

Borders, Radius & Shadows

Border styles, rounded corners, box shadows, and filters

css
💡 box-shadow: 0 0 0 3px color creates a ring effect — great for focus states
⚡ backdrop-filter: blur() creates frosted glass effects — combine with semi-transparent background
📌 outline doesn't take up space or affect layout — border does
🟢 filter: drop-shadow follows the element shape (including transparency) — box-shadow is always rectangular
bordershadowradiusfilter

Focus Styles & Outlines

Accessible focus indicators for keyboard navigation

css
💡 Use :focus-visible instead of :focus — it only shows the ring for keyboard users, not mouse clicks
⚡ :focus-within styles a parent when ANY child inside it has focus — perfect for form groups
📌 Never remove focus outlines without providing an alternative — keyboard users need them
🟢 outline-offset creates a gap between the element and the focus ring for a cleaner look
focusoutlineaccessibility

Custom Properties & Functions

CSS variables and built-in math functions

CSS Variables & Functions

Define reusable values with custom properties and use calc, clamp, min, max

css
💡 CSS variables cascade and inherit — override them in any scope for easy theming
⚡ clamp(min, preferred, max) replaces min-width + max-width + media queries in one line
📌 var(--name, fallback) provides a default value if the variable is not defined
🟢 Use @media (prefers-color-scheme: dark) with variable overrides for system dark mode
variablescustom-propertiescalcclamp

Dark Mode & Theming

Implement dark mode with CSS variables and media queries

css
💡 Override CSS variables in @media (prefers-color-scheme: dark) — one change, everything updates
⚡ color-scheme: light dark on :root makes browser UI (scrollbars, inputs) match your theme
📌 Support both system detection and manual toggle — store the choice in localStorage
🟢 Slightly dim images in dark mode with filter: brightness(0.9) to reduce eye strain
dark-modethemingvariables

Transitions

Smooth property changes on hover, focus, and state changes

CSS Transitions

Animate property changes smoothly between states

css
💡 Transition individual properties instead of "all" — better performance and control
⚡ Only transition cheap properties: transform, opacity, color, background, box-shadow
📌 Avoid transitioning width/height/top/left — they trigger layout recalculation (janky)
🟢 See the CSS Animations sheet for keyframes, complex sequences, and timing deep-dives
transitionhoveranimation

Media Queries & Responsive

Adapt layouts for different screen sizes and user preferences

Media Queries

Responsive breakpoints, user preferences, and container queries

css
💡 Mobile-first (min-width) is the standard — start small, add complexity for larger screens
⚡ Container queries let components respond to their container size, not the viewport
📌 Always respect prefers-reduced-motion — disable animations for users who need it
🟢 See the Screen Sizes & Responsive Breakpoints sheet for device dimensions and patterns
media-queriesresponsivecontainer-queries

Container Queries

Style components based on their container size, not the viewport

css
💡 Container queries let components adapt to where they are placed, not just viewport size
⚡ The same .card component can have different layouts in a sidebar vs main content area
📌 Set container-type: inline-size on the parent — then @container queries check ITS width
🟢 Container query units (cqi, cqb) are like vw/vh but relative to the container
container-queriesresponsivecomponents

Modern CSS Features

CSS nesting, :has(), logical properties, and other recent additions

Nesting, :has() & Logical Properties

Modern CSS features supported in all major browsers

css
💡 CSS nesting is native now — same syntax as Sass/SCSS without the preprocessor
⚡ :has() is the most powerful CSS addition in years — style any ancestor based on descendants
📌 Logical properties (inline/block) make layouts work automatically for RTL languages
🟢 accent-color instantly themes checkboxes, radios, ranges, and progress bars
nestinghaslogicalmodern