Introduction to CSS

CSS (Cascading Style Sheets) is a styling language used to design and control the appearance of web pages. While HTML provides the structure of a webpage, CSS makes it visually appealing and well-organized.

What CSS Can Control

  • Text colors and font styles
  • Font sizes and spacing
  • Layouts and positioning
  • Backgrounds and images
  • Animations and visual effects

Why CSS is Important

  1. Separation of Content and Design – Keeps HTML clean and structured.
  2. Consistency – Apply the same design across multiple pages.
  3. Responsive Design – Create layouts for desktop, tablet, and mobile.
  4. User Experience – Improve readability and visual appeal.

Real-World Example

Without CSS, websites would look plain and unformatted. CSS allows developers to create modern, professional interfaces.


h1 {
    color: blue;
    font-size: 32px;
}
    

🎯 Practice Task

  • Create a CSS rule for body and change the background color.
  • Change the text color of h1.
  • Increase the font size of p elements.

CSS Syntax

CSS is made up of rules that tell the browser how to style HTML elements. Each rule consists of a selector and a declaration block.

Basic Structure


/* This is a CSS rule */
selector {
    property: value;
    property2: value2;
}
    

Selector

The selector specifies which HTML elements the rule applies to. Examples include:

  • h1 – Selects all <h1> elements
  • .class – Selects elements with a class
  • #id – Selects an element with an ID

Declaration Block

The declaration block is enclosed in curly braces { } and contains one or more declarations.

Declaration

A declaration consists of a property and a value, separated by a colon : and ending with a semicolon ;.


h1 {
    color: blue;
    font-size: 24px;
}
    

Example Explained

In the example above:

  • Selector: h1
  • Property: color and font-size
  • Values: blue and 24px

🎯 Practice Task

  • Create a CSS rule for p that changes text color.
  • Set the font size to 18px.
  • Add a background color.

How to Add CSS to HTML

CSS can be added to an HTML document in three different ways: Inline CSS, Internal CSS, and External CSS. Each method has its own use case.

1️⃣ Inline CSS

Inline CSS is written directly inside an HTML element using the style attribute.


<h1 style="color: blue; font-size: 24px;">Hello World</h1>
    

✔ Best for quick testing ❌ Not recommended for large projects ❌ Mixes structure and design

2️⃣ Internal CSS

Internal CSS is written inside a <style> tag within the <head> section of an HTML document.


<head>
    <style>
        h1 {
            color: blue;
            font-size: 24px;
        }
    </style>
</head>
    

✔ Useful for small projects or single-page websites ❌ Not ideal for multi-page applications

3️⃣ External CSS (Recommended)

External CSS is written in a separate .css file and linked to the HTML document using the <link> tag.


<head>
    <link rel="stylesheet" href="styles.css">
</head>
    

✔ Best for large projects ✔ Keeps HTML clean and organized ✔ Easy to maintain and scale ✔ Used in professional development

Best Practices

  • Use External CSS for real-world and scalable projects.
  • Avoid inline styles in production-level websites.
  • Keep structure (HTML), design (CSS), and logic (JavaScript) separate.

🎯 Practice Task

  • Create an external CSS file and link it to your HTML page.
  • Try applying the same style using inline and internal CSS.
  • Observe which method is easier to manage.

CSS Comments

CSS comments are used to explain code, improve readability, and temporarily disable specific styles during development. Comments are ignored by the browser and do not affect styling.

Syntax of CSS Comments


/* This is a single-line comment */

/*
   This is a multi-line comment
   that spans across multiple lines
*/
    

CSS uses /* to start a comment and */ to end it. Everything written between these symbols is treated as a comment.

Example Usage


h1 {
    color: blue;      /* Sets text color to blue */
    font-size: 24px;  /* Sets font size to 24 pixels */
}
    

Why Use Comments?

  • To explain complex styling logic.
  • To organize sections of large CSS files.
  • To temporarily disable styles while testing.

Best Practices

  • Write clear and meaningful comments.
  • Do not overuse comments for obvious code.
  • Keep comments updated when modifying styles.
  • Use comments to divide large CSS files into sections.

🎯 Practice Task

  • Add comments to explain each property in a CSS rule.
  • Comment out a CSS property and observe the change.
  • Organize your CSS file using section comments.

CSS Errors

CSS errors occur when there are syntax mistakes, incorrect property names, or invalid values in your stylesheet. While CSS does not usually stop execution like programming languages, incorrect rules may be ignored by the browser, leading to unexpected styling results.

Common CSS Errors

1️⃣ Missing Semicolon

Each CSS declaration must end with a semicolon (;). Forgetting it can cause the browser to ignore the next declaration.


/* ❌ Incorrect */
h1 {
    color: blue
    font-size: 24px;
}
    

/* ✅ Correct */
h1 {
    color: blue;
    font-size: 24px;
}
    

2️⃣ Incorrect Property Name

If a property name is misspelled or does not exist, the browser will ignore it.


/* ❌ Incorrect */
h1 {
    colr: blue;
}
    

/* ✅ Correct */
h1 {
    color: blue;
}
    

3️⃣ Invalid Value

If a property is given an invalid value, that declaration will not be applied.


/* ❌ Incorrect */
h1 {
    color: bluish;
}
    

/* ✅ Correct */
h1 {
    color: blue;
}
    

How to Debug CSS Errors

  • Use browser Developer Tools (Inspect Element) to check applied styles.
  • Look for crossed-out properties in the Styles panel.
  • Use online CSS validators to check syntax.
  • Check for missing brackets { } and semicolons.

🎯 Practice Task

  • Intentionally remove a semicolon and observe the result.
  • Misspell a property name and inspect it using Developer Tools.
  • Fix the errors and verify the changes.

CSS Selectors

CSS selectors are used to target HTML elements so they can be styled. A selector defines which elements a CSS rule applies to.

Basic Selector Structure


selector {
    property: value;
}
    

The selector comes before the curly braces and determines which HTML elements will receive the styling.

Types of Selectors

1️⃣ Element Selector

Selects all elements of a specific type.


p {
    color: green;
}
    
  • Selector: p
  • Applies to all <p> elements

2️⃣ Class Selector

Selects elements with a specific class attribute. Class selectors start with a dot (.).


.my-class {
    font-weight: bold;
}
    
  • Selector: .my-class
  • Applies to all elements with class="my-class"

3️⃣ ID Selector

Selects a single element with a specific ID. ID selectors start with a hash (#).


#my-id {
    background-color: yellow;
}
    
  • Selector: #my-id
  • Applies to the element with id="my-id"

4️⃣ Universal Selector

Selects all elements on the page.


* {
    margin: 0;
    padding: 0;
}
    
  • Selector: *
  • Applies to all HTML elements

