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. 🎨

πŸ’‘ Why CSS?
- 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
βœ… Flow: Browser reads HTML β†’ finds CSS (inline/internal/external) β†’ applies cascade, specificity and inheritance rules β†’ renders the styled page.

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.
πŸ’‘ Shorthand: Many properties have shorthand (e.g., 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)
⚠️ Best practice: Use external CSS for most projects. Inline only for tiny overrides and testing.

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.

Syntax: /* 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;
}
πŸš€ In short: Comments make your CSS maintainable and team-friendly. Use them wisely.

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
πŸ’‘ Tip: Prefer .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 ("*")
πŸš€ Real Use Case: Highlight all external links using 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
⚠️ Be careful: Overusing descendant selectors (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
❗ Avoid using too many IDs β€” they make CSS harder to override and maintain.
/* Specificity battle */
#title { color: red; }     /* wins */
.title { color: blue; }
h1 { color: green; }
                     
🧠 In short: Higher specificity wins. Inline > ID > Class > Element.

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
πŸ’‘ Tip: Use HSL for theme colors because adjusting brightness & saturation is easier.
/* 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 image
  • background-repeat β€” repeat, no-repeat, repeat-x, repeat-y
  • background-size β€” contain, cover, auto, custom
  • background-position β€” center, top, left, coordinates
  • background-attachment β€” scroll, fixed (parallax effect)
πŸš€ Pro Tip: Use 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-width
  • border-style β€” solid, dashed, dotted, double, groove
  • border-color
  • border-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);
}
🎨 In short: Use gradients to enhance backgrounds, buttons, cards, and UI highlights.

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
πŸ’‘ Tip: Use 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
🎨 Best Practice: Use padding (not margin) to create uniform spacing inside buttons and cards.
.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

  • solid
  • dashed
  • dotted
  • double
  • groove
  • ridge
  • inset
  • outset

Border Radius

border-radius: 10px;       /* rounded corners */
border-radius: 50%;        /* perfect circle */
⚠️ Note: Border radius works only on borders (not outlines).

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;
}
🌟 Recommended: Always use 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);
}
🎨 Pro UI Tip: Use light, soft shadows (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;
}
⚠️ Avoid using too many px values in responsive design.

πŸ“Œ Relative Unit: % (Percentage)

% is relative to the parent element’s size.

.box {
  width: 50%;   /* half of parent width */
}
πŸ’‘ Percentages are ideal for fluid layouts.

πŸ“Œ 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 */
}
🌟 Best Practice: Use rem for font sizes and spacing to maintain consistency.

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 */
}
πŸ“± Use case: Full-screen banners, hero sections, and responsive layout blocks.

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);
}
🎯 Pro Tip: Use 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
πŸ’‘ Tip: Always provide a fallback font for better browser compatibility.

6.2 Font Weight & Style

The font-weight and font-style properties help control thickness and emphasis.

Font Weight

  • font-weight: 100; – Thin
  • font-weight: 400; – Normal
  • font-weight: 600; – Semi-Bold
  • font-weight: 700; – Bold
  • font-weight: 900; – Extra Bold

Font Style

font-style: italic;
✨ Use bold text carefully: Too much bold text reduces readability.

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;
✍️ Pro Tip: Increase letter spacing for uppercase text to make it more readable.

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;
}
⚠️ Avoid long justified paragraphs β€” they can create awkward spacing.

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;
}
🌟 Recommended Fonts: Poppins, Inter, Roboto, Montserrat for clean UI/UX.
🎨 In short: Great typography improves user engagement, readability, and the overall look of your website.

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;
}
πŸ’‘ Best for default layouts. No custom positioning needed.

πŸ”Ή 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.
🧠 Pro Tip: Always set 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.
⚠️ If no positioned parent exists, the element is positioned relative to the page (body).

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
πŸ’‘ Example: Chat buttons on website corners use 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
✨ Sticky elements only work inside scrollable containers.

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
🧠 Remember: A positioned parent creates a new stacking context. Z-index inside it does NOT escape to outer layers.
🎨 In short: With proper positioning & z-index, you can build sticky headers, floating menus, popups, tooltips, and advanced UI elements effortlessly.

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
rowItems placed left to right (default)
columnItems placed top to bottom
row-reverseItems reversed horizontally
column-reverseItems reversed vertically
πŸ’‘ Use column when building mobile-first vertical layouts.

