CSS Tutorial
Learn CSS from first rule to modern layout. 139 hands-on lessons on selectors, the cascade, the box model, Flexbox, Grid, responsive design and animation, with a live editor in every lesson.
Start learning →
of lessons completed
Getting Started
- What Is CSS? Discover what CSS is, how browsers apply it to HTML, and what rules, selectors and declarations look like. Style your first page and see what the course covers.
- Adding CSS to a Page Learn the three ways to add CSS to HTML (the style attribute, a style element and a linked stylesheet), when to use each, and which one wins in a conflict.
- CSS Syntax Learn the anatomy of CSS rules, declarations, properties and values, how whitespace and case work, why invalid CSS is skipped, and what at-rules are.
- Comments and Code Organization Write CSS comments with /* */, use them to disable code while debugging, organize a stylesheet into clear sections, and follow formatting conventions teams rely on.
- Inspecting CSS with DevTools Use browser DevTools to see which CSS rules apply to an element, why declarations are crossed out, edit styles live, read the box model and force hover states.
Selectors
- Selector Basics Learn the five basic CSS selectors (type, class, ID, universal and comma grouping), when to use each one, and how to combine them into precise, readable rules.
- Combinators Learn the four CSS combinators (descendant, child >, next-sibling + and subsequent-sibling ~) and how to select elements by their place in the document tree.
- Attribute Selectors Learn every CSS attribute selector, from [attr] and exact matches to prefix, suffix and substring matching, word and language matches, and the case-insensitive i flag.
- Pseudo-classes Learn the CSS pseudo-classes that style elements by state, including hover, focus, focus-visible, checked, disabled, form validity, :user-invalid, :target, :empty and :root.
- Structural Pseudo-classes Master :first-child, :last-child, :only-child, :nth-child() with an+b formulas and "of S", :nth-of-type() and :nth-last-child(), with an interactive explorer.
- Pseudo-elements Learn CSS pseudo-elements, from ::before and ::after with content to ::first-letter, ::first-line, ::marker, ::placeholder, ::selection, ::backdrop and ::file-selector-button.
- :is(), :where(), :not() and :has() Learn the CSS selector functions :is(), :where(), :not() and :has(), how their specificity differs, forgiving selector lists, and practical parent-selector patterns.
- Rarely Used Selectors: :lang(), :dir(), :scope and @namespace Learn four selector features you will meet less often, :lang(), :dir(), :scope and @namespace, with working examples for multilingual, right-to-left and SVG pages.
The Cascade
- How the Cascade Works Learn how the browser decides which CSS declaration wins when several rules target the same element, from origins and importance to specificity and order.
- Specificity Learn how browsers score CSS selectors with the (a, b, c) specificity model, compare selectors with a live calculator, and keep specificity low with :where().
- Inheritance Learn which CSS properties pass from parent to child, why form controls ignore your fonts, and how inherit, initial, unset and revert control inheritance.
- !important Learn exactly how !important changes the CSS cascade, why it reverses origins and layers, the few cases where it is the right tool, and safer alternatives.
- Cascade Layers Use @layer to control which CSS wins by layer instead of specificity. Learn layer order, unlayered styles, !important, nesting and importing CSS into layers.
- Global Values: initial, inherit, unset, revert Learn the CSS keywords every property accepts (initial, inherit, unset, revert and revert-layer) and how the all property resets an element in one line.
Values and Units
- Units: px, em, rem and More Learn the difference between absolute and relative CSS units, when to use px, em, rem, %, ch and lh, and how em compounds while rem stays predictable.
- Viewport Units Learn CSS viewport units, from vw and vh to vmin, vmax and the new svh, lvh and dvh units that fix full-height layouts behind mobile address bars.
- Colors Learn every everyday way to write a CSS color, from named colors and hex codes to rgb() and hsl(), plus transparency, opacity, currentColor and transparent.
- Modern Color: oklch() and color-mix() Learn modern CSS color with oklch(), wide-gamut display-p3, color-mix(), relative color syntax and light-dark(), with honest notes on browser support.
- calc(), min(), max() and clamp() Learn to do math in CSS with calc(), mix units, pick the smaller or larger value with min() and max(), and build fluid sizes with clamp() in a live visualizer.
- Custom Properties (CSS Variables) Learn CSS custom properties from --name and var() fallbacks to scope, inheritance, theming, changing values with JavaScript and typed @property rules.
- Advanced Math Functions: round(), mod() and Trigonometry Go beyond calc() with CSS round(), mod(), rem(), abs(), sign(), pow(), sqrt(), hypot() and trigonometry. Snap values to steps and place items on a circle.
- env() and attr(): Reading the Device and the HTML Use env() to respect notches and safe-area insets with fallbacks, and attr() to pull HTML attribute values into content and, with typed attr(), into real properties.
The Box Model
- The Box Model Learn the CSS box model, the four layers around every element, and how the browser adds content, padding and border together to get an element's real size.
- box-sizing Learn how box-sizing changes what width and height measure, why border-box is easier to work with, and how to apply the universal border-box reset safely.
- Width and Height Learn how CSS width and height work, what auto really means, how min- and max- limits protect your layout, and when to use min-content, max-content and fit-content.
- Margins Learn CSS margins from the shorthand to auto centering and negative margins, plus the exact rules of margin collapsing and how to stop it when you need to.
- Padding Learn how CSS padding adds breathing room inside an element, how the shorthand and percentages work, and how to choose between padding and margin every time.
- Borders Learn how CSS borders work, from border-style, width and color to single sides, logical properties and the border shorthand, with live examples to edit.
- Rounded Corners Round corners with CSS border-radius. Learn single and per-corner values, elliptical corners with the slash syntax, percentages, circles, pills and blob shapes.
- Border Images Learn CSS border-image, from source, slice, width, outset and repeat to gradient borders, custom dashed lines and how to combine gradient borders with rounded corners.
- Outlines Learn how CSS outlines differ from borders, how outline-offset works, and how to design clear, accessible focus indicators with :focus-visible.
- Box Shadows Master CSS box-shadow, from offsets, blur and spread to inset and layered shadows, and build a consistent elevation system that looks natural on light and dark pages.
- Overflow Control what happens when content is too big for its box with CSS overflow. Compare visible, hidden, clip, scroll and auto, set each axis, and style scroll areas.
Text and Fonts
- Styling Text Style text with CSS color, text-align, text-decoration, text-transform, letter-spacing and word-spacing, including modern underline offset and thickness.
- Fonts Choose typefaces with font-family and font stacks, size text with font-size, set weight and style, and combine everything with the CSS font shorthand.
- Web Fonts Load your own typefaces with @font-face, serve WOFF2, control loading with font-display, use variable fonts, and keep web fonts fast by self-hosting them.
- Variable Fonts and OpenType Features Unlock hidden font features: font-variant-* and font-feature-settings for numerals, ligatures and small caps, and font-variation-settings for variable axes.
- Line Height and Vertical Rhythm Set comfortable line-height with unitless values, limit line length with the ch unit, and space paragraphs and headings for a calm, readable vertical rhythm.
- Wrapping, Overflow and Hyphens Control how text breaks with white-space, overflow-wrap, word-break and hyphens, truncate with ellipsis, clamp to a few lines, and balance headings with text-wrap.
- Modern Text Features: text-box-trim and initial-letter Use newer CSS text features: trim extra space with text-box, make drop caps with initial-letter, and combine them with text-wrap and hanging punctuation.
- Text Shadows Add depth, glows and outlines to text with CSS text-shadow, layer multiple shadows, and use subtle shadows to keep text readable on photos and busy backgrounds.
- Writing Modes and Logical Properties Learn how writing-mode and direction change the flow of text, and use logical properties like margin-inline and padding-block to build layouts that work in any language.
Backgrounds and Effects
- Backgrounds Learn the CSS background properties - color, image, repeat, position, size with cover and contain, attachment - and how to write the background shorthand.
- Multiple Backgrounds and background-clip Stack several background layers on one element, control where each is painted with background-origin and background-clip, and fill text with a gradient.
- Gradients Create CSS gradients with linear-gradient(), radial-gradient() and conic-gradient(), control color stops and hints, and build stripes and patterns with no image files.
- Sizing Images: object-fit and aspect-ratio Fit images and videos into fixed boxes without distortion using object-fit and object-position, and keep any element in proportion with aspect-ratio.
- Styling Images Style images with CSS - responsive images, rounded and circular photos, thumbnails, hover overlays, captions, grid galleries, sprites and an image lightbox with dialog.
- Filters Apply CSS filter functions like blur, brightness, grayscale and drop-shadow, chain them together, and build frosted-glass panels with backdrop-filter.
- Image Reflections and Hover Effects Create a mirror reflection under an image with -webkit-box-reflect or a portable mask-image version, and build zoom, grayscale and caption hover effects the accessible way.
- Blend Modes Mix colors between layers with mix-blend-mode and background-blend-mode, learn what multiply, screen and overlay do, and contain blending with isolation.
- Clip Paths and Masks Cut elements into circles, polygons and custom shapes with clip-path, then fade and shape them with mask-image, gradients and SVG icons that you can recolor.
Layout Fundamentals
- The display Property Learn how the CSS display property controls layout, from block and inline boxes to inline-block, none, flow-root and contents, plus the outer and inner display model.
- Opacity and Visibility Compare opacity with alpha colors, and visibility hidden with display none, content-visibility and the hidden attribute. Hide content accessibly and fade it smoothly.
- Positioning Master CSS positioning with static, relative, absolute, fixed and sticky, the inset properties, and containing blocks that decide where a positioned box lands.
- z-index and Stacking Contexts Learn how browsers decide which element is on top, how z-index really works, what creates a stacking context, and how to debug a z-index that seems ignored.
- Floats Use CSS float to wrap text around images and pull quotes, stop wrapping with clear, contain floats with flow-root, and shape text with shape-outside.
- CSS Shapes Wrap text around circles, ellipses, polygons and images with shape-outside, add space with shape-margin, and style split inline boxes with box-decoration-break.
- Centering Anything Center text, blocks and whole components in CSS, horizontally and vertically, with text-align, margin auto, flexbox, grid, place-items and position plus transform.
- Multi-column Layout Flow content into newspaper-style columns with CSS columns, add gaps and rules, keep items from splitting with break-inside, and span headings across columns.
- Image Galleries and Masonry-style Layouts Build galleries in CSS: uniform grids, justified flex rows, column-based masonry and spanning grids, plus where native masonry and grid-lanes stand.
- Flexbox vs Grid: Choosing a Layout Compare CSS Flexbox and Grid side by side. Learn the one-dimensional versus two-dimensional rule, build the same layout both ways and pick the right tool.
- Sticky Headers, Scroll Containers and Scrollbar Styling Fix position: sticky that does not stick, control scroll containers with scrollbar-gutter and overscroll-behavior, and style scrollbars with modern CSS.
- overscroll-behavior: Stopping Scroll Chaining Learn overscroll-behavior to stop scroll chaining out of panels and modals, control pull-to-refresh and swipe-back gestures, and set values per axis.
Flexbox
- Flexbox Basics Learn how CSS Flexbox works: flex containers and items, the main and cross axis, and how to build your first flexible row of content step by step.
- Flex Container Properties Master the flex container: flex-direction, flex-wrap, flex-flow, justify-content, align-items, align-content and gap, with a live playground to try them all.
- Flex Item Properties Control individual flex items with flex-grow, flex-shrink, flex-basis and the flex shorthand, and learn how order and align-self change single items.
- Flexbox Patterns Build five real-world Flexbox patterns: a navbar, a media object, equal-height cards with aligned footers, a sticky footer and wrapping tags.
Grid
- Grid Basics Learn how CSS Grid works: grid containers and items, columns and rows, the gap property, and how to build your first two-dimensional layout step by step.
- Grid Tracks: fr, repeat() and minmax() Size CSS Grid columns and rows with the fr unit, repeat(), minmax() and intrinsic keywords, and learn exactly when auto-fill and auto-fit behave differently.
- Placing Grid Items Position CSS Grid items with line numbers, span and negative lines, understand the implicit grid, and fill gaps automatically with grid-auto-flow dense.
- Grid Template Areas Name regions of a CSS grid with grid-template-areas, place items with grid-area, leave cells empty, and rearrange a whole page layout at a breakpoint.
- Grid Alignment Align CSS Grid items inside their cells and the whole grid inside its container with justify-items, align-items, the -content and -self properties and place-*.
- Subgrid Learn CSS subgrid: let nested elements share their parent grid's tracks so card titles, text and buttons line up perfectly across a whole row.
- Grid Patterns Put CSS Grid to work with proven patterns: full page layouts, responsive galleries without media queries, overlapping text on images and breakout content.
Responsive Design
- Responsive Design Principles Learn the core ideas of responsive design in CSS - fluid layouts, flexible images, the viewport meta tag and intrinsic layouts that adapt without breakpoints.
- Media Queries Apply CSS only when conditions match. Learn @media syntax, the modern range syntax, orientation, hover and pointer, prefers-* features and combining queries.
- Hover, Pointer and Touch: Designing for Every Input Design for mouse, finger and keyboard. Combine hover and pointer media queries with touch-action, cursor, user-select and pointer-events.
- Mobile-First CSS Write responsive CSS mobile-first. Start with small-screen styles, add min-width breakpoints, choose breakpoints from your content, and build a complete page.
- Container Queries Make components respond to their own space with CSS container queries. Learn container-type, @container, named containers, cqi units and style queries.
- Fluid Typography Make text scale smoothly between screen sizes with clamp(). Build a fluid type scale, keep lines readable, respect zoom, and choose viewport or container units.
Lists, Tables and Forms
- Styling Lists Style HTML lists with CSS. Change bullets and numbers with list-style, color them with ::marker, build custom markers, and remove bullets without hurting accessibility.
- CSS Counters Number headings, figures and nested lists with CSS counters. Learn counter-reset, counter-increment, counter(), counters() and styled nested numbering like 1.2.3.
- Styling Tables Make data tables readable with CSS. Learn border-collapse, padding, zebra striping, number alignment, sticky headers, table-layout and responsive scrolling tables.
- Styling Forms Style form controls that look consistent and stay accessible. Learn appearance, accent-color, focus rings, :user-invalid validation states, field-sizing and custom checkboxes.
- Styling Buttons and Links Style buttons and links that look good and work for everyone. Cover hover, focus-visible, active and disabled states, cursors, transitions and readable links.
UI Components
- Icons in CSS Add crisp, recolorable icons with inline SVG, SVG sprites and mask-image, size them with em and currentColor, avoid icon-font pitfalls and keep them accessible.
- Dropdown Menus Build dropdown menus with :hover and :focus-within, details and summary, and the popover attribute. Position panels well and keep them usable with a keyboard.
- Tooltips Build tooltips with ::after and attr(), add arrows, place them on any side, and make them accessible with aria-describedby, focus support and Escape to close.
- Pagination and Breadcrumb Styling Style pagination bars with clear current and disabled states, breadcrumbs with accessible separators, and joined button groups and segmented controls in CSS.
- Spinners, Loaders and Skeletons Build CSS loading spinners, styled progress bars and shimmering skeleton screens, and make them accessible with role="status", aria-busy and reduced motion.
- User Interface Properties Control how people interact with your page using cursor, resize, user-select, pointer-events, caret-color, accent-color, scrollbar styling and touch-action.
Transforms and Animation
- Transitions Animate CSS changes smoothly with transitions. Learn duration, delay and easing with cubic-bezier(), steps() and linear(), and which properties animate well.
- 2D Transforms Move, rotate, scale and skew elements with CSS transforms. Learn transform-origin, why function order matters, and the translate, rotate and scale properties.
- 3D Transforms Add depth with CSS 3D transforms: perspective, rotateX and rotateY, translateZ, preserve-3d and backface-visibility, then build an accessible flip card.
- Keyframe Animations Build CSS keyframe animations. Define @keyframes, then control duration, delay, iteration, direction, fill-mode and play-state, and stagger and pause motion.
- Motion Path: offset-path and offset-distance Move elements along a curve with CSS motion path. Learn offset-path, offset-distance, offset-rotate and offset-anchor, and animate them with keyframes.
- Scroll-driven Animations Link CSS animations to scrolling with animation-timeline, scroll() and view(). Build progress bars and reveal effects with animation-range and safe fallbacks.
- View Transitions Animate between page states with the View Transition API. Learn startViewTransition(), view-transition-name, its pseudo-elements and cross-page support.
- Motion, Performance and prefers-reduced-motion Make CSS animation smooth and comfortable. Learn the rendering pipeline, compositor-friendly properties, will-change, and how to respect reduced motion.
Modern CSS
- CSS Nesting Learn native CSS nesting, how the & selector works, how to nest media and container queries, and how nested rules affect specificity compared with Sass.
- Feature Queries (@supports) Use @supports to test whether a browser understands a CSS property, value or selector, and build pages that improve gracefully as browsers add new features.
- Scroll Snap Build smooth carousels and galleries with CSS scroll snap, then polish scrolling with scroll-padding, scroll-margin, overscroll-behavior and scrollbar-gutter.
- Anchor Positioning Tether tooltips, menus and labels to other elements with CSS anchor positioning, using anchor-name, position-area, anchor() and automatic fallbacks.
- @scope Learn CSS @scope to limit styles to one part of a page, stop them at an inner boundary with donut scope, and let the nearest scope win conflicts.
- Design Tokens and Theming Build a three-layer design token system with CSS custom properties, then switch between several themes, density modes and dark mode with a single attribute.
- @property and Typed Custom Properties Register custom properties with @property to give them a type, an initial value and controlled inheritance, then animate gradients, counters and sizes.
- CSS Houdini and the Paint API Meet CSS Houdini: try the Typed OM and registerProperty, and see how a paint worklet draws a custom background, with fallbacks for browsers without support.
Best Practices
- Dark Mode Build a dark mode with CSS using prefers-color-scheme, color-scheme, light-dark() and custom properties, then add a manual toggle that overrides the system.
- Accessible CSS Write CSS that works for everyone, with readable contrast, clear focus styles, accessible hiding, reduced motion, zoom support and forced colors mode.
- Organizing CSS Keep growing stylesheets manageable with BEM naming, utility classes, component styles, design tokens, cascade layers and a clear file structure.
- Preprocessors and Frameworks Learn what Sass, Less and PostCSS add to CSS, how Tailwind and Bootstrap work, which features native CSS now covers, and how to decide what your project needs.
- Resets and Base Styles Learn why CSS resets exist, how a reset differs from normalize, and how to write a small modern reset and base styles that suit any new project.
- CSS Performance Make CSS fast. Understand render-blocking stylesheets, inline critical CSS, skip selector myths, and speed up rendering with content-visibility and contain.
- Print Styles Make web pages print well with @media print, hide screen-only parts, show link URLs, control page breaks and set page margins and size with @page.
- CSS At-rules Overview A map of every CSS at-rule, from @import, @media and @layer to @property, @counter-style and @starting-style: what each does, how it's written, and where to learn more.
- CSS Frameworks: Bootstrap and Tailwind Concepts Understand how component frameworks like Bootstrap and utility-first frameworks like Tailwind work under the hood by building tiny versions of both yourself.
- Sass in Practice A practical guide to Sass and SCSS: set up a project, use variables, nesting, mixins, maps and modules with @use, and see the plain CSS that the compiler outputs.
- CSS Architecture: BEM, ITCSS and Utility Classes Learn naming and layering strategies for large CSS codebases: BEM naming, ITCSS layers mapped to @layer, class prefixes and utility classes, with working examples.
- Linting and Visual Regression for CSS Catch CSS bugs automatically: configure Stylelint, add screenshot-based visual regression tests, and check color contrast in code before users find the problems.
Projects
- Project: Profile Card Build a polished profile card with CSS in seven stages. Practice the box model, rounded corners, shadows, typography, flexbox and smooth hover effects.
- Project: Responsive Navigation Bar Build a responsive site header in seven stages with flexbox, a details and summary mobile menu, clear link states, a media query and a sticky header.
- Project: Pricing Page Build a responsive pricing page in seven stages with CSS Grid, subgrid, custom properties, a highlighted plan and a monthly or yearly switch made with :has().
- Project: Responsive Restaurant Website Build a complete one-page restaurant website in seven stages, mobile-first, with a sticky header, a hero, a menu grid with container queries and a booking form.
- Project: Documentation Layout Build a three-column documentation page in seven stages with a sticky sidebar, an On this page box, readable code blocks, callouts and menus that collapse on phones.
- Project: Dashboard Layout Build a responsive admin dashboard in eight stages with grid template areas, a sidebar, stat cards, a CSS bar chart, container queries and dark mode.
- Project: Tribute Page Build a single-page tribute in four stages with a hero image, a CSS-only timeline, a styled pull quote and a footer, using pseudo-elements, logical properties and custom properties.
- Project: Contact Us Page Build a contact page in four stages with an accessible form, a two-column CSS grid, clear focus styles and validation states using :user-invalid and :has().
- Project: Newsletter Layout Build a responsive newsletter in three stages with table layout and inline styles, then learn why email CSS differs from web CSS and how to test it safely.
- Project: Meet the Team Page Build a Meet the Team page in four stages with a responsive card grid, hover and focus overlays, touch-friendly fallbacks and social links, using only CSS.
- Project: Browser Window Mockup Draw a browser window in pure CSS, with traffic-light buttons, tabs, an address bar and a dark variant, using Flexbox, custom properties and no images or JavaScript.
Practice and Review
- CSS Cheat Sheet A one-page CSS cheat sheet with selectors, specificity, units, the box model, flexbox, grid, responsive design, animation and modern CSS, with live examples.
- CSS Recipes Gallery Twenty small, copy-ready CSS recipes with live editors, from toggle switches, tooltips and flip cards to timelines, segmented controls and skeleton loaders.
- CSS Practice Exercises Practice CSS with 28 graded exercises on selectors, the cascade, the box model, flexbox, grid, responsive design and animation, each with a live editor and solution.
- CSS Interview Questions Prepare for front-end interviews with 39 CSS questions and clear answers on the box model, specificity, flexbox, grid, responsive design, performance and architecture.