🎯 Practice Task

  • Create a class selector that changes text color to red.
  • Create an ID selector that adds a background color.
  • Use the universal selector to remove default margin.

Universal Selector

In CSS, the * symbol is called the Universal Selector. It selects all HTML elements on a page.

Basic Syntax


* {
    property: value;
}
    

Any style defined inside the curly braces will apply to every element.

Common Example (CSS Reset)


/* Remove default spacing and set box model */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
    

Explanation

  • margin: 0; – Removes default outer spacing.
  • padding: 0; – Removes default inner spacing.
  • box-sizing: border-box; – Includes padding and border inside width and height calculations.

This combination is widely used as a CSS reset to ensure consistent layout behavior across browsers.

Another Example


/* Apply global font styling */
* {
    font-family: Arial, sans-serif;
}
    

When to Use

  • Creating a CSS reset.
  • Applying consistent box-sizing across the project.
  • Setting global base styles like font-family.

⚠ Important Note

The universal selector affects every element on the page. Overusing it may reduce performance and override more specific styles. Use it mainly for resets and foundational styling.

🎯 Practice Task

  • Use the universal selector to remove default margin and padding.
  • Add a global font style using font-family.
  • Test what happens if you apply a background color globally.

CSS Colors

CSS colors are used to define the color of text, backgrounds, borders, and other visual elements on a webpage. Colors can be written in multiple formats depending on your needs.

Ways to Define Colors in CSS

1️⃣ Color Names

CSS provides predefined color names such as red, blue, green, etc.


h1 {
    color: blue;
}
    

2️⃣ Hexadecimal (Hex) Values

Hex colors start with # followed by six characters. Each pair represents red, green, and blue values.


p {
    color: #FF5733; /* Shade of orange */
}
    

3️⃣ RGB Values

RGB stands for Red, Green, Blue. Each value ranges from 0 to 255.


div {
    background-color: rgb(0, 255, 0); /* Green */
}
    

4️⃣ HSL Values

HSL stands for Hue, Saturation, and Lightness.

  • Hue: Color type (0–360)
  • Saturation: Intensity (%)
  • Lightness: Brightness (%)

section {
    border-color: hsl(240, 100%, 50%); /* Blue */
}
    

Common Usage Example


h1 {
    color: white;
    background-color: #333;
}

button {
    background-color: rgb(0, 123, 255);
    color: #fff;
}
    

Choosing Colors Professionally

  • Contrast: Ensure text is readable against the background.
  • Brand Consistency: Use a defined color palette.
  • Accessibility: Maintain sufficient contrast for users with visual impairments.
  • Consistency: Avoid using too many random colors.

🎯 Practice Task

  • Set text color using a color name.
  • Use a hex value for background color.
  • Create a button using RGB values.
  • Experiment with HSL and adjust lightness.

CSS Backgrounds

CSS background properties allow you to control the background appearance of HTML elements. You can set background colors, images, positioning, size, and repetition behavior.

Common Background Properties

Property Description Example
background-color Sets the background color of an element background-color: lightblue;
background-image Sets a background image background-image: url('image.jpg');
background-repeat Controls if/how the image repeats background-repeat: no-repeat;
background-size Defines the size of the background image background-size: cover;
background-position Sets the position of the background image background-position: center;

Example Usage


/* Background color */
body {
    background-color: #f0f0f0;
}