πŸ”Ή 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
πŸš€ Useful Tip: Use 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;
}
⚠️ baseline aligns text baseline for typography-heavy designs.

πŸ”Ή 4. flex-wrap

Decides whether items wrap to a new line.

.container {
  flex-wrap: nowrap | wrap | wrap-reverse;
}
πŸ’‘ Helpful for responsive rows of cards or images.

πŸ”Ή 5. gap (Flex Gap)

Adds spacing between flex items (no margin needed!).

.container {
  gap: 20px;
}
πŸŽ‰ Flex gap works in all modern browsers β€” preferred over margins.

πŸ”Ή 6. align-content

Used when items wrap (multi-line). Controls vertical spacing between rows.

.container {
  align-content: center | space-between | space-around | stretch;
}
πŸ’‘ Only works when flex-wrap creates multiple rows.

8.2 Flex Item Properties

πŸ”Ή 1. order

Changes the sequence of items without editing HTML.

.item {
  order: 2;
}
⚠️ Overusing 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;
}
πŸ’‘ Set 0 to prevent items from shrinking (great for logos).

πŸ”Ή 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;
}
⭐ Recommended way to control responsive cards/boxes.

πŸ”Ή 6. align-self

Overrides align-items for a single item only.

.item {
  align-self: center;
}
🎯 Useful when one element needs different vertical alignment.

8.3 Flexbox Layout Examples

πŸ”Ή Example 1: Center Anything (Horizontally + Vertically)

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
πŸŽ‰ Easiest way to center elements in CSS!

πŸ”Ή 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;
}
πŸ’‘ Flexbox simplifies header + logo + menu alignment perfectly.

🧠 In Short: Flexbox makes layout building easy, responsive, and powerful β€” especially for navbars, cards, forms, sidebars, and centered elements.

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 */
}
πŸ’‘ 1fr means β€œfractional unit” β€” divides available space equally.

πŸ”Ή 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 */
}
🌟 Cleaner layouts β€” no need for margins between items!

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));
}
πŸ“± Perfect for responsive galleries & card layouts.

πŸ”Ή 3. minmax()

Sets minimum and maximum size of a grid track.

.grid-container {
  grid-template-columns: repeat(3, minmax(150px, 1fr));
}
πŸ’‘ Ensures columns never shrink below 150px.

πŸ”Ή 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;
}
⚠️ Implicit grid helps avoid layout breaks when extra items appear.

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; }
🎯 Result: A clean, readable layout structure similar to designing in Figma.

πŸ”Ή Visual Example (Text-based Diagram)

|  HEADER  |  HEADER  |  HEADER  |
| SIDEBAR  |   MAIN   |   MAIN   |
|  FOOTER  |  FOOTER  |  FOOTER  |
🧠 Ideal for: dashboards, blogs, admin panels, and app layouts.

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));
}
πŸ’‘ Items automatically wrap and resize based on screen width.

πŸ”Ή 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;
  }
}
πŸ“± Perfect for responsive product cards, blogs, and landing pages.

🧠 In Short: CSS Grid is the best tool for creating modern, responsive, and complex layouts with fewer lines of code and perfect alignment.

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;
}
πŸ’‘ Smooth color animation on hover β€” simple and effective.

πŸ”Ή Common transition properties:

  • transition-property
  • transition-duration
  • transition-delay
  • transition-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)
🎨 cubic-bezier() gives you custom control over the animation curve.

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);
}
⚠️ Tip: Always combine transforms in one line β€” multiple transform properties overwrite each other.

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-name
  • animation-duration
  • animation-timing-function
  • animation-delay
  • animation-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); }
}
πŸ”„ Perfect for loaders, icons, and attention-grabbing UI elements.

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; }
🎯 Perfect for fade-in lists, cards, or gallery items.

πŸ”₯ 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); }
}
🧠 Used widely in modern UI/UX for product cards and image galleries.

πŸ”₯ 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;
}
⚠️ Requires position: relative & extra styling but works great!

πŸš€ In Short: CSS Animations help you create modern, eye-catching UI elements that improve user experience without JavaScript.

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.

