CSS3
This content is for Frontend. Switch to the latest version for up-to-date documentation.
CSS (Cascading Style Sheets) is the language used to style and lay out web pages. This guide covers everything from the basics to advanced concepts.
1. Syntax and Selectors
Section titled “1. Syntax and Selectors”Basic Syntax
Section titled “Basic Syntax”A CSS rule consists of a selector and a declaration block.
/* Selector { Property: Value; } */p { color: blue; font-size: 16px;}Common Selectors
Section titled “Common Selectors”- Type selector: Targets elements by tag name (
h1,p). - Class selector: Targets elements with a specific class (
.container). - ID selector: Targets a unique element (
#header). - Universal selector: Targets all elements (
*). - Combinators:
div p: Descendant selector (allpinsidediv).div > p: Child selector (direct children only).h1 + p: Adjacent sibling (immediately after).
2. The Cascade: Why is it called “Cascading”?
Section titled “2. The Cascade: Why is it called “Cascading”?”The “Cascading” in CSS refers to the way the browser determines which styles to apply to an element when multiple rules conflict. Styles “cascade” down from several sources (browser defaults, external sheets, internal styles) until they find the most specific rule.
Imagine water flowing down a series of steps:
- Origin: Is it a browser default or a developer’s style?
- Specificity: How precisely does the selector target the element?
- Source Order: If everything else is equal, the last rule defined wins.
Example of the Cascade
Section titled “Example of the Cascade”In the following example, the button will be blue because the class selector is more specific than the element selector, and the ID selector would be even stronger.
/* Rule 1: Element selector (Low specificity) */button { background-color: red;}
/* Rule 2: Class selector (Medium specificity) - OVERRIDES Rule 1 */.primary-btn { background-color: blue;}
/* Rule 3: Source order - If we added this below, it would win over Rule 2 *//* .primary-btn { background-color: green; } */Specificity Hierarchy
Section titled “Specificity Hierarchy”- Inline styles:
style="..."(highest) - IDs:
#header - Classes, pseudo-classes, attributes:
.btn,:hover,[type="text"] - Elements and pseudo-elements:
h1,::before
Inheritance
Section titled “Inheritance”Some properties (like color and font-family) are inherited by children from their parents. Others (like border and margin) are not.
3. Pseudo-classes and Pseudo-elements
Section titled “3. Pseudo-classes and Pseudo-elements”These allow you to style elements based on their state or specific parts.
- Pseudo-classes (
:): Style based on state.:hover,:focus,:active,:nth-child(even).
- Pseudo-elements (
::): Style specific parts.::before,::after(requires acontentproperty).::first-letter,::placeholder.
4. The Box Model
Section titled “4. The Box Model”The box model is the foundation of CSS layout. Every element is represented as a rectangular box.
- Content: The actual text or images.
- Padding: Space between the content and the border (inside the box).
- Border: A line surrounding the padding and content.
- Margin: Space outside the border (between boxes).
Box Sizing
Section titled “Box Sizing”By default (content-box), padding and borders are added to the width. Use box-sizing: border-box to include them within the defined width.
* { box-sizing: border-box; /* The modern standard */}Margin Collapsing
Section titled “Margin Collapsing”Vertical margins of adjacent elements sometimes collapse into a single margin (the largest of the two), rather than adding together.
5. Colors and Backgrounds
Section titled “5. Colors and Backgrounds”- Color Formats:
rgb(),hsl(),hex (#ffffff), and modernlch()oroklch(). - Gradients:
linear-gradient(to right, red, blue). - Backgrounds:
background-image,background-size: cover,background-position: center.
6. Typography and Units
Section titled “6. Typography and Units”- px: Absolute pixels.
- em: Relative to the font-size of the element.
- rem: Relative to the font-size of the root (
<html>) element. - vh/vw: Relative to 1% of the viewport height/width.
- vmin/vmax: Smallest or largest of vh/vw.
body { font-family: 'Inter', sans-serif; line-height: 1.6; font-size: 16px;}
h1 { font-size: 2.5rem; /* 40px if root is 16px */}7. Layout: Flexbox
Section titled “7. Layout: Flexbox”Flexbox is designed for one-dimensional layouts (rows or columns).
Flex Container Properties
Section titled “Flex Container Properties”.parent { display: flex; /* or inline-flex */ flex-direction: row | row-reverse | column | column-reverse; flex-wrap: nowrap | wrap | wrap-reverse;
/* Alignment */ justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly; align-items: stretch | flex-start | flex-end | center | baseline; align-content: stretch | flex-start | flex-end | center | space-between | space-around; /* Multi-line only */ gap: 20px; /* row-gap column-gap */}Flex Item Properties
Section titled “Flex Item Properties”- flex-grow: How much an item grows (default 0).
- flex-shrink: How much an item shrinks (default 1).
- flex-basis: Initial size before space distribution.
- flex: Shorthand for
grow shrink basis(e.g.,flex: 1 1 0). - align-self: Overrides
align-itemsfor a single item. - order: Changes visual order (default 0).
Flexbox Patterns
Section titled “Flexbox Patterns”- Perfect Center:
justify-content: center; align-items: center; - Sticky Footer:
flex-direction: column;on body,margin-top: auto;on footer. - Navigation:
justify-content: space-between;for logo and links.
8. Layout: Grid
Section titled “8. Layout: Grid”Grid is designed for two-dimensional layouts (rows and columns).
Grid Container Properties
Section titled “Grid Container Properties”.grid-container { display: grid; /* or inline-grid */ grid-template-columns: repeat(3, 1fr); grid-template-rows: auto 1fr; grid-template-areas: 'header header' 'sidebar main'; gap: 1rem;
/* Alignment */ justify-items: start | end | center | stretch; align-items: start | end | center | stretch; place-items: center; /* Shorthand */}Grid Item Properties
Section titled “Grid Item Properties”- grid-column:
1 / 3(starts at line 1, ends at line 3) orspan 2. - grid-row:
1 / span 2. - grid-area: Assigns item to a named area (e.g.,
grid-area: header).
Advanced Grid Features
Section titled “Advanced Grid Features”- auto-fit vs auto-fill:
auto-fit: Stretches items to fill the row.auto-fill: Keeps empty tracks if items don’t fill the row.
- minmax():
minmax(200px, 1fr)ensures a minimum width while staying fluid. - subgrid: Allows nested grids to align with the parent grid (
grid-template-columns: subgrid). - grid-auto-flow:
densefills in gaps left by larger items.
9. Positioning
Section titled “9. Positioning”- Static: Default flow.
- Relative: Positioned relative to its normal position.
- Absolute: Positioned relative to the nearest positioned ancestor.
- Fixed: Relative to the browser window.
- Sticky: Toggles between relative and fixed based on scroll.
Z-index and Stacking Context
Section titled “Z-index and Stacking Context”The z-index property controls the vertical stacking of overlapping elements. It only works on positioned elements (relative, absolute, fixed, sticky).
10. Responsive Design
Section titled “10. Responsive Design”Adapt the layout for different screen sizes and devices.
Media Queries: Two Approaches
Section titled “Media Queries: Two Approaches”1. Mobile First (min-width)
Section titled “1. Mobile First (min-width)”Style for mobile first, then add rules for larger screens. Recommended.
/* Base styles for mobile */.container { width: 100%;}
@media (min-width: 768px) { /* Tablet */ .container { width: 750px; }}@media (min-width: 1024px) { /* Desktop */ .container { width: 960px; }}2. Desktop First (max-width)
Section titled “2. Desktop First (max-width)”Style for desktop first, then add rules for smaller screens.
@media (max-width: 767px) { /* Below Tablet */ .sidebar { display: none; }}Standard Breakpoints
Section titled “Standard Breakpoints”- Mobile Small:
320px - Mobile Large:
480px - Tablet:
768px - Desktop:
1024px - Large Desktop:
1200px
Container Queries
Section titled “Container Queries”Modern CSS allows styling based on a parent container’s size rather than the whole viewport.
.parent { container-type: inline-size;}
@container (min-width: 500px) { .child { display: flex; }}11. Visual Effects
Section titled “11. Visual Effects”- Box Shadows:
box-shadow: 10px 10px 5px grey;. - Text Shadows:
text-shadow: 2px 2px red;. - Filters:
filter: blur(5px) grayscale(100%);. - Object Fit: Control how images/videos scale inside their container.
object-fit: cover;(crops to fill),object-fit: contain;(shows full image).
12. Advanced: CSS Variables
Section titled “12. Advanced: CSS Variables”Custom properties allow you to store values and reuse them.
:root { --primary-color: #3498db; --spacing: 1rem;}
.button { background-color: var(--primary-color); padding: var(--spacing);}13. Transforms, Transitions, and Animations
Section titled “13. Transforms, Transitions, and Animations”Transitions
Section titled “Transitions”Smoothly change property values over time.
.btn { /* transition: property duration timing-function delay; */ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);}Timing Functions: ease, linear, ease-in, ease-out, ease-in-out, or cubic-bezier().
Transforms (2D & 3D)
Section titled “Transforms (2D & 3D)”Modify the coordinate space of an element.
.box { transform: rotate(45deg) scale(1.2) translate(10px, 20px) skew(10deg);}
/* 3D transforms */.container { perspective: 1000px;}.card { transform: rotateY(180deg); transform-style: preserve-3d; backface-visibility: hidden;}Animations
Section titled “Animations”Create complex multi-step sequences.
@keyframes slide { 0% { transform: translateX(0); } 50% { transform: translateX(50px); } 100% { transform: translateX(100px); }}
.element { animation: slide 2s ease infinite alternate; animation-play-state: running | paused; animation-fill-mode: forwards | backwards | both | none;}Performance Optimization
Section titled “Performance Optimization”- Animate only:
transformandopacity. These are GPU-accelerated and don’t trigger “Layout” or “Paint” cycles. - will-change: Hint to the browser that an element will change (
will-change: transform;). Use sparingly. - translateZ(0): Force hardware acceleration.
14. Practical Recipes
Section titled “14. Practical Recipes”Loading Spinner
Section titled “Loading Spinner”@keyframes spin { to { transform: rotate(360deg); }}.spinner { width: 40px; height: 40px; border: 4px solid rgba(0, 0, 0, 0.1); border-left-color: #3498db; border-radius: 50%; animation: spin 1s linear infinite;}