/* Background image */
header {
    background-image: url('header-bg.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
}
    

Background Shorthand Property

The background shorthand property allows you to define multiple background properties in a single line.


section {
    background: url('section-bg.jpg') no-repeat center/cover lightgray;
}
    

The shorthand combines: image → repeat → position → size → color

Best Practices

  • Use background-size: cover; for responsive full-width images.
  • Avoid large image files to improve performance.
  • Always provide a fallback background color.
  • Optimize images for web usage.

🎯 Practice Task

  • Set a background color for the body.
  • Add a background image to a header section.
  • Use background-size: cover; and center the image.
  • Rewrite your code using the shorthand property.

CSS Borders

CSS borders allow you to add lines around HTML elements. You can control the border's width, style, color, and even round the corners.

Border Properties

Property Description Example
border-width Sets the thickness of the border border-width: 2px;
border-style Defines the border style (solid, dashed, dotted, etc.) border-style: solid;
border-color Sets the color of the border border-color: red;
border-top, border-right, border-bottom, border-left Applies border to specific sides border-top: 2px solid black;
border-radius Rounds the corners of the border border-radius: 10px;

Basic Example


div {
    border-width: 3px;
    border-style: dashed;
    border-color: blue;
}
    

Shorthand Border Property

Instead of writing width, style, and color separately, you can use the shorthand border property.


section {
    border: 4px solid green;
}
    

Shorthand order: border: width style color;

Applying Borders to Specific Sides


article {
    border-top: 2px solid black;
    border-bottom: 2px solid black;
}
    

Border Radius

The border-radius property creates rounded corners.


div {
    border-radius: 10px;
}
    

Best Practices

  • Always define border-style — without it, the border will not appear.
  • Use shorthand for cleaner and professional code.
  • Use border-radius for modern UI designs.
  • Avoid thick borders unless needed for emphasis.

🎯 Practice Task

  • Add a solid border to a div.
  • Create a dashed border on only the top side.
  • Add rounded corners using border-radius.
  • Rewrite your code using the shorthand property.

CSS Margins

CSS margins control the space outside an element's border. They create distance between elements and help structure layout spacing.

Margin Properties

Property Description Example
margin-top Sets the top margin margin-top: 10px;
margin-right Sets the right margin margin-right: 10px;
margin-bottom Sets the bottom margin margin-bottom: 10px;
margin-left Sets the left margin margin-left: 10px;

Basic Example


p {
    margin-top: 20px;
    margin-right: 15px;
    margin-bottom: 20px;
    margin-left: 15px;
}
    

Shorthand Margin Property

The margin property allows you to define all four margins in one line.


/* Same margin on all sides */
div {
    margin: 10px;
}

/* Top & Bottom | Left & Right */
div {
    margin: 10px 15px;
}

/* Top | Left & Right | Bottom */
div {
    margin: 10px 15px 20px;
}

/* Top | Right | Bottom | Left (Clockwise) */
div {
    margin: 10px 15px 20px 5px;
}
    

🔁 Shorthand order follows a clockwise direction: Top → Right → Bottom → Left

Important Concept: Margin Collapsing

When two vertical margins meet, they may collapse into one. The larger margin value will be applied instead of adding both.


div {
    margin-bottom: 20px;
}

p {
    margin-top: 30px;
}

/* Resulting vertical space = 30px (not 50px) */
    

Best Practices

  • Use shorthand for cleaner and professional code.
  • Be mindful of margin collapsing in vertical layouts.
  • Use consistent spacing values for a clean design system.
  • Avoid excessive margin values that break layout flow.

🎯 Practice Task

  • Add equal margin to all sides of a div.
  • Set different margin values using shorthand.
  • Test margin collapsing by stacking two elements.

CSS Padding

CSS padding controls the space inside an element — specifically the space between the content and its border. Padding increases the internal spacing of an element without affecting the space outside it.

Padding Properties

Property Description Example
padding-top Sets the top padding padding-top: 10px;
padding-right Sets the right padding padding-right: 10px;
padding-bottom Sets the bottom padding padding-bottom: 10px;
padding-left Sets the left padding padding-left: 10px;

Basic Example


p {
    padding-top: 20px;
    padding-right: 15px;
    padding-bottom: 20px;
    padding-left: 15px;
}
    

Shorthand Padding Property

The padding property allows you to define all four padding values in a single line.


/* Same padding on all sides */
div {
    padding: 10px;
}

/* Top & Bottom | Left & Right */
div {
    padding: 10px 15px;
}

/* Top | Left & Right | Bottom */
div {
    padding: 10px 15px 20px;
}

/* Top | Right | Bottom | Left (Clockwise) */
div {
    padding: 10px 15px 20px 5px;
}
    

🔁 Shorthand order follows a clockwise direction: Top → Right → Bottom → Left

Padding and Element Size

Padding increases the total size of an element unless box-sizing: border-box; is used.


div {
    width: 200px;
    padding: 20px;
}

/* Total rendered width becomes 240px */
    

To prevent padding from increasing total width or height:


div {
    box-sizing: border-box;
}
    

Best Practices

  • Use padding for internal spacing, margins for external spacing.
  • Prefer shorthand for cleaner and maintainable code.
  • Use consistent spacing values to maintain design balance.
  • Consider using box-sizing: border-box; in modern layouts.

🎯 Practice Task

  • Add equal padding to all sides of a div.
  • Create a card layout using padding for internal spacing.
  • Test how padding affects element width with and without box-sizing.

CSS Height and Width

The height and width properties define the dimensions of an element’s content area. These properties are essential for layout control and responsive design.

Dimension Properties

Property Description Example
width Sets the width of an element width: 300px;
height Sets the height of an element height: 150px;
max-width Defines the maximum width an element can grow to max-width: 800px;
max-height Defines the maximum height an element can grow to max-height: 500px;
min-width Defines the minimum width an element can shrink to min-width: 200px;
min-height Defines the minimum height an element can shrink to min-height: 100px;

Basic Example


div {
    width: 300px;
    height: 150px;
}
    

Responsive Example


.container {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
}
    

Using max-width helps create responsive layouts that adjust to different screen sizes.

Common CSS Units

  • px – Fixed pixel value
  • % – Relative to the parent element
  • em – Relative to the element’s font size
  • rem – Relative to the root font size
  • vh – Viewport height
  • vw – Viewport width

Important: Box Model Interaction

By default, width and height apply only to the content area. Padding and border are added outside this size.


div {
    width: 200px;
    padding: 20px;
    border: 5px solid black;
}

/* Total width becomes 250px unless box-sizing is changed */
    

To include padding and border inside the defined width and height:


div {
    box-sizing: border-box;
}
    

Best Practices

  • Use max-width for responsive layouts.
  • Avoid fixed heights unless necessary.
  • Use relative units (%, rem, vh, vw) for flexible design.
  • Apply box-sizing: border-box; for predictable sizing.

🎯 Practice Task

  • Create a responsive container using max-width.
  • Set minimum and maximum width constraints.
  • Test how padding affects width with and without box-sizing.

CSS Box Model

The CSS Box Model defines how elements are structured and spaced in a web page. Every HTML element is treated as a rectangular box composed of four layers:

  • Content – The actual content (text, image, etc.)
  • Padding – Space between content and border
  • Border – Surrounds the padding and content
  • Margin – Space outside the border (between elements)

Box Model Structure


+-----------------------------+
|           Margin            |
|  +-----------------------+  |
|  |        Border         |  |
|  |  +-----------------+  |  |
|  |  |     Padding     |  |  |
|  |  |  +-----------+  |  |  |
|  |  |  |  Content  |  |  |  |
|  |  |  +-----------+  |  |  |
|  |  +-----------------+  |  |
|  +-----------------------+  |
+-----------------------------+
    

How Total Size Is Calculated

By default, an element’s total width and height are calculated as:


Total Width =
width + padding-left + padding-right + border-left + border-right

Total Height =
height + padding-top + padding-bottom + border-top + border-bottom
    

Example


div {
    width: 200px;
    padding: 20px;
    border: 5px solid black;
}
    

🔎 Total rendered width becomes: 200 + 40 (padding) + 10 (border) = 250px

Modern Solution: box-sizing

To include padding and border inside the defined width and height, use box-sizing: border-box;.


div {
    width: 200px;
    padding: 20px;
    border: 5px solid black;
    box-sizing: border-box;
}
    

✅ Now the total width remains 200px.

Recommended Global Practice


* {
    box-sizing: border-box;
}
    

This ensures consistent and predictable sizing across your layout.

Key Differences

  • Margin → Controls spacing between elements.
  • Padding → Controls internal spacing.
  • Border → Surrounds the padding and content.
  • Content → The visible data inside the element.

🎯 Practice Task

  • Create a box with padding, border, and margin.
  • Calculate its total width manually.
  • Apply box-sizing: border-box; and observe the difference.

CSS Outline

The outline property draws a line around an element, outside its border. Unlike borders, outlines:

  • Do not take up space
  • Do not affect layout or element size
  • Are commonly used for focus states and accessibility

Outline vs Border

  • Border → Part of the box model and affects layout
  • Outline → Drawn outside the element and does not affect layout

Outline Properties

Property Description Example
outline-style Defines the style (solid, dotted, dashed, etc.) outline-style: solid;
outline-width Defines the thickness outline-width: 3px;
outline-color Defines the color outline-color: blue;
outline-offset Sets space between the outline and the element outline-offset: 4px;

Basic Example


button {
    outline-style: dashed;
    outline-color: red;
    outline-width: 2px;
}
    

Shorthand Outline Property

You can define width, style, and color in a single declaration:


div {
    outline: 2px solid green;
}
    

Using Outline for Accessibility

Outlines are commonly used for keyboard focus indicators. Browsers automatically apply outlines to focused elements like buttons and links.


button:focus {
    outline: 3px solid #007BFF;
    outline-offset: 2px;
}
    

⚠ Avoid removing outlines without providing an alternative focus style.

Best Practices

  • Use outlines for focus states and accessibility.
  • Do not remove default focus outlines without replacement.
  • Use outline-offset for better visual separation.
  • Prefer outline over border for temporary highlighting.

🎯 Practice Task

  • Add a custom focus outline to a button.
  • Experiment with outline-offset.
  • Compare outline and border visually.

CSS Text Styling

CSS text properties allow you to control the appearance, spacing, alignment, and decoration of text content. Proper text styling improves readability, accessibility, and visual hierarchy.

Common Text Properties

Property Description Example
color Sets the text color color: #333;
text-align Aligns text (left, right, center, justify) text-align: center;
text-decoration Adds underline, overline, or line-through text-decoration: underline;
text-transform Controls capitalization text-transform: uppercase;
line-height Sets spacing between lines line-height: 1.6;
letter-spacing Controls spacing between characters letter-spacing: 1px;
word-spacing Controls spacing between words word-spacing: 3px;
white-space Controls how whitespace is handled white-space: nowrap;
text-indent Indents the first line text-indent: 30px;
text-shadow Adds shadow effect to text text-shadow: 1px 1px 3px gray;

Basic Example


p {
    color: #333;
    text-align: justify;
    line-height: 1.6;
    text-transform: capitalize;
    letter-spacing: 1px;
    word-spacing: 2px;
    text-indent: 20px;
}
    

Text Shadow Example


h1 {
    text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
}
    

Improving Readability

  • Use line-height: 1.5–1.8 for paragraphs.
  • Avoid excessive letter-spacing on body text.
  • Use text-align: left for better readability on long text.
  • Maintain sufficient color contrast for accessibility.

Accessibility Tip

Avoid using text-decoration: none; on links without providing a clear alternative hover or focus style.

Best Practices

  • Use consistent typography across your project.
  • Keep text readable on all screen sizes.
  • Use shadows sparingly for subtle visual depth.
  • Test text contrast for accessibility compliance.

🎯 Practice Task

  • Style a paragraph with proper line-height and spacing.
  • Create a heading with text-shadow.
  • Design a readable blog text layout.

CSS Fonts

CSS font properties control the typography of your website. Good font choices improve readability, hierarchy, and overall user experience.

Common Font Properties

Property Description Example
font-family Specifies the font family font-family: Arial, sans-serif;
font-size Defines the size of the text font-size: 16px;
font-weight Controls boldness (100–900 or keywords) font-weight: 700;
font-style Sets italic or oblique text font-style: italic;
font-variant Controls small-caps text font-variant: small-caps;

Font Family & Font Stacks

Always provide fallback fonts in case the primary font is unavailable. This is called a font stack.


body {
    font-family: "Helvetica Neue", Arial, sans-serif;
}
    

The browser will try each font in order until it finds one available.

Basic Example


h1 {
    font-family: "Times New Roman", serif;
    font-size: 36px;
    font-weight: 400;
    font-style: normal;
}
    

Shorthand Font Property

The font property allows you to define multiple font properties in one line.


p {
    font: italic 400 16px/1.6 Arial, sans-serif;
}
    

Order: font-style → font-weight → font-size → line-height → font-family

Using Web Fonts

You can use custom fonts via services like Google Fonts or by importing font files using @font-face.


@font-face {
    font-family: "MyFont";
    src: url("MyFont.woff2") format("woff2");
}

body {
    font-family: "MyFont", sans-serif;
}
    

Responsive Font Sizing

  • Use rem for scalable typography.
  • Avoid very small font sizes (below 14px).
  • Use relative units for better accessibility.

Best Practices

  • Limit your design to 2–3 font families.
  • Use font-weight variations for hierarchy.
  • Ensure good contrast between text and background.
  • Use consistent font sizing across sections.

🎯 Practice Task

  • Create a font stack for body text.
  • Use the shorthand font property.
  • Apply different font weights to create hierarchy.

CSS Lists

CSS allows you to customize the appearance of ordered (<ol>) and unordered (<ul>) lists. You can control bullet styles, numbering formats, positioning, and even use custom images.

Common List Properties

Property Description Example
list-style-type Defines the bullet or numbering style list-style-type: circle;
list-style-position Controls bullet placement (inside or outside) list-style-position: inside;
list-style-image Uses an image as the bullet list-style-image: url("bullet.png");
list-style Shorthand for all list-style properties list-style: square inside;

Unordered List Example


ul {
    list-style-type: square;
    list-style-position: inside;
}
    

Ordered List Example


ol {
    list-style-type: upper-roman;
    list-style-position: outside;
}
    

Removing Default List Styles (Common in Navigation)

Lists are commonly used for navigation menus. In such cases, default bullets and spacing are usually removed.


ul {
    list-style: none;
    padding: 0;
    margin: 0;
}
    

Using Custom Bullet Images


ul {
    list-style-image: url("custom-bullet.png");
}
    

⚠ For advanced control, developers often use pseudo-elements (::before) instead of list-style-image.

Best Practices

  • Use ordered lists (<ol>) for sequential content.
  • Use unordered lists (<ul>) for non-sequential items.
  • Remove default styles when creating navigation menus.
  • Keep spacing consistent for clean layout alignment.

🎯 Practice Task

  • Create a custom styled unordered list.
  • Design an ordered list with Roman numerals.
  • Build a simple horizontal navigation menu using a list.

CSS Tables

CSS allows you to customize the appearance of HTML tables, including borders, spacing, alignment, layout behavior, and visual enhancements such as hover effects and zebra striping.

Common Table Properties

Property Description Example
border-collapse Controls whether borders are merged or separated border-collapse: collapse;
border-spacing Sets spacing between cells (when not collapsed) border-spacing: 10px;
caption-side Positions the table caption caption-side: bottom;
table-layout Defines how column widths are calculated table-layout: fixed;
width Sets table width width: 100%;

Basic Table Styling Example


table {
    width: 100%;
    border-collapse: collapse;
}

th, td {
    border: 1px solid #ccc;
    padding: 10px;
    text-align: left;
}

th {
    background-color: #f2f2f2;
}
    

Zebra Striping (Alternating Row Colors)


tr:nth-child(even) {
    background-color: #f9f9f9;
}
    

Row Hover Effect


tr:hover {
    background-color: #e6f2ff;
}
    

Using Table Caption


caption {
    caption-side: top;
    font-weight: bold;
    margin-bottom: 10px;
}
    

Responsive Table Tip

For small screens, wrap your table inside a container and enable horizontal scrolling:


.table-container {
    overflow-x: auto;
}
    

Best Practices

  • Use tables only for tabular data (not for layout).
  • Always include <th> for headers.
  • Use border-collapse: collapse; for cleaner design.
  • Add zebra striping for better readability.
  • Ensure responsiveness on smaller screens.

🎯 Practice Task

  • Create a styled table with borders and padding.
  • Add zebra striping.
  • Add a hover effect.
  • Make the table responsive.

CSS Display

The display property defines how an element is rendered in the document flow. It controls whether an element behaves as a block-level element, inline element, flexible container, grid container, or is hidden entirely.

Common Display Values

Value Description Behavior
block Element starts on a new line Takes full available width
inline Flows within text Only takes required width
inline-block Flows inline but allows width & height Combines inline + block behavior
none Completely hides the element Removed from layout
flex Creates a flex container Enables flexible layouts
grid Creates a grid container Enables two-dimensional layouts

Block vs Inline Example


div {
    display: block;
}

span {
    display: inline;
}
    

Inline-Block Example

Useful for buttons, navigation items, and cards.


.box {
    display: inline-block;
    width: 150px;
    height: 100px;
}
    

Hiding Elements


.hidden {
    display: none;
}
    

⚠ Unlike visibility: hidden;, display: none; removes the element completely from the layout.

Flex and Grid (Modern Layout)


.container {
    display: flex;
}

.grid-layout {
    display: grid;
}
    

Flexbox and Grid are powerful layout systems covered in advanced CSS sections.

Best Practices

  • Use block for structural layout elements.
  • Use inline for text-level elements.
  • Use inline-block for buttons and small layout components.
  • Use flex and grid for modern layouts.
  • Avoid using tables for layout purposes.

🎯 Practice Task

  • Convert a block element into inline.
  • Create a navigation bar using inline-block.
  • Hide and show elements using display.
  • Create a simple flex container.

CSS Position

The position property controls how an element is positioned within the document flow. It works together with the offset properties top, right, bottom, and left.

Common Position Values

Value Description Layout Behavior
static Default value Element follows normal document flow
relative Positioned relative to its normal position Remains in flow but can be offset
absolute Positioned relative to nearest positioned ancestor Removed from normal flow
fixed Positioned relative to viewport Stays fixed during scrolling
sticky Switches between relative and fixed Sticks after reaching scroll threshold

Offset Properties

Offset properties define the final position of a positioned element:


top
right
bottom
left
    

Relative Position Example


.box {
    position: relative;
    top: 10px;
    left: 20px;
}
    

The element moves visually but still occupies its original space.

Absolute Position Example


.container {
    position: relative;
}

.child {
    position: absolute;
    top: 0;
    right: 0;
}
    

The absolutely positioned element is placed relative to the nearest ancestor with position other than static.

Fixed Position Example


header {
    position: fixed;
    top: 0;
    width: 100%;
}
    

Commonly used for sticky navigation bars.

Sticky Position Example


nav {
    position: sticky;
    top: 0;
}
    

The element scrolls normally until it reaches the defined offset, then becomes fixed.

Using z-index

The z-index property controls stacking order of positioned elements.


.modal {
    position: absolute;
    z-index: 1000;
}
    

Best Practices

  • Use relative to create positioning context.
  • Use absolute for precise placement inside containers.
  • Use fixed for headers, sidebars, or floating buttons.
  • Use sticky for modern scroll-based UI behavior.
  • Avoid excessive absolute positioning for full-page layouts.

🎯 Practice Task

  • Create a fixed navigation bar.
  • Position a badge in the top-right corner of a card using absolute.
  • Create a sticky sidebar.
  • Experiment with z-index stacking.

CSS Position Offsets

Offset properties are used with positioned elements (relative, absolute, fixed, and sticky) to control their final placement.

These properties define the distance between an element and the edges of its containing block.

Offset Properties

Property Description Example
top Distance from the top edge top: 10px;
right Distance from the right edge right: 20px;
bottom Distance from the bottom edge bottom: 15px;
left Distance from the left edge left: 30px;

How Offsets Behave with Different Position Values

  • relative: Moves element visually but keeps original space.
  • absolute: Positions element relative to nearest positioned ancestor.
  • fixed: Positions element relative to the viewport.
  • sticky: Works like relative until scroll threshold is reached.

Relative Position Example


.box {
    position: relative;
    top: 10px;
    left: 20px;
}
    

The element shifts visually but still occupies its original layout space.

Absolute Position Example


.container {
    position: relative;
}

.child {
    position: absolute;
    top: 0;
    right: 0;
}
    

The .child element is positioned relative to .container because it is the nearest positioned ancestor.

Using Negative Values


.banner {
    position: relative;
    top: -20px;
}
    

Negative values move elements in the opposite direction.

Modern Shorthand: inset

The inset property is shorthand for top, right, bottom, and left.


.modal {
    position: absolute;
    inset: 0;
}
    

This positions the element to fill its containing block.

Best Practices

  • Always define a positioning context using position: relative; on the parent.
  • Avoid excessive use of negative offsets.
  • Use inset for cleaner, modern CSS.
  • Test positioning across different screen sizes.

🎯 Practice Task

  • Move an element using relative positioning.
  • Position a badge in the top-right corner using absolute offsets.
  • Create a full-screen overlay using inset: 0;.
  • Experiment with negative offset values.

CSS Z-Index

The z-index property controls the stacking order of positioned elements along the z-axis (front-to-back direction).

Elements with a higher z-index value appear in front of elements with a lower value when they overlap.

Important Requirement

The z-index property only works on elements that have a position value other than static.


.box {
    position: relative;
    z-index: 10;
}
    

Basic Example


.front {
    position: relative;
    z-index: 2;
}

.back {
    position: relative;
    z-index: 1;
}
    

The .front element will appear above .back when they overlap.

Negative Z-Index


.background {
    position: relative;
    z-index: -1;
}
    

Negative values push elements behind others. Be careful, as this can sometimes place elements behind the page background.

Understanding Stacking Context

A stacking context is a parent container that controls the stacking order of its child elements.

A new stacking context is created when:

  • An element has position and a z-index value.
  • An element has opacity less than 1.
  • An element uses transform, filter, etc.

.container {
    position: relative;
    z-index: 1; /* Creates stacking context */
}
    

Elements inside a stacking context cannot escape it, even if they have higher z-index values.

Common Use Cases

  • Modals and overlays
  • Dropdown menus
  • Tooltips
  • Sticky navigation bars

Best Practices

  • Always define position when using z-index.
  • Avoid extremely large z-index values (e.g., 999999).
  • Organize layering with a clear stacking scale system.
  • Be aware of stacking context limitations.

🎯 Practice Task

  • Create two overlapping boxes with different z-index values.
  • Create a modal overlay using z-index.
  • Experiment with negative z-index values.
  • Create a stacking context and test its behavior.

CSS Overflow

The overflow property controls what happens when content exceeds the boundaries of its container.

It determines whether content is clipped, hidden, or scrollable.

Overflow Values

Value Description Behavior
visible Default value Overflow content is visible outside container
hidden Clips overflowing content No scrollbars shown
scroll Always shows scrollbars Scrollable even if not needed
auto Adds scrollbars only when needed Recommended for most cases
clip Clips content without scrollbars Modern alternative to hidden

Basic Example


.container {
    width: 200px;
    height: 100px;
    overflow: hidden;
}
    

Scrollable Container


.scrollable {
    width: 200px;
    height: 100px;
    overflow: auto;
}
    

This creates scrollbars only when the content exceeds the container size.

Controlling Directions Separately

Use overflow-x and overflow-y to manage horizontal and vertical overflow independently.


.container {
    overflow-x: scroll;
    overflow-y: hidden;
}
    

Common Use Cases

  • Scrollable cards or panels
  • Image cropping
  • Modal body scrolling
  • Horizontal scrolling tables
  • Preventing layout breakage

Important Notes

  • overflow only works if the container has a defined height or width.
  • Hidden overflow may cut off important content.
  • Scrollbars may behave differently across browsers.

Best Practices

  • Use auto instead of scroll in most cases.
  • Always define height when using vertical overflow.
  • Use overflow: hidden; carefully to avoid content loss.
  • Use horizontal overflow for responsive tables.

🎯 Practice Task

  • Create a scrollable card component.
  • Create a horizontally scrollable table.
  • Use overflow to crop an image.
  • Test overflow behaviors with different container sizes.

CSS Float

The float property was originally designed to wrap text around images, but it was widely used in the past to create layouts such as sidebars and multi-column designs.

When an element is floated, it is removed from the normal document flow and positioned to the left or right of its container.

Float Values

Value Description
left Floats element to the left
right Floats element to the right
none Default value (no floating)

Basic Float Example


.left {
    float: left;
    width: 50%;
}

.right {
    float: right;
    width: 50%;
}
    

Floated elements sit side by side if there is enough horizontal space.

The Clear Property

The clear property prevents elements from wrapping around floated elements.


.clear {
    clear: both;
}
    
Value Description
left Clears left floats
right Clears right floats
both Clears both left and right floats

Common Issue: Collapsing Parent

Because floated elements are removed from normal flow, their parent container may collapse (height becomes zero).

Clearfix Technique


.container::after {
    content: "";
    display: block;
    clear: both;
}
    

This ensures the parent container properly wraps around floated children.

Modern Alternatives

Today, float is rarely used for layout. Modern CSS layout systems include:

  • display: flex; (Flexbox)
  • display: grid; (CSS Grid)

Float is still commonly used for text wrapping around images.

Best Practices

  • Use float primarily for text wrapping.
  • Avoid building full layouts with float.
  • Always clear floats to prevent layout issues.
  • Prefer Flexbox or Grid for modern layouts.

🎯 Practice Task

  • Create a two-column layout using float.
  • Fix collapsing parent using clearfix.
  • Wrap text around an image using float.
  • Recreate the layout using Flexbox instead.

CSS Opacity

The opacity property controls the transparency level of an element. Values range from 0 (completely transparent) to 1 (fully opaque).

Opacity Values

Value Description
1 Fully visible (default)
0.5 50% transparent
0 Completely transparent (invisible but still clickable)

Basic Example


.transparent {
    opacity: 0.5;
}
    

Important Behavior

When opacity is applied to an element, it affects the entire element, including its children.


.card {
    opacity: 0.7;
}
    

All text, images, and child elements inside .card will also become semi-transparent.

Opacity vs RGBA Background

If you want only the background to be transparent (without affecting text), use rgba() instead.


.box {
    background-color: rgba(0, 0, 0, 0.5);
}
    

This keeps text fully visible while making only the background transparent.

Hover Effect Example


.image {
    opacity: 0.7;
    transition: opacity 0.3s ease;
}

.image:hover {
    opacity: 1;
}
    

Opacity transitions are commonly used for image hover effects.

Stacking Context Note

An element with opacity less than 1 creates a new stacking context, which can affect z-index behavior.

Accessibility Considerations

  • Avoid making text too transparent.
  • Ensure sufficient contrast for readability.
  • Test opacity effects across different screen types.

Best Practices

  • Use opacity for subtle visual effects.
  • Prefer rgba() for background transparency.
  • Combine opacity with transitions for smooth UI effects.
  • Avoid excessive transparency for important content.

🎯 Practice Task

  • Create an image hover fade-in effect.
  • Build a semi-transparent overlay.
  • Compare opacity vs rgba background transparency.
  • Experiment with opacity and z-index stacking.

CSS Navigation Bars

Navigation bars (navbars) are essential UI components used for website navigation. Modern navbars are typically built using semantic HTML and styled using Flexbox.

Basic HTML Structure


<nav class="navbar">
    <div class="logo">MySite</div>
    <ul class="nav-links">
        <li><a href="#" class="active">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
</nav>

Modern Flexbox Styling


.navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #333;
    padding: 0 20px;
}

