📝 CSS Basics
1. CSS Syntax & Structure
CSS (Cascading Style Sheets) controls how HTML elements look. Every CSS rule follows this structure:
<!-- HTML Structure --> <h1 class="title">Welcome</h1> <p class="description">This is a paragraph.</p> <button class="btn">Click Me</button>
/* CSS Rule Structure */ selector { property: value; } /* Example */ .title { color: blue; font-size: 24px; } .description { color: gray; line-height: 1.6; } .btn { background: #3498db; color: white; padding: 10px 20px; }
Welcome
This is a paragraph.
💡 CSS Rule Parts
Selector: What to style (e.g., .title) | Property: What to change (e.g., color) | Value: The new value (e.g., blue)
2. Three Ways to Add CSS
You can add CSS to your HTML in three different ways:
<!-- 1. INLINE CSS (style attribute) --> <!-- Avoid this - hard to maintain --> <h1 style="color: red; font-size: 24px;"> Red Heading </h1> <p style="color: blue; padding: 10px;"> Blue paragraph with padding </p> <div style="background: yellow; margin: 20px;"> Yellow box </div>
<!-- 2. INTERNAL CSS (in <head>) --> <head> <style> h1 { color: red; font-size: 24px; } .my-paragraph { color: blue; padding: 10px; } .my-box { background: yellow; margin: 20px; } </style> </head>
<!-- 3. EXTERNAL CSS (Recommended!) --> <!-- Link in HTML <head> --> <!DOCTYPE html> <html> <head> <title>My Page</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1 class="title">Hello</h1> <p class="text">World</p> </body> </html>
/* styles.css - Separate CSS file */ .title { color: red; font-size: 24px; } .text { color: blue; padding: 10px; } /* Benefits of External CSS: - Reusable across multiple pages - Browser can cache the file - Keeps HTML clean - Easier to maintain */
⚠️ Best Practice
Always use external CSS files for real projects. It keeps your code organized and allows caching for better performance.
3. Colors & Units
CSS supports multiple ways to define colors and measurement units.
/* COLOR FORMATS */ color: red; /* Named color */ color: #3498db; /* Hex (6 digits) */ color: #3498db80; /* Hex with alpha */ color: rgb(52, 152, 219); /* RGB */ color: rgba(52, 152, 219, 0.5); /* RGBA (with transparency) */ color: hsl(204, 70%, 53%); /* HSL (hue, saturation, lightness) */
/* MEASUREMENT UNITS */ width: 200px; /* Pixels (absolute) */ width: 50%; /* Percentage of parent */ font-size: 1.5em; /* Relative to parent font */ font-size: 1.5rem; /* Relative to root font ✓ */ width: 100vw; /* Viewport width */ height: 100vh; /* Viewport height */ /* CALCULATIONS */ width: calc(100% - 200px); font-size: clamp(1rem, 2vw, 2rem); /* min, preferred, max */
🎯 CSS Selectors
1. Basic Selectors
The fundamental ways to target HTML elements.
/* Universal Selector - selects ALL elements */ * { margin: 0; box-sizing: border-box; } /* Element/Type Selector - by tag name */ p { line-height: 1.6; } button { cursor: pointer; } /* Class Selector - reusable, starts with dot (.) */ .product-card { border: 1px solid #ddd; } .btn { padding: 10px 20px; } /* ID Selector - unique, starts with hash (#) */ #header { position: fixed; } /* Grouping Selector - apply same styles to multiple */ h1, h2, h3 { color: #333; font-family: sans-serif; }
2. Combinator Selectors
Select elements based on their relationship to other elements.
/* Descendant (space) - ANY nested element */ .card p { color: gray; } /* Selects all p inside .card, any depth */ /* Child (>) - DIRECT children only */ .card > p { margin: 10px; } /* Only p that are immediate children */ /* Adjacent Sibling (+) - immediately after */ h2 + p { font-size: 1.2rem; } /* First p right after h2 */ /* General Sibling (~) - all siblings after */ h2 ~ p { color: #555; } /* All p siblings after h2 */
p (child ✓, descendant ✓)
p (descendant ✓, not child)
3. Attribute Selectors
Select elements based on their attributes or attribute values.
/* Has attribute */ [disabled] { opacity: 0.5; cursor: not-allowed; } /* Exact attribute value */ [type="text"] { border: 1px solid #ccc; } [type="submit"] { background: #3498db; } /* Starts with (^=) */ [href^="https"] { color: green; } /* Secure links */ /* Ends with ($=) */ [href$=".pdf"] { color: red; } /* PDF links */ [src$=".png"] { border: none; } /* PNG images */ /* Contains (*=) */ [href*="google"] { font-weight: bold; } /* Google links */
4. Pseudo-Class Selectors (States & Position)
Select elements based on their state or position in the DOM.
/* === USER INTERACTION STATES === */ a:link { color: blue; } /* Unvisited link */ a:visited { color: purple; } /* Visited link */ a:hover { color: red; } /* Mouse over */ a:active { color: orange; } /* Being clicked */ button:hover { background: #2980b9; } input:focus { border-color: #3498db; outline: none; } /* === FORM STATES === */ input:enabled { background: white; } input:disabled { background: #eee; } input:checked { accent-color: #3498db; } input:required { border-left: 3px solid red; } input:valid { border-color: green; } input:invalid { border-color: red; }
/* === STRUCTURAL/POSITIONAL === */ li:first-child { font-weight: bold; } li:last-child { border-bottom: none; } li:nth-child(2) { color: red; } /* 2nd item */ li:nth-child(odd) { background: #f5f5f5; } li:nth-child(even) { background: #fff; } li:nth-child(3n) { color: blue; } /* Every 3rd */ p:first-of-type { font-size: 1.2em; } div:empty { display: none; } /* === NEGATION === */ button:not(.disabled) { cursor: pointer; } li:not(:last-child) { border-bottom: 1px solid #ddd; }
5. Pseudo-Element Selectors (::)
Style specific parts of an element or insert content.
/* Insert content before/after element */ .price::before { content: '₹'; } .required::after { content: ' *'; color: red; } /* Decorative element (empty content) */ .card::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 4px; background: linear-gradient(to right, #3498db, #9b59b6); } /* Style first letter/line */ p::first-letter { font-size: 3em; float: left; color: #3498db; } p::first-line { font-weight: bold; } /* Style text selection */ ::selection { background: #3498db; color: white; } /* Style placeholder text */ input::placeholder { color: #999; font-style: italic; } /* Style list markers */ li::marker { color: #3498db; }
6. Specificity (Which Rule Wins?)
When multiple rules target the same element, specificity determines which one applies.
| Selector Type | Specificity | Example |
|---|---|---|
| Inline styles | 1000 | style="..." |
| ID | 100 | #header |
| Class, attribute, pseudo-class | 10 | .nav, [type], :hover |
| Element, pseudo-element | 1 | div, ::before |
p { } /* Specificity: 0-0-1 */ .card { } /* Specificity: 0-1-0 */ #header { } /* Specificity: 1-0-0 */ #header .nav li a { } /* Specificity: 1-1-2 */ .card.featured { } /* Specificity: 0-2-0 */ /* !important overrides everything (AVOID using this!) */ .card { color: red !important; }
⚠️ Avoid !important
Using !important makes debugging difficult. Instead, write more specific selectors or reorganize your CSS.
📦 Box Model
Understanding the Box Model
Every HTML element is a box with content, padding, border, and margin.
.box { /* Content size */ width: 300px; height: 200px; min-width: 200px; max-width: 100%; /* Padding (inside border) */ padding: 20px; /* All sides */ padding: 10px 20px; /* vertical | horizontal */ padding: 10px 20px 15px 5px; /* top right bottom left */ /* Border */ border: 2px solid #333; border-radius: 10px; /* Rounded corners */ border-radius: 50%; /* Circle */ /* Margin (outside border) */ margin: 20px; margin: 0 auto; /* Center horizontally */ /* IMPORTANT: box-sizing */ box-sizing: border-box; /* width includes padding+border */ }
💡 Always Use border-box
Add this to the top of every stylesheet: *, *::before, *::after { box-sizing: border-box; }
Box Shadow & Overflow
/* Box Shadow: x-offset y-offset blur spread color */ box-shadow: 0 4px 6px rgba(0,0,0,0.1); /* Subtle */ box-shadow: 0 10px 40px rgba(0,0,0,0.2); /* Elevated */ box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); /* Inner shadow */ box-shadow: 0 0 0 3px #3498db; /* Focus ring */ /* Multiple shadows */ box-shadow: 0 4px 6px rgba(0,0,0,0.1), 0 10px 20px rgba(0,0,0,0.1); /* Overflow - what happens when content exceeds box */ overflow: visible; /* Default - content overflows */ overflow: hidden; /* Clip overflow */ overflow: scroll; /* Always show scrollbars */ overflow: auto; /* Scrollbars when needed */ overflow-x: hidden; overflow-y: auto; /* Separate axes */
✍️ Typography
Font Properties
.text { /* Font family with fallbacks */ font-family: 'Segoe UI', Arial, sans-serif; /* Font size */ font-size: 1rem; /* Recommended: relative units */ font-size: 16px; /* Absolute pixels */ /* Font weight */ font-weight: 400; /* normal */ font-weight: 700; /* bold */ font-weight: bold; /* keyword */ /* Font style */ font-style: italic; font-style: normal; /* Line height (spacing between lines) */ line-height: 1.6; /* Unitless recommended */ }
Text Properties
.text { /* Alignment */ text-align: left; /* left | center | right | justify */ /* Decoration */ text-decoration: underline; text-decoration: line-through; text-decoration: none; /* Remove underline from links */ /* Transform */ text-transform: uppercase; /* UPPERCASE */ text-transform: lowercase; /* lowercase */ text-transform: capitalize; /* Capitalize Each Word */ /* Spacing */ letter-spacing: 2px; /* Space between letters */ word-spacing: 5px; /* Space between words */ /* Shadow */ text-shadow: 2px 2px 4px rgba(0,0,0,0.3); } /* Text truncation with ellipsis (...) */ .truncate { white-space: nowrap; /* Prevent wrapping */ overflow: hidden; /* Hide overflow */ text-overflow: ellipsis; /* Show ... */ } /* Multi-line truncation */ .truncate-2-lines { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
🔤 Fonts & Icons
1. Google Fonts (Easiest Method)
Google Fonts provides 1500+ free fonts. Just link and use!
<!-- Step 1: Add link in HTML <head> --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet"> <!-- Multiple weights: 400 (normal), 700 (bold) --> <!-- Multiple fonts separated by &family= -->
/* Step 2: Use in CSS */ body { font-family: 'Roboto', sans-serif; } h1, h2, h3 { font-family: 'Open Sans', sans-serif; font-weight: 600; } /* Popular Google Fonts: - Roboto (clean, modern) - Open Sans (friendly, readable) - Lato (professional) - Montserrat (geometric, headings) - Poppins (rounded, modern) - Inter (UI design) - Playfair Display (elegant, serif) */
💡 How to Get Google Fonts
Visit fonts.google.com → Select fonts → Click "Get embed code" → Copy the <link> tag to your HTML.
2. Custom Fonts (@font-face)
Load your own font files for complete control and offline use.
/* Define custom font */ @font-face { font-family: 'MyCustomFont'; src: url('fonts/mycustomfont.woff2') format('woff2'), url('fonts/mycustomfont.woff') format('woff'); font-weight: normal; font-style: normal; font-display: swap; /* Show fallback while loading */ } /* Define bold version */ @font-face { font-family: 'MyCustomFont'; src: url('fonts/mycustomfont-bold.woff2') format('woff2'); font-weight: bold; font-style: normal; } /* Use the font */ body { font-family: 'MyCustomFont', Arial, sans-serif; } /* Font formats (best to worst support): - woff2 (best compression, modern browsers) - woff (good compression, wide support) - ttf (TrueType, older browsers) - eot (IE only) */
3. Font Awesome Icons
The most popular icon library with 2000+ free icons.
<!-- Step 1: Add CDN link in HTML <head> --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"> <!-- Step 2: Use icons with <i> tag --> <i class="fa-solid fa-house"></i> <!-- Home icon --> <i class="fa-solid fa-user"></i> <!-- User icon --> <i class="fa-solid fa-cart-shopping"></i> <!-- Cart icon --> <i class="fa-solid fa-magnifying-glass"></i> <!-- Search --> <i class="fa-solid fa-bars"></i> <!-- Menu/hamburger --> <i class="fa-solid fa-xmark"></i> <!-- Close X --> <i class="fa-solid fa-check"></i> <!-- Checkmark --> <i class="fa-solid fa-heart"></i> <!-- Heart --> <i class="fa-solid fa-star"></i> <!-- Star --> <i class="fa-solid fa-trash"></i> <!-- Delete --> <i class="fa-solid fa-pen"></i> <!-- Edit --> <i class="fa-solid fa-plus"></i> <!-- Add --> <!-- Brand icons (social media) --> <i class="fa-brands fa-facebook"></i> <i class="fa-brands fa-instagram"></i> <i class="fa-brands fa-twitter"></i> <i class="fa-brands fa-whatsapp"></i> <i class="fa-brands fa-youtube"></i> <i class="fa-brands fa-linkedin"></i> <i class="fa-brands fa-github"></i>
/* Style Font Awesome icons with CSS */ i { font-size: 24px; /* Icon size */ color: #3498db; /* Icon color */ } /* Icon in button */ .btn i { margin-right: 8px; /* Space between icon & text */ } /* Hover effect */ .icon:hover { color: #e74c3c; transform: scale(1.2); } /* Icon sizes (Font Awesome classes) */ fa-xs, fa-sm, fa-lg, fa-xl, fa-2xl /* Spinning icon (for loading) */ <i class="fa-solid fa-spinner fa-spin"></i>
4. Bootstrap Icons
Another popular free icon library with 2000+ icons.
<!-- Add CDN link --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"> <!-- Use icons --> <i class="bi bi-house"></i> <!-- Home --> <i class="bi bi-person"></i> <!-- User --> <i class="bi bi-cart"></i> <!-- Cart --> <i class="bi bi-search"></i> <!-- Search --> <i class="bi bi-list"></i> <!-- Menu --> <i class="bi bi-x-lg"></i> <!-- Close --> <i class="bi bi-check-lg"></i> <!-- Check --> <i class="bi bi-heart-fill"></i> <!-- Heart filled --> <i class="bi bi-star-fill"></i> <!-- Star filled --> <i class="bi bi-trash"></i> <!-- Delete --> <i class="bi bi-pencil"></i> <!-- Edit --> <i class="bi bi-plus-lg"></i> <!-- Add --> <i class="bi bi-arrow-left"></i> <!-- Back arrow --> <i class="bi bi-arrow-right"></i> <!-- Forward arrow --> <!-- Social icons --> <i class="bi bi-facebook"></i> <i class="bi bi-instagram"></i> <i class="bi bi-twitter-x"></i> <i class="bi bi-whatsapp"></i> <i class="bi bi-youtube"></i> <i class="bi bi-linkedin"></i> <i class="bi bi-github"></i>
5. Using Icons in Buttons & Links
<!-- Icon + Text Button --> <button class="btn"> <i class="fa-solid fa-cart-shopping"></i> Add to Cart </button> <!-- Icon-only Button --> <button class="btn-icon"> <i class="fa-solid fa-heart"></i> </button> <!-- Social Links --> <div class="social-links"> <a href="#"><i class="fa-brands fa-facebook"></i></a> <a href="#"><i class="fa-brands fa-instagram"></i></a> <a href="#"><i class="fa-brands fa-twitter"></i></a> </div>
/* Button with icon */ .btn { display: inline-flex; align-items: center; gap: 8px; padding: 12px 24px; background: #3498db; color: white; border: none; border-radius: 8px; cursor: pointer; } /* Icon-only button */ .btn-icon { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; background: #f0f0f0; border: none; cursor: pointer; transition: all 0.3s; } .btn-icon:hover { background: #e74c3c; color: white; } /* Social links */ .social-links { display: flex; gap: 15px; } .social-links a { font-size: 24px; color: #333; transition: color 0.3s, transform 0.3s; } .social-links a:hover { color: #3498db; transform: translateY(-3px); }
6. Other Icon Resources
| Icon Library | Website | Icons | Best For |
|---|---|---|---|
| Font Awesome | fontawesome.com | 2000+ free | General purpose |
| Bootstrap Icons | icons.getbootstrap.com | 2000+ | Bootstrap projects |
| Material Icons | fonts.google.com/icons | 2500+ | Google/Material Design |
| Heroicons | heroicons.com | 450+ | Tailwind CSS |
| Feather Icons | feathericons.com | 280+ | Minimal, clean |
| Remix Icon | remixicon.com | 2800+ | Modern apps |
🎨 CSS Variables (Custom Properties)
💡 Why Use CSS Variables?
CSS Variables let you store values (colors, sizes, etc.) in one place and reuse them everywhere. Change the variable once, and it updates throughout your entire stylesheet!
1. Defining CSS Variables
Variables are defined using -- prefix and accessed using var().
/* Define variables in :root (global scope) */ :root { /* Colors */ --primary-color: #3498db; --secondary-color: #2ecc71; --accent-color: #e74c3c; --text-color: #333333; --text-light: #666666; --bg-color: #ffffff; --bg-secondary: #f5f5f5; /* Spacing */ --spacing-xs: 4px; --spacing-sm: 8px; --spacing-md: 16px; --spacing-lg: 24px; --spacing-xl: 32px; /* Typography */ --font-primary: 'Segoe UI', sans-serif; --font-heading: 'Poppins', sans-serif; --font-size-sm: 0.875rem; --font-size-md: 1rem; --font-size-lg: 1.25rem; --font-size-xl: 1.5rem; /* Border radius */ --radius-sm: 4px; --radius-md: 8px; --radius-lg: 16px; --radius-full: 9999px; /* Shadows */ --shadow-sm: 0 1px 2px rgba(0,0,0,0.1); --shadow-md: 0 4px 6px rgba(0,0,0,0.1); --shadow-lg: 0 10px 25px rgba(0,0,0,0.15); /* Transitions */ --transition-fast: 0.15s ease; --transition-normal: 0.3s ease; --transition-slow: 0.5s ease; }
2. Using CSS Variables
/* Use variables with var() */ body { font-family: var(--font-primary); color: var(--text-color); background: var(--bg-color); } .card { background: var(--bg-color); padding: var(--spacing-lg); border-radius: var(--radius-md); box-shadow: var(--shadow-md); transition: box-shadow var(--transition-normal); } .card:hover { box-shadow: var(--shadow-lg); } .btn-primary { background: var(--primary-color); padding: var(--spacing-sm) var(--spacing-md); border-radius: var(--radius-sm); transition: all var(--transition-fast); } h1, h2, h3 { font-family: var(--font-heading); color: var(--text-color); } /* Fallback value (if variable is undefined) */ .element { color: var(--undefined-var, #333); }
3. Dark Mode with Variables
CSS Variables make implementing dark mode incredibly easy!
/* Light theme (default) */ :root { --bg-color: #ffffff; --bg-secondary: #f5f5f5; --text-color: #333333; --text-light: #666666; --border-color: #e0e0e0; --card-bg: #ffffff; } /* Dark theme */ [data-theme="dark"] { --bg-color: #1a1a2e; --bg-secondary: #16213e; --text-color: #ffffff; --text-light: #a0a0b0; --border-color: #2a2a4a; --card-bg: #0f3460; } /* Auto dark mode (follows system preference) */ @media (prefers-color-scheme: dark) { :root { --bg-color: #1a1a2e; --bg-secondary: #16213e; --text-color: #ffffff; --text-light: #a0a0b0; --border-color: #2a2a4a; --card-bg: #0f3460; } } /* Components automatically adapt! */ body { background: var(--bg-color); color: var(--text-color); } .card { background: var(--card-bg); border: 1px solid var(--border-color); }
<!-- HTML: Toggle dark mode with JavaScript --> <button onclick="toggleTheme()">Toggle Dark Mode</button> <script> function toggleTheme() { const html = document.documentElement; if (html.getAttribute('data-theme') === 'dark') { html.removeAttribute('data-theme'); } else { html.setAttribute('data-theme', 'dark'); } } </script>
4. Variables with calc()
Combine variables with calculations for dynamic values.
:root { --base-size: 16px; --spacing-unit: 8px; --sidebar-width: 250px; } /* Use calc() with variables */ .heading { font-size: calc(var(--base-size) * 2); /* 32px */ } .section { padding: calc(var(--spacing-unit) * 3); /* 24px */ margin-bottom: calc(var(--spacing-unit) * 4); /* 32px */ } .main-content { width: calc(100% - var(--sidebar-width)); margin-left: var(--sidebar-width); } /* Dynamic spacing scale */ :root { --space-1: calc(var(--spacing-unit) * 1); /* 8px */ --space-2: calc(var(--spacing-unit) * 2); /* 16px */ --space-3: calc(var(--spacing-unit) * 3); /* 24px */ --space-4: calc(var(--spacing-unit) * 4); /* 32px */ --space-5: calc(var(--spacing-unit) * 5); /* 40px */ }
5. Component-Level Variables
Override variables for specific components to create variants.
/* Base button with variables */ .btn { --btn-bg: var(--primary-color); --btn-color: #ffffff; --btn-padding: 10px 20px; --btn-radius: var(--radius-md); background: var(--btn-bg); color: var(--btn-color); padding: var(--btn-padding); border-radius: var(--btn-radius); border: none; cursor: pointer; } /* Button variants - just override the variables! */ .btn-secondary { --btn-bg: var(--secondary-color); } .btn-danger { --btn-bg: var(--accent-color); } .btn-outline { --btn-bg: transparent; --btn-color: var(--primary-color); border: 2px solid var(--primary-color); } .btn-small { --btn-padding: 6px 12px; } .btn-large { --btn-padding: 14px 28px; } .btn-rounded { --btn-radius: var(--radius-full); }
6. Complete Variables Example
/* Complete CSS Variables Setup */ :root { /* === COLORS === */ --color-primary: #3498db; --color-primary-dark: #2980b9; --color-secondary: #2ecc71; --color-accent: #e74c3c; --color-warning: #f39c12; --color-text: #333333; --color-text-light: #666666; --color-text-muted: #999999; --color-bg: #ffffff; --color-bg-alt: #f8f9fa; --color-border: #e0e0e0; /* === TYPOGRAPHY === */ --font-sans: 'Inter', -apple-system, sans-serif; --font-serif: 'Georgia', serif; --font-mono: 'Fira Code', monospace; --text-xs: 0.75rem; --text-sm: 0.875rem; --text-base: 1rem; --text-lg: 1.125rem; --text-xl: 1.25rem; --text-2xl: 1.5rem; --text-3xl: 2rem; /* === SPACING === */ --space-1: 0.25rem; --space-2: 0.5rem; --space-3: 0.75rem; --space-4: 1rem; --space-5: 1.5rem; --space-6: 2rem; --space-8: 3rem; /* === BORDERS === */ --radius-sm: 4px; --radius-md: 8px; --radius-lg: 12px; --radius-xl: 16px; --radius-full: 9999px; /* === SHADOWS === */ --shadow-sm: 0 1px 2px rgba(0,0,0,0.05); --shadow-md: 0 4px 6px rgba(0,0,0,0.1); --shadow-lg: 0 10px 15px rgba(0,0,0,0.1); --shadow-xl: 0 20px 25px rgba(0,0,0,0.15); /* === TRANSITIONS === */ --transition-fast: 150ms ease; --transition-base: 300ms ease; --transition-slow: 500ms ease; /* === LAYOUT === */ --container-sm: 640px; --container-md: 768px; --container-lg: 1024px; --container-xl: 1280px; }
📦 Flexbox Layout
💡 When to use Flexbox?
Flexbox is ideal for one-dimensional layouts — arranging items in a single row OR column. Perfect for navigation bars, centering content, or distributing space among items.
1. Flex Direction
Controls the main axis direction — how items flow in the container.
<!-- Flex Row --> <div class="flex-container row"> <div class="box">1</div> <div class="box">2</div> <div class="box">3</div> </div> <!-- Flex Column --> <div class="flex-container column"> <div class="box">1</div> <div class="box">2</div> <div class="box">3</div> </div>
.flex-container { display: flex; gap: 10px; } .flex-container.row { flex-direction: row; /* → horizontal */ } .flex-container.column { flex-direction: column; /* ↓ vertical */ } .box { width: 80px; height: 60px; background: #e94560; border-radius: 8px; }
2. Justify Content (Main Axis)
Aligns items along the main axis (horizontally for row, vertically for column).
.container { display: flex; /* Pack items at the start */ justify-content: flex-start; /* Center items */ justify-content: center; /* Pack items at the end */ justify-content: flex-end; /* Space between items */ justify-content: space-between; /* Equal space around items */ justify-content: space-around; /* Equal space everywhere */ justify-content: space-evenly; }
3. Align Items (Cross Axis)
Aligns items along the cross axis (vertically for row, horizontally for column).
.container { display: flex; height: 120px; /* Need height */ align-items: flex-start; /* Top */ align-items: center; /* Middle */ align-items: flex-end; /* Bottom */ align-items: stretch; /* Fill height */ } /* CENTER ANYTHING (horizontal + vertical) */ .center-content { display: flex; justify-content: center; align-items: center; }
4. Flex Wrap & Flex Grow
/* Flex Wrap */ .container { display: flex; flex-wrap: wrap; /* Allow wrapping */ gap: 10px; } /* Flex Item Properties */ .item { flex-grow: 1; /* Grow to fill */ flex-shrink: 1; /* Can shrink */ flex-basis: 200px; /* Initial size */ /* Shorthand: grow shrink basis */ flex: 1 1 200px; flex: 1; /* flex: 1 1 0 */ }
🔲 CSS Grid Layout
💡 When to use CSS Grid?
Grid is perfect for two-dimensional layouts — controlling both rows AND columns simultaneously. Ideal for page layouts, card grids, dashboards, and complex UI structures.
1. Basic Grid Setup
Create a grid container and define columns. Items automatically flow into cells.
<div class="grid-container"> <div class="box">1</div> <div class="box">2</div> <div class="box">3</div> <div class="box">4</div> <div class="box">5</div> <div class="box">6</div> </div>
.grid-container { display: grid; grid-template-columns: 1fr 1fr 1fr; /* or: repeat(3, 1fr) */ gap: 10px; } /* fr = fractional unit (flexible) Items automatically flow into cells */
2. Grid Template Columns
Define column sizes using various units: px, fr, auto, %, minmax(), etc.
.grid { display: grid; gap: 10px; /* Equal columns */ grid-template-columns: 1fr 1fr 1fr; /* Fixed + flexible */ grid-template-columns: 100px 1fr 2fr; /* Repeat shorthand */ grid-template-columns: repeat(4, 1fr); /* RESPONSIVE auto-fit! */ grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); }
3. Grid Span (Spanning Columns/Rows)
.item { /* Span 2 columns */ grid-column: span 2; /* Span 2 rows */ grid-row: span 2; /* Explicit start/end */ grid-column: 1 / 3; /* col 1 to 3 */ grid-row: 2 / 4; /* row 2 to 4 */ /* Full width */ grid-column: 1 / -1; /* first to last */ }
4. Grid Template Areas
Name grid areas and place items using those names — very intuitive for layouts!
.layout { display: grid; grid-template-columns: 1fr 2fr 1fr; grid-template-rows: auto 1fr auto; grid-template-areas: "header header header" "sidebar main aside" "footer footer footer"; gap: 10px; } .header { grid-area: header; } .sidebar { grid-area: sidebar; } .main { grid-area: main; } .aside { grid-area: aside; } .footer { grid-area: footer; }
📍 CSS Position
💡 What is CSS Position?
The position property controls how an element is positioned in the document. It works with top, right, bottom, and left properties to place elements precisely.
1. Static & Relative Position
top: 20px; left: 30px
Relative box still occupies original space!
/* STATIC (default) */ .static { position: static; /* top/left/right/bottom have NO effect */ } /* RELATIVE - offset from normal position */ .relative { position: relative; top: 20px; /* move down */ left: 30px; /* move right */ } /* Original space is preserved Creates positioning context for children */
2. Absolute Position
Removed from document flow, positioned relative to nearest positioned ancestor.
/* Parent MUST have position set */ .parent { position: relative; } .absolute-child { position: absolute; top: 10px; left: 10px; } /* CENTER an absolute element */ .centered { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
3. Fixed & Sticky Position
Section A content line 1
Section A content line 2
Section A content line 3
Section B content line 1
Section B content line 2
Section B content line 3
/* FIXED - relative to viewport */ .fixed-nav { position: fixed; top: 0; left: 0; right: 0; z-index: 1000; } /* STICKY - scrolls then sticks */ .sticky-header { position: sticky; top: 0; /* stick at top */ z-index: 10; } /* Great for table headers, section headers */
4. Z-Index (Stacking Order)
/* Z-index only works on positioned elements */ .layer-1 { z-index: 1; } .layer-2 { z-index: 2; } .layer-3 { z-index: 3; } /* on top */ /* Common z-index scale: Content: 1-10 Dropdowns: 100 Modals: 1000 Tooltips: 10000 */
static
Default • Normal flow • No offset
relative
Offset from self • Keeps space
absolute
Removed • Relative to parent
fixed
Relative to viewport • Stays on scroll
sticky
Hybrid • Scrolls then sticks
✨ Transitions & Animations
1. CSS Transitions
Smoothly animate property changes on hover, focus, or state changes.
<button class="btn">Hover Me</button> <div class="card"> <h3>Hover Card</h3> <p>This card lifts on hover</p> </div> <input type="text" class="input" placeholder="Focus me">
.btn { background: #3498db; color: white; padding: 12px 24px; border: none; border-radius: 8px; /* Transition: property duration timing */ transition: all 0.3s ease; } .btn:hover { background: #2980b9; transform: translateY(-3px); box-shadow: 0 5px 15px rgba(0,0,0,0.2); } .card { transition: transform 0.3s, box-shadow 0.3s; } .card:hover { transform: translateY(-5px); box-shadow: 0 10px 30px rgba(0,0,0,0.15); } .input:focus { border-color: #3498db; box-shadow: 0 0 0 3px rgba(52,152,219,0.3); } /* Timing: ease, linear, ease-in, ease-out */
2. Keyframe Animations
Create complex, multi-step animations that run automatically.
<!-- Fade in element --> <div class="fade-in">I fade in!</div> <!-- Bouncing element --> <div class="bounce">I bounce!</div> <!-- Loading spinner --> <div class="spinner"></div> <!-- Pulse effect --> <div class="pulse">Pulse</div>
/* Define animations with @keyframes */ @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } } @keyframes bounce { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-15px); } } @keyframes spin { to { transform: rotate(360deg); } } /* Apply animations */ .fade-in { animation: fadeIn 0.5s ease forwards; } .bounce { animation: bounce 1s ease infinite; } .spinner { width: 40px; height: 40px; border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; animation: spin 1s linear infinite; }
3. CSS Transforms
Move, rotate, scale, or skew elements without affecting document flow.
<div class="box translate">Translate</div> <div class="box scale">Scale</div> <div class="box rotate">Rotate</div> <div class="box skew">Skew</div>
/* Translate (move) */ transform: translateX(50px); /* right */ transform: translateY(-20px); /* up */ transform: translate(50px, -20px); /* Scale (resize) */ transform: scale(1.5); /* 150% */ transform: scaleX(2); /* width only */ /* Rotate */ transform: rotate(45deg); transform: rotate(-90deg); /* Skew */ transform: skewX(10deg); transform: skewY(5deg); /* Combine transforms */ transform: translateY(-5px) scale(1.05) rotate(2deg); /* Transform origin */ transform-origin: top left; transform-origin: center center; /* default */
📱 Responsive Design
1. Media Queries
Apply different styles based on screen size using mobile-first approach.
<div class="grid"> <div class="card">Card 1</div> <div class="card">Card 2</div> <div class="card">Card 3</div> <div class="card">Card 4</div> </div> <!-- Add viewport meta in <head> --> <meta name="viewport" content="width=device-width, initial-scale=1.0">
/* Mobile First Approach */ /* Base: Mobile (1 column) */ .grid { display: grid; grid-template-columns: 1fr; gap: 20px; } /* Tablet: 768px+ (2 columns) */ @media (min-width: 768px) { .grid { grid-template-columns: repeat(2, 1fr); } } /* Desktop: 1024px+ (3 columns) */ @media (min-width: 1024px) { .grid { grid-template-columns: repeat(3, 1fr); } } /* Large: 1200px+ (4 columns) */ @media (min-width: 1200px) { .grid { grid-template-columns: repeat(4, 1fr); } }
| Device | Width |
|---|---|
| Mobile | < 768px |
| Tablet | 768px+ |
| Desktop | 1024px+ |
| Large | 1200px+ |
2. Special Media Queries
<!-- Dark mode toggle --> <body class="theme-auto"> <div class="card"> This card adapts to system dark mode! </div> </body> <!-- Print-only content --> <button class="no-print">Print</button> <div class="print-only">Printed on...</div>
/* Auto dark mode (system preference) */ @media (prefers-color-scheme: dark) { :root { --bg: #1a1a1a; --text: #ffffff; } } /* Respect reduced motion */ @media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } } /* Hover only on devices that support it */ @media (hover: hover) { .card:hover { transform: scale(1.02); } } /* Print styles */ @media print { .no-print { display: none; } .print-only { display: block; } body { font-size: 12pt; color: black; } }
prefers-color-scheme: dark - Dark mode
prefers-reduced-motion - Accessibility
hover: hover - Touch vs mouse
print - Print stylesheet
3. Responsive Best Practices
<!-- Responsive image --> <img src="photo.jpg" alt="Photo" class="responsive-img"> <!-- Fluid typography heading --> <h1 class="fluid-heading">Responsive Title</h1> <!-- Auto-fit grid (no media queries!) --> <div class="auto-grid"> <div class="card">Card 1</div> <div class="card">Card 2</div> <div class="card">Card 3</div> <div class="card">Card 4</div> </div> <!-- Centered container --> <div class="container"> Content here... </div>
/* Fluid images */ .responsive-img { max-width: 100%; height: auto; } /* Fluid typography with clamp() */ .fluid-heading { /* clamp(min, preferred, max) */ font-size: clamp(1.5rem, 4vw, 3rem); } /* Auto-fit grid - NO media queries! */ .auto-grid { display: grid; grid-template-columns: repeat( auto-fit, minmax(250px, 1fr) ); gap: 20px; } /* Centered container */ .container { width: 100%; max-width: 1200px; margin: 0 auto; padding: 0 20px; }
✓ max-width: 100% for images
✓ clamp() for fluid typography
✓ auto-fit + minmax() for grids
✓ rem units for spacing
✓ Mobile-first with min-width
🎉 Congratulations!
You've covered all the essential CSS concepts! Practice by building real projects — that's the best way to master CSS. Good luck with your learning journey!