Cascading Style Sheets(CSS) for Beginners
By Himanshu Shekhar , 04 Jan 2022
Introduction to CSS β Cascading Style Sheets
CSS (Cascading Style Sheets) is the language that styles HTML β it defines how web pages look: layout, colors, fonts, spacing and responsive behaviour. In this beginner-friendly module from NotesTime.in, youβll learn what CSS is, how it works with HTML, basic syntax, ways to include styles, and best-practice commenting. Perfect for beginners, front-end learners, and anyone preparing simple UI projects.
1. What is CSS?
CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of HTML documents. While HTML provides structure and content, CSS controls the visual appearance β colors, fonts, spacing, alignment, and more.
Think of HTML as the bones of a webpage and CSS as the clothes and makeup that make it look great. π¨
- Separates content (HTML) from presentation (CSS).
- Reuse styles across multiple pages.
- Easier maintenance and faster styling changes.
Quick Examples
Change text color and font-size using CSS:
<p class="lead">Hello world</p>
2. How CSS Works
CSS works by selecting HTML elements and applying style rules to them. A CSS rule typically consists of a selector and a declaration block.
| Part | Example | What it does |
|---|---|---|
| Selector | h1, .btn, #main |
Targets HTML elements to style |
| Property | color, margin, display |
The style attribute you want to change |
| Value | #ff0000, 20px, block |
What the property should be set to |
CSS Rule Example
/* selector */ body {
/* declaration block */
margin: 0;
font-family: 'Inter', sans-serif;
color: #333;
}
3. CSS Syntax & Structure
A CSS rule set looks like selector { property: value; }. Multiple properties go inside the curly braces separated by semicolons.
CSS supports comments, shorthand properties, and grouping of selectors for cleaner code.
- Selector: element, class (
.card), id (#sidebar), attribute, pseudo-class etc. - Declaration: property + value pair (e.g.,
padding: 16px;). - At-rules: special rules like
@media,@keyframes,@import.
margin: 10px 20px; or border: 1px solid #ddd;) which reduces code and improves readability.
Grouping Selectors
h1, h2, h3 {
margin-bottom: 0.5rem;
font-weight: 600;
}
4. Inline, Internal & External CSS
There are three basic ways to add CSS to an HTML document. Each has use-cases and trade-offs.
| Method | How | When to use | Pros / Cons |
|---|---|---|---|
| Inline | <div style="color: red;"> |
Quick one-off tweaks | + Immediate. β Not reusable; poor separation of concerns |
| Internal (Embedded) | <style>...</style> inside <head> |
Page-specific styles or demos | + Easy for single page. β Not reusable across pages |
| External | <link rel="stylesheet" href="styles.css"> |
Recommended for production, multiple pages | + Reusable & cacheable. β Extra HTTP request (often worth it) |
Examples
<button style="background:#0d6efd;color:#fff;padding:8px 12px">Click</button>
<head>
<style>
.card { padding: 16px; border-radius: 8px; }
</style>
</head>
<link rel="stylesheet" href="css/styles.css">
5. CSS Comments
Comments help document your CSS and are ignored by the browser. Use them to explain complex rules, mark sections, or temporarily disable code.
/* This is a comment */
Good Commenting Habits
- π Use section headers (e.g.,
/* Header / Navigation */). - π Explain the "why" not the "what" when the code is self-explanatory.
- β»οΈ Remove outdated comments β stale comments confuse future maintainers.
/* Buttons
--------------------------------------------- */
.btn {
display: inline-block;
padding: 10px 14px;
border-radius: 6px;
}
/* Large primary button */
.btn-primary {
background: #0d6efd;
color: #fff;
}
CSS Selectors β Targeting HTML Elements Effectively
CSS Selectors help you choose which HTML elements you want to style. They are the foundation of CSS because every style rule begins by selecting one or more elements. In this module from NotesTime.in, youβll learn all types of selectors β basic, attribute, combinators, pseudo-classes, pseudo-elements, and specificity rules.
2.1 Basic Selectors
Basic selectors are the simplest and most frequently used selectors in CSS. They target HTML elements using names, classes, IDs, and universal patterns.
| Selector | Example | Description |
|---|---|---|
| Element Selector | p { ... } |
Selects all <p> tags |
| Class Selector | .title { ... } |
Selects elements with class="title" |
| ID Selector | #header { ... } |
Selects the element with id="header" |
| Universal Selector | * { ... } |
Selects all elements |
| Grouping Selector | h1, h2, h3 { ... } |
Styles multiple selectors together |
.class selectors over #id to keep your CSS flexible and reusable.
Example
/* Basic selectors */
h1 { color: #333; }
.title { font-size: 20px; }
#main { padding: 20px; }
2.2 Attribute Selectors
Attribute selectors allow you to style elements based on their attributes and values. Useful for forms, links, inputs, and custom components.
| Selector | Example | Matches |
|---|---|---|
| [attr] | input[required] |
Elements with a required attribute |
| [attr="value"] | a[target="_blank"] |
Exact value match |
| [attr^="value"] | img[src^="https"] |
Starts with ("^") |
| [attr$="value"] | a[href$=".pdf"] |
Ends with ("$") |
| [attr*="value"] | div[class*="box"] |
Contains ("*") |
a[target="_blank"].
a[target="_blank"] {
color: #d63384;
text-decoration: underline;
}
2.3 Combinators
Combinators style elements based on their relationships in the HTML structure. This gives you precise control over nested layouts.
| Combinator | Symbol | Meaning | Example |
|---|---|---|---|
| Descendant | (space) | Selects all nested children | div p |
| Child | > | Selects direct children | ul > li |
| Adjacent Sibling | + | Selects the next sibling | h1 + p |
| General Sibling | ~ | Selects all following siblings | p ~ span |
div p) can slow down CSS in large pages.
Example
/* Only direct children */
ul > li { margin-bottom: 10px; }
2.4 Pseudo-Classes
Pseudo-classes allow you to style elements based on states, positions, user interactions, and more.
| Pseudo-Class | Example | Use Case |
|---|---|---|
:hover |
a:hover |
When user hovers |
:focus |
input:focus |
When element is focused |
:active |
button:active |
While clicking |
:first-child |
li:first-child |
First element in parent |
:nth-child() |
tr:nth-child(odd) |
Table striping |
a:hover {
color: #0d6efd;
}
2.5 Pseudo-Elements
Pseudo-elements style specific parts of an element such as the first letter, first line, or generate content using ::before and ::after.
| Pseudo-Element | Usage |
|---|---|
::before |
Add content before element |
::after |
Add content after element |
::first-letter |
Style the first letter |
::first-line |
Style the first line |
::selection |
Style text selection |
.title::before {
content: "π ";
color: #198754;
}
2.6 CSS Specificity
Specificity determines which CSS rule wins when multiple selectors target the same element. It follows a scoring system where some selectors are stronger than others.
| Selector Type | Specificity Score | Strength |
|---|---|---|
| Inline Styles | 1000 | π₯ Very High |
IDs (#id) |
100 | High |
Classes (.class), attributes |
10 | Medium |
Elements (h1, p) |
1 | Low |
| Universal (*) | 0 | Very Low |
/* Specificity battle */
#title { color: red; } /* wins */
.title { color: blue; }
h1 { color: green; }
Colors, Backgrounds & Borders in CSS
Colors, backgrounds, and borders are essential for creating visually appealing web pages. In this module from NotesTime.in, youβll learn all modern color formats, background techniques, image controls, and border styling methods used by developers worldwide.
3.1 Color Models (HEX, RGB, HSL)
CSS provides multiple ways to define colors. Each model has its advantages depending on design needs.
| Color Format | Example | Description |
|---|---|---|
| HEX | #ff5733 |
Hexadecimal values (most common for web) |
| RGB | rgb(255, 87, 51) |
Red, Green, Blue β ideal for digital screens |
| RGBA | rgba(255, 87, 51, 0.5) |
RGB + Alpha (transparency) |
| HSL | hsl(14, 100%, 60%) |
Hue, Saturation & Lightness β easy for designers |
| HSLA | hsla(14, 100%, 60%, 0.5) |
HSL + Alpha transparency |
/* Examples */
h1 { color: #3498db; }
p { color: rgb(80, 80, 80); }
.box { background-color: hsla(200, 50%, 50%, 0.5); }
3.2 Background Images
CSS allows you to set any image as the background of an element using background-image.
.hero {
background-image: url("banner.jpg");
}
Common Background Properties
background-imageβ sets the imagebackground-repeatβ repeat, no-repeat, repeat-x, repeat-ybackground-sizeβ contain, cover, auto, custombackground-positionβ center, top, left, coordinatesbackground-attachmentβ scroll, fixed (parallax effect)
background-size: cover; for hero sections that fill full width beautifully.
.hero {
background-image: url("hero.jpg");
background-size: cover;
background-position: center;
}
3.3 Background Positioning
Controls where the background image appears in an element.
| Position | Example | Meaning |
|---|---|---|
| center | background-position: center; |
Centers the image |
| top left | background-position: top left; |
Aligns image to top-left corner |
| x y values | background-position: 50px 20px; |
Custom pixel positioning |
| % percentage | background-position: 50% 50%; |
Full responsive control |
.banner {
background-position: center center;
}
3.4 Borders & Outline
Borders visually separate elements, while outlines highlight elements (mainly for focus).
Border Properties
border-widthborder-styleβ solid, dashed, dotted, double, grooveborder-colorborder-radiusβ rounded corners
.card {
border: 2px solid #222;
border-radius: 10px;
}
Outline vs Border
| Border | Outline |
|---|---|
| Part of elementβs dimensions | Does NOT affect layout |
| Can have radius | No radius |
| More commonly used for UI | Often used for accessibility |
input:focus {
outline: 2px solid #0d6efd;
}
3.5 Gradients
CSS gradients allow smooth transitions between two or more colors β without using images.
Types of Gradients
- Linear Gradient
- Radial Gradient
- Conic Gradient
Examples
/* Linear gradient */
.box1 {
background: linear-gradient(to right, #ff9a9e, #fad0c4);
}
/* Radial gradient */
.box2 {
background: radial-gradient(circle, #a18cd1, #fbc2eb);
}
/* Conic gradient */
.box3 {
background: conic-gradient(from 0deg, red, yellow, green, blue, red);
}
CSS Box Model β Margin, Padding, Borders & Box-Sizing
Everything in CSS is a box β text, buttons, images, forms, containers, and layout sections. The CSS Box Model controls how much space an element occupies, how far it stays from other elements, and how content sits inside it. Mastering the Box Model is essential for layout, spacing, UI design, and responsive websites.
4.1 Margin β Outside Spacing
The margin is the space outside an element. It creates distance between two elements.
Margin Syntax
margin: 20px; /* all sides */
margin: 10px 20px; /* top-bottom | left-right */
margin: 5px 10px 15px 20px; /* top | right | bottom | left */
| Property | Meaning |
|---|---|
margin-top |
Space above the element |
margin-right |
Space on the right |
margin-bottom |
Space below |
margin-left |
Space on the left |
margin: auto; to center block-level elements.
.container {
width: 500px;
margin: auto;
}
4.2 Padding β Inside Spacing
Padding is the space between the content and the border. It increases the clickable area and improves readability.
Padding Syntax
padding: 20px;
padding: 10px 20px;
padding: 5px 10px 15px 20px;
| Property | Meaning |
|---|---|
padding-top |
Space inside at the top |
padding-right |
Space inside on the right |
padding-bottom |
Space inside at the bottom |
padding-left |
Space inside on the left |
.btn {
padding: 12px 25px;
border-radius: 6px;
}
4.3 Border Types
Borders surround elements and can be styled to match the UI design.
Border Syntax
border: 2px solid #333;
Border Styles
soliddasheddotteddoublegrooveridgeinsetoutset
Border Radius
border-radius: 10px; /* rounded corners */
border-radius: 50%; /* perfect circle */
4.4 Content Box vs Border Box
The box-sizing property controls how width & height are calculated.
| Box-Sizing | What width includes? |
|---|---|
| content-box (default) | ONLY content (padding & border added later) |
| border-box | Content + padding + border inside the width |
/* Common practice */
* {
box-sizing: border-box;
}
border-box for responsive layouts β easier sizing!
4.5 Box Shadow
The box-shadow property adds shadow around elements to create depth, elevation, and modern UI design.
Syntax
box-shadow: offsetX offsetY blur spread color;
| Part | Meaning |
|---|---|
| offset-x | Horizontal shadow direction |
| offset-y | Vertical shadow direction |
| blur | Softness of the shadow |
| spread | How far shadow expands |
| color | Shadow color |
.card {
box-shadow: 0 4px 10px rgba(0,0,0,0.2);
}
rgba) for clean, modern card designs.
CSS Units & Measurements
CSS provides a variety of units to size elements, text, spacing, and layouts. Understanding units like px, %, em, rem, vh, vw and functions like calc() is essential for responsive and modern web design.
5.1 px, %, em, rem
CSS units are divided into two categories: absolute units and relative units.
π Absolute Unit: px
px (pixels) is a fixed-size unit. It does NOT scale with screen size.
h1 {
font-size: 32px;
}
π Relative Unit: % (Percentage)
% is relative to the parent elementβs size.
.box {
width: 50%; /* half of parent width */
}
π Relative Unit: em
em is relative to the parent elementβs font-size.
| Parent Font Size | Value Used | Result |
|---|---|---|
| 16px | 2em |
32px |
| 20px | 1.5em |
30px |
.text {
font-size: 1.5em;
}
π Relative Unit: rem
rem (root em) is relative to the HTML root font-size. More predictable than em.
html { font-size: 16px; }
p {
font-size: 1.25rem; /* 20px */
}
5.2 Viewport Units (vh, vw)
Viewport units scale according to the user's screen size, making them ideal for responsive layouts.
| Unit | Meaning |
|---|---|
| 1vh | 1% of the viewport height |
| 1vw | 1% of the viewport width |
| vmin | Minimum of vh and vw |
| vmax | Maximum of vh and vw |
.hero {
height: 100vh; /* full screen height */
width: 100vw; /* full screen width */
}
5.3 Calc() β Calculations in CSS
calc() allows mathematical operations directly inside CSS. You can combine different units like px, %, rem, vh, and more.
Syntax
width: calc(100% - 50px);
Examples
.sidebar {
width: calc(25% + 50px);
}
.box {
height: calc(100vh - 80px);
}
.text {
font-size: calc(1rem + 2px);
}
calc() for dynamic layouts where fixed and flexible units must work together.
CSS Typography β Fonts, Weights, Spacing & Text Styling
Typography plays a crucial role in web design and user experience. CSS gives powerful control over fonts, readability, spacing, alignment, and text decorations. In this module, you'll learn how to style text professionally using industry-level techniques.
6.1 Fonts & Font-Family
The font-family property sets the typeface for text. You can use web-safe fonts, custom fonts, or Google Fonts.
Syntax
font-family: "Poppins", Arial, sans-serif;
| Font Type | Examples |
|---|---|
| Sans-serif | Poppins, Arial, Helvetica |
| Serif | Times New Roman, Georgia |
| Monospace | Courier New, Consolas |
| Display Fonts | Impact, Bebas Neue |
6.2 Font Weight & Style
The font-weight and font-style properties help control thickness and emphasis.
Font Weight
font-weight: 100;β Thinfont-weight: 400;β Normalfont-weight: 600;β Semi-Boldfont-weight: 700;β Boldfont-weight: 900;β Extra Bold
Font Style
font-style: italic;
6.3 Line Height & Letter Spacing
Spacing improves readability and visual comfort in text blocks.
Line Height
Controls vertical spacing between lines of text.
line-height: 1.5; /* 150% of font-size */
| Font Size | Line Height | Spacing |
|---|---|---|
| 16px | 1.5 | 24px |
| 18px | 1.8 | 32.4px |
Letter Spacing
Controls horizontal spacing between characters.
letter-spacing: 1px;
6.4 Text Alignment & Decoration
These properties help control structure and enhance text presentation.
Text Alignment
text-align: left;text-align: right;text-align: center;text-align: justify;
Text Decoration
text-decoration: underline;text-decoration: line-through;text-decoration: overline;text-decoration-color: red;
a {
text-decoration: none;
color: #0d6efd;
}
6.5 Google Fonts
Google Fonts provides hundreds of free, high-quality fonts that you can import into your project.
How to Import Google Fonts
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
Using the Font
body {
font-family: "Poppins", sans-serif;
}
CSS Positioning β Control Element Placement with Precision
CSS Positioning allows you to control exactly where elements appear on a webpage. With different position types like static, relative, absolute, fixed, and sticky, you can create modern layouts, floating boxes, sticky headers, tooltips, popups, and more.
7.1 Static, Relative, Absolute
πΉ 1. Static Position (Default)
All HTML elements are static by default. Static elements follow normal page flow β meaning they canβt be moved using top, left, right or bottom.
div {
position: static;
}
πΉ 2. Relative Position
A relative element stays in the normal flow but can be moved relative to its original position.
div {
position: relative;
top: 10px;
left: 20px;
}
- β The element moves, but space remains preserved.
- β Used for creating tooltips, badges, or as a parent for absolute elements.
position: relative; on a parent
when placing absolute child elements.
πΉ 3. Absolute Position
An absolute element is removed from the normal flow and positioned relative to the nearest positioned parent (relative, absolute, or fixed).
div {
position: absolute;
top: 20px;
right: 10px;
}
- β Does NOT take up space.
- β Perfect for modals, floating icons, labels, tooltips.
7.2 Fixed & Sticky
πΉ 1. Fixed Position
A fixed element stays in the same place even when scrolling. It is positioned relative to the viewport.
nav {
position: fixed;
top: 0;
width: 100%;
}
- β Used for sticky navbars
- β Used for back-to-top buttons
- β Does not move during scroll
position: fixed.
πΉ 2. Sticky Position
Sticky is a hybrid between relative and fixed. It acts relative until scroll reaches a threshold, then becomes fixed.
header {
position: sticky;
top: 0;
}
- β Great for table headers
- β Section titles in long pages
- β Sticky sidebars
7.3 Z-Index
z-index controls which element appears in front when elements overlap. Higher value β element appears on top.
Syntax
div {
position: absolute;
z-index: 10;
}
Rules of Z-index
- β Works only on positioned elements (not static)
- β Higher number = higher stacking priority
- β Negative values send elements behind
| z-index Value | Meaning |
|---|---|
| -1 | Behind everything |
| 1 | Default stacking |
| 999 | Used for popups / modals |
| 9999 | Used for overlays |
Mastering CSS Flexbox β The Modern Layout System
Flexbox (Flexible Box Layout) is a powerful CSS layout system designed for one-dimensional layouts β either rows or columns. It makes alignment, spacing, and distribution of elements simpler and more responsive compared to traditional methods like floats or inline-block.
8.1 Flex Container Properties
To use Flexbox, you must assign display: flex; to the parent container.
The direct children automatically become flex items.
.container {
display: flex;
}
πΉ 1. flex-direction
Defines the direction of items inside the container.
.container {
flex-direction: row | row-reverse | column | column-reverse;
}
| Value | Description |
|---|---|
| row | Items placed left to right (default) |
| column | Items placed top to bottom |
| row-reverse | Items reversed horizontally |
| column-reverse | Items reversed vertically |
πΉ 2. justify-content
Controls spacing along the main axis.
.container {
justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
}
- β Center items horizontally
- β Perfect for navbars or equal spacing layouts
space-between for menus where
first item sticks left and last item sticks right.
πΉ 3. align-items
Controls alignment along the cross axis (vertical if row direction).
.container {
align-items: stretch | flex-start | flex-end | center | baseline;
}
πΉ 4. flex-wrap
Decides whether items wrap to a new line.
.container {
flex-wrap: nowrap | wrap | wrap-reverse;
}
πΉ 5. gap (Flex Gap)
Adds spacing between flex items (no margin needed!).
.container {
gap: 20px;
}
πΉ 6. align-content
Used when items wrap (multi-line). Controls vertical spacing between rows.
.container {
align-content: center | space-between | space-around | stretch;
}
flex-wrap creates multiple rows.
8.2 Flex Item Properties
πΉ 1. order
Changes the sequence of items without editing HTML.
.item {
order: 2;
}
order may confuse screen readers β use wisely.
πΉ 2. flex-grow
Defines how much an item expands to fill extra space.
.item {
flex-grow: 1;
}
- β 1 = expand equally
- β 0 = no expansion (default)
πΉ 3. flex-shrink
Controls how items shrink when space is limited.
.item {
flex-shrink: 0;
}
πΉ 4. flex-basis
Defines the starting width/height of the item.
.item {
flex-basis: 200px;
}
πΉ 5. flex (Shorthand)
flex = grow shrink basis
.item {
flex: 1 1 150px;
}
πΉ 6. align-self
Overrides align-items for a single item only.
.item {
align-self: center;
}
8.3 Flexbox Layout Examples
πΉ Example 1: Center Anything (Horizontally + Vertically)
.container {
display: flex;
justify-content: center;
align-items: center;
}
πΉ Example 2: Responsive Card Layout
.cards {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 1 1 250px;
background: #f8f9fa;
padding: 20px;
border-radius: 10px;
}
- β Cards wrap on smaller screens
- β Equal spacing via
gap
πΉ Example 3: Navbar Using Flexbox
nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px;
}
CSS Grid β The Ultimate 2D Layout System
CSS Grid is a modern and powerful two-dimensional layout system used to create complex, responsive web designs. Unlike Flexbox (which works in one direction), Grid allows you to design layouts in both rows and columns simultaneously β perfect for full-page layouts, dashboards, galleries, and more.
9.1 Grid Container
To use CSS Grid, set the parent element to:
.grid-container {
display: grid;
}
πΉ grid-template-columns
Defines the number and width of columns.
.grid-container {
grid-template-columns: 200px 200px 200px; /* 3 fixed columns */
}
Using repeat():
.grid-container {
grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
}
πΉ grid-template-rows
Defines the height of each row.
.grid-container {
grid-template-rows: 100px 200px auto;
}
πΉ gap (Row & Column Gap)
Adds spacing between grid items:
.grid-container {
gap: 20px; /* row & column gap */
row-gap: 15px; /* only row gap */
column-gap: 30px; /* only column gap */
}
9.2 Grid Template
πΉ 1. Defining both rows & columns
.grid-container {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: 100px auto 150px;
}
πΉ 2. auto-fit & auto-fill (Responsive Grids)
These automatically create responsive columns that wrap based on screen width.
.grid-container {
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
πΉ 3. minmax()
Sets minimum and maximum size of a grid track.
.grid-container {
grid-template-columns: repeat(3, minmax(150px, 1fr));
}
πΉ 4. Implicit vs Explicit Grid
- Explicit Grid: Defined by
grid-template-rows&grid-template-columns - Implicit Grid: Auto-created when items overflow the defined tracks
.grid-container {
grid-auto-rows: 100px;
grid-auto-columns: 200px;
}
9.3 Grid Areas
Grid Areas allow you to assign names to parts of the layout and arrange elements visually like a wireframe β super powerful for complex designs.
πΉ Step 1: Define Grid Areas in Container
.grid-container {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
grid-template-columns: 200px 1fr 1fr;
gap: 20px;
}
πΉ Step 2: Assign Elements to Areas
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
πΉ Visual Example (Text-based Diagram)
| HEADER | HEADER | HEADER | | SIDEBAR | MAIN | MAIN | | FOOTER | FOOTER | FOOTER |
9.4 Responsive Grid
CSS Grid becomes incredibly powerful when combined with responsive units and breakpoints.
πΉ Example: Auto-Responsive Gallery
.gallery {
display: grid;
gap: 20px;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
πΉ Example: Grid with Media Queries
.grid-layout {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
@media (max-width: 768px) {
.grid-layout {
grid-template-columns: 1fr 1fr;
}
}
@media (max-width: 480px) {
.grid-layout {
grid-template-columns: 1fr;
}
}
CSS Animations β Bringing Your Webpages to Life
CSS Animations allow you to add smooth movement, transitions, and interactive effects without JavaScript. You can animate colors, positions, size, rotation, opacity, and more. This module covers transitions, transforms, keyframes, and advanced animation tricks with practical examples.
10.1 Transitions
Transitions allow you to animate changes smoothly when a property changes (like on hover, click, or focus).
πΉ Basic Syntax:
transition: property duration timing-function delay;
Example:
.box {
background: blue;
transition: background 0.5s ease;
}
.box:hover {
background: red;
}
πΉ Common transition properties:
transition-propertytransition-durationtransition-delaytransition-timing-function
πΉ Timing Functions
Control how animations accelerate or slow down:
ease
linear
ease-in
ease-out
ease-in-out
cubic-bezier(0.42, 0, 0.58, 1)
10.2 Transform
The transform property lets you move, scale, rotate, or skew elements.
πΉ Move (translate)
.box:hover {
transform: translateX(50px);
}
πΉ Scale
.box:hover {
transform: scale(1.3);
}
πΉ Rotate
.box:hover {
transform: rotate(45deg);
}
πΉ Skew
.box:hover {
transform: skewX(20deg);
}
Combined Transform Example:
.box:hover {
transform: translateY(20px) rotate(20deg) scale(1.1);
}
10.3 Keyframes
Keyframes allow you to create multi-step animations that run automatically.
πΉ Basic Keyframe Structure
@keyframes moveBox {
from { transform: translateX(0); }
to { transform: translateX(200px); }
}
.box {
animation: moveBox 2s ease-in-out;
}
πΉ Using % Stages
@keyframes bounce {
0% { transform: translateY(0); }
50% { transform: translateY(-50px); }
100% { transform: translateY(0); }
}
πΉ Animation Properties
animation-nameanimation-durationanimation-timing-functionanimation-delayanimation-iteration-count(1, infinite)animation-direction(normal, reverse, alternate)animation-fill-mode(forwards, backwards, both)
πΉ Example: Looping Animation
.loading {
animation: spin 1s linear infinite;
}
@keyframes spin {
100% { transform: rotate(360deg); }
}
10.4 Advanced Animation Tricks
π₯ 1. Animation Delay with Staggering
.item:nth-child(1) { animation-delay: 0s; }
.item:nth-child(2) { animation-delay: 0.2s; }
.item:nth-child(3) { animation-delay: 0.4s; }
π₯ 2. Fade-In Animation
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.box {
animation: fadeIn 1.5s ease;
}
π₯ 3. Hover Triggered Animation
.card:hover .image {
animation: zoom 0.5s ease;
}
@keyframes zoom {
0% { transform: scale(1); }
100% { transform: scale(1.2); }
}
π₯ 4. Smooth Slide-In Animation
@keyframes slideIn {
0% { transform: translateX(-100%); opacity: 0; }
100% { transform: translateX(0); opacity: 1; }
}
.panel {
animation: slideIn 1s ease-out forwards;
}
π₯ 5. Button Ripple Effect (Pure CSS)
@keyframes ripple {
0% { transform: scale(0); opacity: 0.5; }
100% { transform: scale(2); opacity: 0; }
}
button:active::after {
animation: ripple 0.5s ease-out;
}
Responsive Design β Making Websites Look Great on Any Device
Responsive Design ensures your website automatically adjusts to different screen sizes including mobiles, tablets, laptops, and large desktops. Instead of creating separate sites for each device, you build one layout that adapts, scales, and reorganizes based on the screen width.
11.1 Media Queries
Media Queries are the backbone of responsive design. They apply CSS rules only when certain conditions (like screen width) are met.
πΉ Basic Syntax
@media (condition) {
/* CSS rules */
}
πΉ Example: Change Background on Small Screens
@media (max-width: 600px) {
body {
background: lightblue;
}
}
πΉ Common Media Query Types
- π
max-widthβ Styles for smaller screens - π
min-widthβ Styles for larger screens - π
orientationβ portrait or landscape (mobile/tablet) - π₯οΈ
resolutionβ useful for retina displays
πΉ Example: Orientation Based Styles
@media (orientation: landscape) {
.image {
height: 200px;
}
}
11.2 Mobile-First Design
Mobile-first means you write styles for small screens first,
then scale up for larger screens using min-width media queries.
πΉ Example: Mobile-First Button
Base Style (Mobile):
.btn {
padding: 10px;
font-size: 14px;
}
Tablet Upwards (β₯768px):
@media (min-width: 768px) {
.btn {
padding: 15px;
font-size: 16px;
}
}
Desktop Upwards (β₯1024px):
@media (min-width: 1024px) {
.btn {
padding: 18px;
font-size: 18px;
}
}
πΉ Common Breakpoints (Industry Standard)
| Device Type | Width |
|---|---|
| Small Phones | <576px |
| Mobile | 576px β 767px |
| Tablet | 768px β 991px |
| Laptop | 992px β 1199px |
| Desktop / TV | β₯1200px |
11.3 Breakpoints
Breakpoints are specific screen widths at which the layout changes to maintain a good user experience.
πΉ Example: Responsive Grid with Breakpoints
.cards {
display: grid;
grid-template-columns: 1fr;
gap: 20px;
}
/* Tablet */
@media (min-width: 768px) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}
/* Desktop */
@media (min-width: 1024px) {
.cards {
grid-template-columns: repeat(3, 1fr);
}
}
πΉ Example: Navigation Menu Breakpoint
@media (max-width: 768px) {
nav ul {
display: none;
}
.menu-icon {
display: block;
}
}
CSS Variables β Reusable, Powerful & Modern Styling
CSS Variables (also called Custom Properties) allow you to store values like colors, spacing, fonts, or sizes in a reusable way. They make your CSS more organized, scalable, and easier to maintain β especially for large projects.
12.1 Using Variables
πΉ Syntax
:root {
--primary-color: #3498db;
--padding-size: 20px;
}
Using the variable:
button {
background: var(--primary-color);
padding: var(--padding-size);
}
πΉ Why :root?
:root represents the top-level element (html).
Declaring variables here makes them global and accessible from anywhere.
:root.
πΉ Example: Global Design System
:root {
--heading-font: "Poppins", sans-serif;
--text-color: #333;
--border-radius: 10px;
--transition-fast: 0.2s;
}
12.2 Global & Local Variables
πΉ Global Variables
Defined in :root and accessible everywhere.
:root {
--global-bg: #f5f5f5;
}
πΉ Local Variables
Variables defined inside a selector apply only to that element and its children.
.card {
--card-padding: 25px;
padding: var(--card-padding);
}
πΉ Example: Parent-Child Behavior
.theme-dark {
--text-color: #fff;
}
.theme-light {
--text-color: #333;
}
p {
color: var(--text-color);
}
12.3 Theming With Variables
CSS variables make it extremely easy to switch between themes like Light Mode and Dark Mode β with just a single class toggle.
πΉ Example: Light & Dark Theme
Base Colors:
:root {
--bg: #ffffff;
--text: #222;
}
Dark Theme:
.dark {
--bg: #1e1e1e;
--text: #f1f1f1;
}
Using Variables:
body {
background: var(--bg);
color: var(--text);
transition: background 0.3s, color 0.3s;
}
.dark class with JS.
πΉ Theming Buttons
:root {
--btn-bg: #3498db;
--btn-text: #fff;
}
.dark {
--btn-bg: #555;
--btn-text: #eee;
}
button {
background: var(--btn-bg);
color: var(--btn-text);
}
πΉ Dynamic Variables (Updated with JavaScript)
document.documentElement.style.setProperty('--primary-color', '#ff5733');
CSS Frameworks β Faster, Cleaner & Responsive UI Development
CSS Frameworks provide pre-written styles, grid systems, UI components, and utility classes that allow developers to build modern layouts faster. Instead of writing everything from scratch, you can use ready-made buttons, grids, forms, and typography.
13.1 Bootstrap
Bootstrap is the worldβs most popular CSS (and JS) framework. It offers a powerful grid system, ready-made UI components, utilities, and responsive design defaults.
πΉ Key Features
- 12-column responsive grid system
- Ready-made components like navbar, cards, modals
- Utility classes for spacing, display, colors
- Mobile-first and responsive
- Easy to customize themes
πΉ Basic Bootstrap CDN Setup
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
πΉ Example: Bootstrap Button
<button class="btn btn-primary">Click Me</button>
13.2 Tailwind CSS
Tailwind CSS is a modern βutility-firstβ framework.
Instead of prebuilt components, it provides utility classes like p-4,
text-center, bg-blue-500 to build custom designs rapidly.
πΉ Key Features
- Highly customizable with config file
- No need to write custom CSS for spacing/colors
- Responsive utilities built-in (
md:,lg:, etc.) - Fast UI development
- Great for modern, minimal, custom UI design
πΉ Tailwind CDN Setup
<script src="https://cdn.tailwindcss.com"></script>
πΉ Example: Tailwind Button
<button class="px-4 py-2 bg-blue-600 text-white rounded-lg">
Click Me
</button>
πΉ Bootstrap vs Tailwind (Quick Comparison)
| Feature | Bootstrap | Tailwind |
|---|---|---|
| Design Style | Predefined components | Utility-based custom design |
| Learning Curve | Easy | Moderate |
| Customization | Limited (with overrides) | Very high (flexible) |
| Best Use Cases | Dashboards, Admin UX | Modern websites, custom UI |
13.3 Material UI (MUI)
Material UI (MUI) is a React-based CSS framework built on Googleβs Material Design principles. It includes professional components such as cards, menus, dialogs, tables, navigation bars, and more.
πΉ Key Features
- Fully styled professional UI components
- Dark mode support built in
- Highly customizable themes
- Built for React applications
- Supports modern animations & transitions
πΉ Installation (React)
npm install @mui/material @emotion/react @emotion/styled
πΉ Example: Material UI Button
import Button from '@mui/material/Button';
function App() {
return <Button variant="contained">Click Me</Button>;
}
πΉ Which Framework Should You Learn?
- Bootstrap: Easy, fast, best for beginners
- Tailwind: Most customizable, best for modern websites
- MUI: Best for React developers building professional dashboards/apps
CSS Best Practices β Write Clean, Scalable & Professional CSS
Writing CSS is easy β but writing clean, maintainable, and scalable CSS requires proper best practices. These rules help avoid messy code, reduce duplication, maintain consistency, and make your project easier to manage.
14.1 Clean & Readable Code
πΉ Use Consistent Formatting
button {
background-color: #3498db;
padding: 12px 20px;
border-radius: 6px;
}
- Use proper indentation
- Use lowercase for properties/values
- Add spaces around
:and{ }
πΉ Avoid Repetition (DRY Principle)
/* Bad */
.btn-blue { color: blue; }
.text-blue { color: blue; }
/* Good */
:root {
--primary-color: blue;
}
.color-primary {
color: var(--primary-color);
}
πΉ Add Helpful Comments
/* Buttons section */
.button-primary {
...
}
14.2 File Structure
Organizing CSS files properly keeps large projects manageable.
πΉ Basic CSS File Structure
styles/
βββ reset.css
βββ variables.css
βββ components.css
βββ layout.css
βββ main.css
- reset.css β Removes default browser styles
- variables.css β Colors, fonts, spacing
- components.css β Buttons, cards, navbars
- layout.css β Grid, containers, positioning
- main.css β Imports all files + page-specific styles
πΉ Using @import (Modular Approach)
@import url("reset.css");
@import url("variables.css");
@import url("components.css");
πΉ Use Separate Files for Large Projects
- CSS grows quickly β split by components
- Makes debugging faster
- Better readability for teams
14.3 Naming Conventions (BEM)
BEM (Block Element Modifier) is one of the most popular naming conventions. It makes CSS predictable, clear, and structured.
πΉ BEM Structure
.block {}
.block__element {}
.block--modifier {}
πΉ Example: Card Component
.card {} /* Block */
.card__title {} /* Element */
.card--dark {} /* Modifier */
πΉ Why Use BEM?
- Scalable naming
- Avoids conflicts
- Reusable components
- Consistent structure
πΉ BEM Real UI Example
<div class="navbar navbar--dark">
<h3 class="navbar__title">NotesTime</h3>
<button class="navbar__btn navbar__btn--active">Menu</button>
</div>