.nav-links {
    list-style: none;
    display: flex;
    margin: 0;
    padding: 0;
}

.nav-links li {
    margin-left: 20px;
}

.nav-links a {
    text-decoration: none;
    color: white;
    padding: 14px 0;
    transition: color 0.3s ease;
}

.nav-links a:hover,
.nav-links a:focus {
    color: #f2c94c;
}

.nav-links a.active {
    border-bottom: 2px solid #f2c94c;
}
    

Sticky Navigation Bar


.navbar {
    position: sticky;
    top: 0;
    z-index: 1000;
}
    

This keeps the navbar visible when scrolling.

Responsive Navigation (Simple Example)


@media (max-width: 768px) {
    .nav-links {
        flex-direction: column;
        background-color: #444;
    }

    .nav-links li {
        margin: 10px 0;
    }
}
    

Key Features in Modern Navbars

  • Flexbox layout
  • Hover and focus states for accessibility
  • Active link indication
  • Sticky positioning
  • Responsive behavior

Best Practices

  • Use semantic <nav> element.
  • Remove default list styling for menu items.
  • Always provide hover and focus states.
  • Ensure sufficient color contrast.
  • Use Flexbox instead of float for layout.

🎯 Practice Task

  • Create a horizontal navigation bar using Flexbox.
  • Add an active link style.
  • Make the navbar sticky.
  • Make it responsive for mobile screens.