πŸ“± Fun Fact: 70% of web traffic today comes from mobile devices. Responsive design is no longer optional β€” it’s mandatory!

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;
  }
}
πŸ’‘ max-width means β€œapply styles when screen width is ≀ 600px”.

πŸ”Ή 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.

⚠️ Why mobile-first? - Faster loading - Better performance - Works on all devices - Search engines prefer it (SEO boost)

πŸ”Ή 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;
  }
}
πŸ“± β†’ πŸ’» Your website grows as screen size grows.

πŸ”Ή Common Breakpoints (Industry Standard)

Device Type Width
Small Phones<576px
Mobile576px – 767px
Tablet768px – 991px
Laptop992px – 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);
  }
}
πŸ“¦ Items rearrange neatly based on screen size.

πŸ”Ή Example: Navigation Menu Breakpoint

@media (max-width: 768px) {
  nav ul {
    display: none;
  }
  .menu-icon {
    display: block;
  }
}
πŸ“± Mobile menu replaces desktop menu β€” modern websites use this everywhere!

🧠 In Short: Responsive design ensures your website works perfectly on every device using media queries, flexible units, breakpoints, and mobile-first strategies.

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.

πŸ’‘ Think of CSS variables like β€œglobal settings” for your entire website.

12.1 Using Variables

πŸ”Ή Syntax

:root {
  --primary-color: #3498db;
  --padding-size: 20px;
}

Using the variable:

button {
  background: var(--primary-color);
  padding: var(--padding-size);
}
🌟 Variables help avoid repeated values and make global edits easy.

πŸ”Ή Why :root?

:root represents the top-level element (html). Declaring variables here makes them global and accessible from anywhere.

πŸ”‘ Best practice: Always define your main color palette and spacing in :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);
}
⚠️ Local variables override global ones when they have the same name.

πŸ”Ή Example: Parent-Child Behavior

.theme-dark {
  --text-color: #fff;
}

.theme-light {
  --text-color: #333;
}

p {
  color: var(--text-color);
}
🎯 Result: Same paragraph inherits different colors depending on parent theme.

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;
}
πŸŒ™ Switch themes by simply adding/removing the .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);
}
🎨 Perfect for real-world websites, dashboards, portfolio themes, etc.

πŸ”Ή Dynamic Variables (Updated with JavaScript)

document.documentElement.style.setProperty('--primary-color', '#ff5733');
πŸš€ Use this for color pickers, user personalization, or dynamic UI controls.

🧠 In Short: CSS Variables simplify your code, allow global control, support theming, and make large projects easier to maintain.

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.

πŸ’‘ Think of frameworks as β€œpre-built Lego blocks” for web design β€” assemble them to create beautiful UIs quickly.

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>
⭐ Best for beginners, agencies, dashboards, admin panels.

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>
⚑ Best for developers who want full design freedom and pixel-perfect UI.

πŸ”Ή 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>;
}
πŸš€ Best for React projects where you need fast, premium UI components.

πŸ”Ή 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
πŸ”₯ Pro Tip: Learn Bootstrap first ➝ Tailwind next ➝ MUI (if using React)

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.

πŸ’‘ Good CSS = Faster Development + Fewer Bugs + Better Performance

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 { }
βœ”οΈ Clean formatting makes CSS easier to scan, debug, and maintain.

πŸ”Ή Avoid Repetition (DRY Principle)

/* Bad */
.btn-blue { color: blue; }
.text-blue { color: blue; }

/* Good */
:root {
  --primary-color: blue;
}
.color-primary {
  color: var(--primary-color);
}
⚠️ DRY = Don’t Repeat Yourself Repeated CSS values make code harder to maintain.

πŸ”Ή Add Helpful Comments

/* Buttons section */
.button-primary {
  ...
}
πŸ’‘ Comment sections to organize your file: "Header styles", "Footer styles", "Layout", "Components", etc.

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");
🌟 Modular CSS keeps code structured and makes teamwork easier.

πŸ”Ή 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 is used by companies like Google, Yandex, and many large teams.

πŸ”Ή 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>
πŸ”‘ BEM helps create UI components that are reusable across your entire site.

🧠 In Short: Clean formatting, modular file structure, and BEM naming lead to professional, scalable CSS.