CSS Dropdown Menus

Dropdown menus are widely used in navigation systems to organize links and actions in a structured way. Modern dropdowns should be accessible, responsive, and scalable for large applications.

Basic HTML Structure

HTML - Dropdown Navbar

<nav class="navbar">
    <ul class="nav-links">
        <li class="dropdown">
            <a href="#" class="dropdown-toggle">Services</a>
            <ul class="dropdown-menu">
                <li><a href="#">Web Design</a></li>
                <li><a href="#">Development</a></li>
                <li><a href="#">SEO</a></li>
            </ul>
        </li>
    </ul>
</nav>

The dropdown is structured using nested unordered lists. The parent .dropdown acts as the positioning context.

Dropdown Positioning


.dropdown {
    position: relative;
}

.dropdown-menu {
    list-style: none;
    position: absolute;
    top: 100%;
    left: 0;
    min-width: 180px;
    background-color: #ffffff;
    padding: 0;
    margin: 0;
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}
    

position: relative; creates a positioning context. position: absolute; places the dropdown below the parent. top: 100%; ensures it appears directly under the toggle.

Dropdown Link Styling


.dropdown-menu li a {
    display: block;
    padding: 10px 15px;
    text-decoration: none;
    color: #333;
    transition: background-color 0.3s ease;
}

.dropdown-menu li a:hover {
    background-color: #f2f2f2;
}
    

Using display: block; makes the entire row clickable, improving usability.

Visibility Control (Hover + Focus)


.dropdown-menu {
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease;
}

.dropdown:hover .dropdown-menu,
.dropdown:focus-within .dropdown-menu {
    opacity: 1;
    visibility: visible;
}
    

:hover enables mouse interaction. :focus-within ensures keyboard accessibility.

Z-Index for Layering


.dropdown-menu {
    z-index: 1000;
}
    

z-index ensures the dropdown appears above other page elements.

Nested Dropdown (Advanced Structure)


.dropdown-menu li {
    position: relative;
}

.dropdown-menu .submenu {
    position: absolute;
    top: 0;
    left: 100%;
}
    

Nested dropdowns allow multi-level navigation systems. This structure is commonly used in large websites.

Important Concepts

  • Relative & Absolute Positioning control placement.
  • Opacity & Visibility enable smooth animations.
  • Z-index manages stacking order.
  • :focus-within improves accessibility.
  • Transition enhances user experience.

Best Practices

  • Ensure keyboard accessibility.
  • Do not rely only on hover for important navigation.
  • Maintain sufficient color contrast.
  • Test on touch devices.
  • Use aria attributes for advanced accessibility.

🎯 Practice Task

  • Create a responsive navigation bar with dropdown.
  • Add fade-in animation.
  • Implement keyboard accessibility.
  • Create a multi-level nested dropdown.

CSS Forms

CSS allows developers to design clean, accessible, and professional forms. Proper form styling improves usability, readability, accessibility, and overall user experience in modern web applications.

Basic HTML Structure

HTML – Form Example

<form class="form-container">

    <div class="form-group">
        <label for="name">Full Name</label>
        <input type="text" id="name" class="form-control" placeholder="Enter your name">
    </div>

    <div class="form-group">
        <label for="email">Email Address</label>
        <input type="email" id="email" class="form-control" placeholder="Enter your email">
    </div>

    <div class="form-group">
        <label for="message">Message</label>
        <textarea id="message" class="form-control" rows="4"></textarea>
    </div>

    <button type="submit" class="btn-submit">Submit</button>

</form>

The form is structured using reusable class-based architecture. Each input field is wrapped inside a .form-group for spacing and organization.

Form Container Styling


.form-container {
    max-width: 500px;
    background-color: #ffffff;
    padding: 2rem;
    border-radius: 10px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
}
    

The container creates a clean card-style layout suitable for login forms, contact forms, and registration forms.

Form Group & Labels


.form-group {
    margin-bottom: 1.25rem;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 600;
    color: #333;
}
    

Labels are displayed as block elements to ensure proper alignment and accessibility.

Input & Textarea Styling


.form-control {
    width: 100%;
    padding: 0.75rem 1rem;
    border: 1px solid #dcdcdc;
    border-radius: 6px;
    font-size: 1rem;
    transition: border-color 0.3s ease, box-shadow 0.3s ease;
    box-sizing: border-box;
}
    

box-sizing: border-box; ensures padding does not break layout. All form elements use a reusable .form-control class.

Focus State (Accessibility Enhancement)


.form-control:focus {
    border-color: #2563eb;
    outline: none;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
}
    

Focus states are critical for keyboard navigation and accessibility compliance.

Submit Button Styling


.btn-submit {
    display: inline-block;
    width: 100%;
    padding: 0.9rem;
    background-color: #2563eb;
    color: #ffffff;
    font-weight: 600;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: background-color 0.3s ease, transform 0.2s ease;
}

.btn-submit:hover {
    background-color: #1e4ed8;
    transform: translateY(-2px);
}

.btn-submit:active {
    transform: translateY(0);
}
    

Micro-interactions such as hover and active states improve visual feedback and user experience.

Validation States (Professional Enhancement)


.form-control.error {
    border-color: #dc2626;
}

.form-control.success {
    border-color: #16a34a;
}
    

In large applications, validation styles help users understand errors clearly.

Important Concepts

  • Reusable Classes improve scalability.
  • Focus States enhance accessibility.
  • Transitions improve user interaction.
  • box-sizing prevents layout issues.
  • Semantic HTML improves SEO and usability.

Best Practices

  • Always associate labels with inputs using for and id.
  • Use accessible focus styles (never remove focus without replacement).
  • Ensure sufficient color contrast.
  • Test forms on mobile devices.
  • Optimize spacing for readability.

🎯 Practice Task

  • Create a responsive contact form.
  • Add focus and hover effects.
  • Add error and success validation styles.
  • Style a login form using the same architecture.

CSS Website Layouts

Modern websites are structured using layout techniques such as Flexbox and CSS Grid. A standard website layout typically includes: Header, Navigation, Main Content, Sidebars, and Footer.

Basic HTML Layout Structure


<div class="wrapper">

    <header class="header">Header</header>

    <nav class="nav">Navigation Menu</nav>

    <main class="content-area">
        <aside class="sidebar-left">Left Sidebar</aside>
        <section class="main-content">Main Content</section>
        <aside class="sidebar-right">Right Sidebar</aside>
    </main>

    <footer class="footer">Footer</footer>

</div>

Semantic HTML elements like <header>, <nav>, <main>, <aside>, and <footer> improve SEO and accessibility.

Global Reset & Base Styling


* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    background-color: #ffffff;
}
    

box-sizing: border-box; ensures predictable sizing across the entire layout.

Wrapper Container


.wrapper {
    width: 90%;
    margin: 30px auto;
}
    

The wrapper centers the layout and controls overall width.

Header & Navigation Styling


.header,
.nav,
.footer {
    background-color: #e6e6e6;
    padding: 20px;
    text-align: center;
    border-radius: 4px;
    margin-bottom: 15px;
}
    

These sections use Flexbox-friendly alignment for consistent structure.

Main Content Layout (CSS Grid)


.content-area {
    display: grid;
    grid-template-columns: 1fr 3fr 1fr;
    gap: 15px;
    margin-bottom: 15px;
}

.sidebar-left,
.sidebar-right,
.main-content {
    background-color: #e6e6e6;
    padding: 20px;
    border-radius: 4px;
    min-height: 300px;
}
    

CSS Grid allows precise multi-column layouts. Here we create a 3-column structure: Sidebar (1fr) | Main Content (3fr) | Sidebar (1fr).

Responsive Layout


@media (max-width: 768px) {
    .content-area {
        grid-template-columns: 1fr;
    }
}
    

On smaller screens, the layout converts into a single-column structure for better readability on tablets and mobile devices.

Important Concepts

  • CSS Grid enables multi-column layouts.
  • Flexbox is useful for alignment inside sections.
  • Semantic HTML improves accessibility and SEO.
  • Media Queries ensure responsiveness.
  • Fraction Units (fr) control proportional widths.

Best Practices

  • Always design mobile-first when possible.
  • Use semantic HTML elements.
  • Keep layout structure separate from content styling.
  • Use CSS Grid for major layout and Flexbox for alignment.
  • Test layout across different screen sizes.

🎯 Practice Task

  • Create a 3-column website layout.
  • Convert it into a 2-column layout on tablet.
  • Make it single-column on mobile.
  • Add a fixed header at the top.

CSS Flexbox (Flexible Box Layout)

CSS Flexbox is a modern layout system designed to create flexible, responsive, and well-aligned layouts. It simplifies alignment, spacing, and distribution of elements without using floats or complex positioning.

Basic HTML Structure

HTML – Flexbox Example

<div class="flex-container">
    <div class="flex-item">Item 1</div>
    <div class="flex-item">Item 2</div>
    <div class="flex-item">Item 3</div>
</div>

The parent element becomes a flex container, and its children become flex items.

Flex Container Properties

Property Description
display: flex; Defines a flex container.
flex-direction Controls item direction (row, column).
justify-content Aligns items along the main axis.
align-items Aligns items along the cross axis.
flex-wrap Allows items to wrap to next line.
gap Adds spacing between flex items.

Flex Container Example


.flex-container {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
}
    

This creates a responsive horizontal layout where items are spaced evenly and wrap automatically on smaller screens.

Flex Item Properties

Property Description
flex-grow Defines how much an item can grow.
flex-shrink Defines how much an item can shrink.
flex-basis Initial size of the item.
flex Shorthand for grow, shrink, basis.
align-self Overrides alignment for a single item.

Flex Item Example


.flex-item {
    flex: 1;            /* grow: 1, shrink: 1, basis: 0 */
    padding: 20px;
    background-color: #e6e6e6;
    text-align: center;
    border-radius: 6px;
}
    

Using flex: 1; ensures all items share equal width.

Responsive Flexbox Layout


@media (max-width: 768px) {
    .flex-container {
        flex-direction: column;
    }
}
    

On smaller screens, the layout switches from row to column for better readability.

Important Concepts

  • Main Axis is controlled by flex-direction.
  • Cross Axis is perpendicular to main axis.
  • Flexbox is one-dimensional (row OR column).
  • Gap property simplifies spacing.
  • Flexbox is ideal for alignment tasks.

Best Practices

  • Use Flexbox for component-level layouts.
  • Use CSS Grid for full-page multi-column layouts.
  • Prefer gap over margin spacing.
  • Test wrapping behavior on smaller screens.
  • Combine Flexbox with media queries for responsiveness.

🎯 Practice Task

  • Create a responsive navigation bar using Flexbox.
  • Center a card both horizontally and vertically.
  • Create a 3-column layout using flex.
  • Make the layout stack on mobile.

CSS Grid (Two-Dimensional Layout System)

CSS Grid is a powerful two-dimensional layout system that allows you to design complex layouts using rows and columns simultaneously. Unlike Flexbox (which is one-dimensional), Grid controls both horizontal and vertical alignment at the same time.

Basic HTML Structure


<div class="grid-container">
    <div class="grid-item">Header</div>
    <div class="grid-item">Sidebar</div>
    <div class="grid-item">Main</div>
    <div class="grid-item">Footer</div>
</div>

The parent element becomes a grid container, and its children become grid items.

Grid Container Properties

Property Description
display: grid; Defines the element as a grid container.
grid-template-columns Defines column structure and width.
grid-template-rows Defines row structure and height.
grid-template-areas Defines named layout areas.
gap Controls spacing between rows and columns.
justify-items Horizontal alignment inside cells.
align-items Vertical alignment inside cells.
justify-content Aligns entire grid horizontally.
align-content Aligns entire grid vertically.

Grid Container Example


.grid-container {
    display: grid;
    grid-template-columns: 250px 1fr;
    grid-template-rows: 80px 1fr 60px;
    grid-template-areas:
        "header header"
        "sidebar main"
        "footer footer";
    gap: 20px;
    height: 100vh;
}
    

Grid Item Properties

Property Description
grid-column Defines column start and end position.
grid-row Defines row start and end position.
grid-area Assigns item to named area.
justify-self Horizontal alignment of individual item.
align-self Vertical alignment of individual item.

Assigning Grid Areas


header {
    grid-area: header;
}

aside {
    grid-area: sidebar;
}

main {
    grid-area: main;
}

footer {
    grid-area: footer;
}
    

Responsive Grid Layout


@media (max-width: 768px) {
    .grid-container {
        grid-template-columns: 1fr;
        grid-template-areas:
            "header"
            "main"
            "sidebar"
            "footer";
    }
}
    

On smaller screens, the layout switches to a single-column structure for improved readability and mobile optimization.

Common Grid Units

  • px → Fixed size
  • % → Percentage of container
  • fr → Fraction of available space (flexible unit)
  • auto → Size based on content
  • minmax() → Defines size range
  • repeat() → Repeats column/row patterns

Dynamic Column Example


.grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}
    

This creates automatically responsive columns that adjust based on available screen width.

When to Use Grid vs Flexbox

  • Use Grid → Full-page layouts (rows + columns).
  • Use Flexbox → Component alignment (one direction).
  • Combine both for modern responsive design.

Best Practices

  • Use fr unit for flexible layouts.
  • Use gap instead of margin for spacing.
  • Prefer named areas for readability.
  • Use repeat() and minmax() for responsive grids.
  • Test layouts on multiple screen sizes.

🎯 Practice Task

  • Create a 3-column blog layout using Grid.
  • Design a dashboard layout (sidebar + header + main).
  • Build a responsive product card grid.
  • Make the layout mobile-friendly using media queries.

🎉 Course Completed!

Congratulations! You’ve successfully finished this course.