Chapter 1: Introduction to Web & HTML Basics
Learning Objectives
By the end of this chapter, you will be able to:
- Understand how the internet and web work
- Write a valid HTML5 document with proper structure
- Use basic HTML tags correctly (html, head, body, h1, p)
- Create your first web page and view it in a browser
Concept Introduction: What is the Web?
The web is a system of interconnected documents and resources linked by hyperlinks and accessed through the internet. When you open a web browser (Chrome, Firefox, Safari), you’re accessing documents written in HTML (HyperText Markup Language).
A URL (Uniform Resource Locator) is the web address you type in your
browser, like https://www.example.com. It tells your browser where to
find a web page.
HTML is the markup language that provides the structure and content of web pages. Think of it as the skeleton of a house. CSS adds the styling (paint, decoration), and JavaScript adds interactivity (doors that open, lights that turn on).
Learn more: W3Schools HTML Introduction
HTML Document Structure
Every valid HTML5 document has this basic structure:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<!-- Content goes here -->
</body>
</html>
Let’s break down each part:
<!DOCTYPE html>- Declares this is an HTML5 document<html>- The root element that contains all other elements<head>- Contains metadata (title, character encoding, links to CSS)<title>- The text shown in the browser tab<body>- Contains all visible content (headings, paragraphs, images, etc.)
Step-by-Step Exercise: Create Your First Web Page
Step 1: Open a Text Editor
Open a text editor like Notepad (Windows), TextEdit (Mac), or VS Code (any platform). Do NOT use Word or Google Docs.
Step 2: Write the HTML
Copy and paste this code into your text editor:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>My First Web Page</title>
</head>
<body>
<h1>Welcome to My Web Page</h1>
<p>Hello! This is my first web page created with HTML.</p>
<h2>About Me</h2>
<p>I am learning web design and this is the beginning
of my journey.</p>
<h2>My Interests</h2>
<p>I enjoy learning new technologies and creating
amazing websites.</p>
</body>
</html>
Step 3: Save the File
- Click File → Save As
- Name the file:
index.html - Choose a location (Desktop or Documents)
- Make sure the file type is Plain Text or All Files
- Click Save
Step 4: Open in Your Browser
- Open the folder where you saved
index.html - Right-click on the file
- Choose Open With → Chrome (or your preferred browser)
- Your web page should appear!
Step 5: View Page Source
In your browser, right-click on the page and select Inspect or View Page Source to see your HTML code.
Common HTML Elements You Used
| Element | Purpose | Example |
|---|---|---|
<h1> to <h6> | Headings (h1 is largest) | <h1>Welcome</h1> |
<p> | Paragraph of text | <p>This is text</p> |
<body> | Contains all visible content | Wraps page content |
<head> | Contains page metadata | <title>, <meta> |
Challenge Exercise (Optional)
Personalize Your Page: Edit your index.html file to:
- Change the title (in the
<title>tag) to something personal - Replace “Welcome to My Web Page” with your own heading
- Add information about yourself in the paragraphs
- Add at least two more
<h2>headings with<p>paragraphs below them - Save the file and refresh your browser (press F5) to see changes
Tip: Every time you edit the HTML file and save it, refresh your browser (Ctrl+R or Cmd+R) to see the changes.
Key Takeaways
- HTML is the foundation of all web pages
- A valid HTML5 document needs
<!DOCTYPE>,<html>,<head>, and<body>tags - Headings (
<h1>-<h6>) organize content hierarchically - Paragraphs (
<p>) contain text content - Always save files as
.htmlwith a text editor - View your work in a web browser
References
Chapter 2: HTML5 - Headings, Paragraphs & Text Formatting
Learning Objectives
By the end of this chapter, you will be able to:
- Understand heading hierarchy and use heading tags correctly
- Format text with bold, italic, emphasis, and strong tags
- Apply colors to text and backgrounds using inline styles
- Use HTML attributes to enhance your elements
- Create semantically meaningful content
Concept Introduction: Headings & Hierarchy
Headings organize your page content into a clear structure. HTML has
six heading levels: <h1> (largest) through <h6> (smallest).
<h1>- Main page title (use only ONE per page)<h2>- Major sections<h3>- Subsections<h4>through<h6>- Further subdivisions
Important: Use headings for structure, not styling. Don’t skip heading levels (go h1 → h2 → h3, not h1 → h3).
Learn more: W3Schools HTML Headings
Text Formatting Tags
HTML provides semantic tags for emphasizing text:
| Tag | Purpose | Usage |
|---|---|---|
<strong> | Indicates strong importance | <strong>critical info</strong> |
<b> | Bold text (no semantic meaning) | <b>bold text</b> |
<em> | Emphasized text (usually italic) | <em>emphasized</em> |
<i> | Italic text (no semantic meaning) | <i>italic text</i> |
Semantic vs Non-semantic: <strong> and <em> add meaning for
screen readers. <b> and <i> are just visual styling.
Learn more: W3Schools Text Formatting
HTML Attributes
Attributes provide additional information about elements. Common attributes include:
id- Unique identifier for an elementclass- Groups elements for stylingstyle- Inline CSS stylingtitle- Tooltip text on hover
Example:
<p style="color: blue;">This text is blue</p>
<h2 id="main-heading">My Heading</h2>
Learn more: W3Schools HTML Attributes
Inline Styling with Colors
You can apply colors directly to HTML elements using the style attribute:
<!-- Text color -->
<p style="color: red;">This text is red</p>
<!-- Background color -->
<p style="background-color: yellow;">Yellow background</p>
<!-- Combined -->
<p style="color: white; background-color: navy;">
White text on navy background
</p>
Color values can be:
- Color names:
red,blue,green, etc. - Hex codes:
#FF0000(red),#0000FF(blue) - RGB:
rgb(255, 0, 0)(red)
Learn more: W3Schools HTML Colors
Step-by-Step Exercise: Create a Blog Post
Step 1: Open Your Text Editor
Create a new file and save it as blog-post.html
Step 2: Write the HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>My First Blog Post</title>
</head>
<body>
<h1>The Future of Web Design</h1>
<p style="color: #666;">
Published on <strong>November 23, 2025</strong>
</p>
<h2>Introduction</h2>
<p>Web design has evolved dramatically over the past
decade. <em>Responsive design</em>, <strong>accessibility</strong>,
and <b>performance</b> are now essential considerations for
every web developer.</p>
<h2>Key Trends</h2>
<p>Several important trends are shaping modern web design:</p>
<h3>Mobile-First Design</h3>
<p>Designing for mobile devices first, then scaling up
to larger screens. This ensures <strong>optimal user
experience</strong> on all devices.</p>
<h3>Accessibility Matters</h3>
<p>Making websites accessible to everyone, including
people with disabilities. This is both a
<em>moral responsibility</em> and often a legal requirement.</p>
<h2>Conclusion</h2>
<p style="background-color: #e8f4f8; padding: 15px;">
The future of web design is <strong>user-centric</strong>,
<strong>accessible</strong>, and <strong>performant</strong>.
Staying current with these trends will keep your skills
relevant in the evolving tech landscape.
</p>
</body>
</html>
Step 3: Save and Open
- Save the file as
blog-post.html - Open it in your web browser
- Notice how the different heading levels create structure
- Observe the colored text and backgrounds
Step 4: Modify and Experiment
Edit your HTML to:
- Change the publication date to today’s date
- Add a new
<h3>subsection under “Key Trends” - Include at least one
<strong>tag and one<em>tag - Apply a background color to one paragraph
- Change the text color of the introduction paragraph
Save and refresh your browser to see changes.
Proper Heading Hierarchy Example
<!DOCTYPE html>
<html>
<head>
<title>Correct Heading Structure</title>
</head>
<body>
<h1>Company Website</h1>
<h2>Products</h2>
<h3>Software</h3>
<p>Description of software products...</p>
<h3>Hardware</h3>
<p>Description of hardware products...</p>
<h2>Services</h2>
<h3>Consulting</h3>
<p>Description of consulting services...</p>
</body>
</html>
Notice: h1 → h2 → h3 (proper order, no skipping)
Common Mistakes to Avoid
❌ Wrong: Using <h1> multiple times
<h1>Title 1</h1>
<h1>Title 2</h1>
✅ Right: Using heading hierarchy
<h1>Main Title</h1>
<h2>Section 1</h2>
<h2>Section 2</h2>
❌ Wrong: Using headings for styling
<h3 style="font-size: 50px;">This is not a real section</h3>
✅ Right: Using semantic headings
<h1 style="font-size: 50px;">This is a real main heading</h1>
Text Formatting Comparison
<!-- Semantic (preferred) -->
<p>This is <strong>very important</strong> information.</p>
<p>This is <em>emphasized</em> text.</p>
<!-- Non-semantic (just visual) -->
<p>This is <b>bold</b> text.</p>
<p>This is <i>italic</i> text.</p>
Browsers display <strong> and <b> as bold, and <em> and <i> as
italic. But semantic tags provide meaning to assistive technologies.
Challenge Exercise (Optional)
Create a blog post about a topic you’re interested in with:
- One main heading (
<h1>) - At least three section headings (
<h2>) - At least two subsections with
<h3>headings - Use
<strong>for important terms - Use
<em>for emphasized phrases - Apply at least two different text colors
- Apply at least one background color to a paragraph
- Ensure proper heading hierarchy (no skipping levels)
Key Takeaways
- Always use one
<h1>per page for the main title - Follow heading hierarchy: h1 → h2 → h3 (don’t skip levels)
- Use
<strong>and<em>for semantic text emphasis - Use
<b>and<i>for visual styling only - Apply colors with the
styleattribute:color: red; - Use hex codes, RGB, or color names for colors
- Proper structure makes content more accessible
References
- W3Schools HTML Headings
- W3Schools HTML Paragraphs
- W3Schools HTML Text Formatting
- W3Schools HTML Styles
- W3Schools HTML Colors
Chapter 3: HTML5 - Images, Links & Media
Learning Objectives
By the end of this chapter, you will be able to:
- Insert and format images in web pages
- Create internal and external hyperlinks
- Add a favicon to your website
- Embed videos and audio content
- Understand responsive design basics
- Build multi-page websites with navigation
Concept Introduction: Images & Links
Images add visual appeal and communicate information. Use the <img>
tag to display images on your page.
Links (hyperlinks) connect pages together and allow users to navigate.
Use the <a> tag to create clickable links to other pages or websites.
Responsive Images automatically adjust their size based on screen size, providing better user experience on mobile and desktop devices.
Learn more: W3Schools HTML Images and W3Schools HTML Links
The Image Tag
Insert images with the <img> tag:
<img src="image.jpg" alt="Description of image">
Important attributes:
src- Path to the image filealt- Alternative text (shown if image won’t load, used by screen readers)width- Image width in pixelsheight- Image height in pixels
Example:
<img src="cat.jpg" alt="A fluffy orange cat"
width="300" height="200">
Always include the alt attribute! It helps accessibility and SEO.
Learn more: W3Schools img Tag
The Anchor Tag for Links
Create links with the <a> tag:
<a href="url">Link text</a>
Types of links:
<!-- External link (to another website) -->
<a href="https://www.example.com">Visit Example</a>
<!-- Internal link (to another page on your site) -->
<a href="about.html">About Us</a>
<!-- Link to a file -->
<a href="document.pdf">Download PDF</a>
<!-- Email link -->
<a href="mailto:hello@example.com">Email Us</a>
<!-- Link with target="_blank" (opens in new tab) -->
<a href="https://www.example.com" target="_blank">
Open in new tab
</a>
Learn more: W3Schools Links
Favicons
A favicon is the small icon that appears in the browser tab. Add it
with a <link> tag in the <head>:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<!-- Content -->
</body>
</html>
Favicon formats: .ico, .png, .gif, .jpg
Learn more: W3Schools Favicon
Embedding Video
Embed videos using the HTML5 <video> tag:
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
Attributes:
width,height- Size of video playercontrols- Shows play/pause buttonsautoplay- Starts playing automaticallyloop- Repeats when finishedmuted- Starts without sound
Learn more: W3Schools Video
Embedding Audio
Embed audio using the HTML5 <audio> tag:
<audio controls>
<source src="song.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>
Learn more: W3Schools Audio
Step-by-Step Exercise: Build a Multi-Page Website
Step 1: Create Project Folder
Create a folder named my-website and inside it create:
index.html(home page)about.html(about page)portfolio.html(portfolio page)contact.html(contact page)
Step 2: Create index.html (Home Page)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>My Portfolio - Home</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<h1>Welcome to My Portfolio</h1>
<h2>Navigation</h2>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="portfolio.html">Portfolio</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
<h2>Latest Projects</h2>
<p>Check out my recent work and experience.</p>
<p><a href="portfolio.html">View My Portfolio →</a></p>
</body>
</html>
Step 3: Create about.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>My Portfolio - About</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<h1>About Me</h1>
<h2>Navigation</h2>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="portfolio.html">Portfolio</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
<h2>My Story</h2>
<p>I am a web design student learning to create amazing
websites. I have a passion for <strong>clean design</strong>
and <strong>user experience</strong>.</p>
<h2>Skills</h2>
<ul>
<li>HTML5</li>
<li>CSS3</li>
<li>Web Design</li>
<li>Responsive Design</li>
</ul>
<p><a href="contact.html">Get in touch →</a></p>
</body>
</html>
Step 4: Create portfolio.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>My Portfolio - Projects</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<h1>My Portfolio</h1>
<h2>Navigation</h2>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="portfolio.html">Portfolio</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
<h2>Project 1: Blog Website</h2>
<p>A modern blog built with clean HTML and responsive design.
</p>
<h2>Project 2: E-Commerce Site</h2>
<p>An online store with product listings and categories.
</p>
<h2>Project 3: Portfolio Site</h2>
<p>This very website showcasing my web design skills.
</p>
</body>
</html>
Step 5: Create contact.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>My Portfolio - Contact</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<h1>Contact Me</h1>
<h2>Navigation</h2>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="portfolio.html">Portfolio</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
<h2>Get in Touch</h2>
<p>I'd love to hear from you! Feel free to reach out.</p>
<p>Email: <a href="mailto:hello@example.com">
hello@example.com</a></p>
<p>Phone: <a href="tel:+1234567890">+1 (234) 567-8900</a></p>
</body>
</html>
Step 6: Test Navigation
- Open
index.htmlin your browser - Click each link in the Navigation section
- Verify you can navigate between all pages
- Use the back button to return to previous pages
- Open links in new tabs using Ctrl+Click (Cmd+Click on Mac)
Adding Images to Your Website
- Save an image file (JPG, PNG, GIF) in your
my-websitefolder - Add it to a page:
<h2>Sample Image</h2>
<img src="myimage.jpg" alt="Description of my image"
width="400">
- The
width="400"sets the width; height adjusts automatically
Common File Paths
<!-- File in same folder -->
<a href="page.html">Link</a>
<img src="image.jpg" alt="Image">
<!-- File in subfolder -->
<a href="pages/page.html">Link</a>
<img src="images/photo.jpg" alt="Photo">
<!-- Go up one folder level -->
<a href="../index.html">Home</a>
<!-- Absolute URL (external site) -->
<a href="https://www.example.com">External</a>
Semantic HTML for Navigation
Best practice: use <nav> and <ul> for navigation menus:
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/services">Services</a></li>
</ul>
</nav>
This provides better accessibility and semantic meaning.
Challenge Exercise (Optional)
Enhance your multi-page website:
- Add a
<nav>element with semantic navigation to all pages - Create an
imagessubfolder and add images to your pages - Add at least one image to the portfolio page
- Create an external link to your favorite website
- Add an email link:
<a href="mailto:your-email@example.com"> - Test all links work correctly
Key Takeaways
- Always include
alttext for images for accessibility - Use
<a href="">to create clickable links - Internal links use relative paths:
about.html - External links use full URLs:
https://example.com - Organize files in folders (images/, pages/, etc.)
- Test all links before publishing
- Use semantic
<nav>tags for navigation menus
References
- W3Schools HTML Images
- W3Schools HTML Links
- W3Schools HTML Favicon
- W3Schools HTML5 Video
- W3Schools HTML5 Audio
Chapter 4: HTML5 - Tables & Structured Data
Learning Objectives
By the end of this chapter, you will be able to:
- Build well-structured HTML tables with proper semantic elements
- Understand when and why to use tables
- Create tables with headers, body, and footer sections
- Organize tabular data semantically
- Style tables with basic attributes
Concept Introduction: Tables
Tables organize data into rows and columns for easy comparison and reference. Use tables for:
- Schedules and timetables
- Price comparisons
- Statistics and data
- Sports scores
- Product specifications
Don’t use tables for layout! Tables are for tabular data only. Use CSS for page layout instead.
Learn more: W3Schools HTML Tables
Table Elements & Structure
A table consists of:
<table>- Container for the entire table<thead>- Header section (column titles)<tbody>- Body section (data rows)<tfoot>- Footer section (summary rows)<tr>- Table row<th>- Table header cell<td>- Table data cell
Example:
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alice</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Bob</td>
<td>30</td>
<td>Los Angeles</td>
</tr>
</tbody>
</table>
Learn more: W3Schools Table Elements
Table Attributes
Common table attributes:
border- Adds borders around cells (1 for visible borders)cellpadding- Space inside cellscellspacing- Space between cellswidth- Table width in pixels or percentage
Example:
<table border="1" cellpadding="10" cellspacing="5" width="100%">
<!-- Table content -->
</table>
Learn more: W3Schools Table Attributes
Spanning Cells
Combine multiple cells using:
colspan- Span across multiple columnsrowspan- Span across multiple rows
Example:
<table border="1">
<tr>
<th colspan="2">Personal Information</th>
</tr>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td>John</td>
<td>28</td>
</tr>
</table>
Learn more: W3Schools Colspan & Rowspan
Step-by-Step Exercise: Create a Class Schedule
Step 1: Create schedule.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Class Schedule</title>
</head>
<body>
<h1>Weekly Class Schedule</h1>
<table border="1" cellpadding="10" cellspacing="5"
width="100%">
<thead>
<tr style="background-color: #4CAF50; color: white;">
<th>Time</th>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>9:00-10:00</strong></td>
<td>Math</td>
<td>English</td>
<td>Math</td>
<td>Science</td>
<td>History</td>
</tr>
<tr>
<td><strong>10:00-11:00</strong></td>
<td>English</td>
<td>Science</td>
<td>English</td>
<td>Math</td>
<td>PE</td>
</tr>
<tr>
<td><strong>11:00-12:00</strong></td>
<td>Science</td>
<td>Math</td>
<td>History</td>
<td>English</td>
<td>Art</td>
</tr>
<tr style="background-color: #f0f0f0;">
<td><strong>12:00-1:00</strong></td>
<td colspan="5" style="text-align: center;">
<em>Lunch Break</em>
</td>
</tr>
<tr>
<td><strong>1:00-2:00</strong></td>
<td>PE</td>
<td>Art</td>
<td>PE</td>
<td>History</td>
<td>Math</td>
</tr>
</tbody>
</table>
</body>
</html>
Step 2: Create a Price Comparison Table
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Pricing Comparison</title>
</head>
<body>
<h1>Web Hosting Plans</h1>
<table border="1" cellpadding="15" width="100%">
<thead>
<tr style="background-color: #2196F3; color: white;">
<th>Feature</th>
<th>Basic</th>
<th>Professional</th>
<th>Enterprise</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Storage</strong></td>
<td>10 GB</td>
<td>100 GB</td>
<td>Unlimited</td>
</tr>
<tr>
<td><strong>Bandwidth</strong></td>
<td>100 GB/month</td>
<td>1 TB/month</td>
<td>Unlimited</td>
</tr>
<tr>
<td><strong>Email Accounts</strong></td>
<td>5</td>
<td>25</td>
<td>Unlimited</td>
</tr>
<tr>
<td><strong>Support</strong></td>
<td>Email only</td>
<td>Email & Chat</td>
<td>24/7 Phone</td>
</tr>
<tr style="background-color: #fff3cd;">
<td><strong>Price/Month</strong></td>
<td style="color: green;"><strong>$9.99</strong></td>
<td style="color: green;"><strong>$19.99</strong></td>
<td style="color: green;"><strong>$49.99</strong></td>
</tr>
</tbody>
</table>
</body>
</html>
Step 3: Create a Sports Statistics Table
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Sports Statistics</title>
</head>
<body>
<h1>Basketball Team Statistics</h1>
<table border="1" cellpadding="10">
<thead>
<tr style="background-color: #FF9800; color: white;">
<th>Player</th>
<th>Games</th>
<th>Points</th>
<th>Assists</th>
<th>Rebounds</th>
</tr>
</thead>
<tbody>
<tr>
<td>James</td>
<td>20</td>
<td>425</td>
<td>78</td>
<td>156</td>
</tr>
<tr>
<td>Michael</td>
<td>20</td>
<td>380</td>
<td>92</td>
<td>134</td>
</tr>
<tr>
<td>David</td>
<td>19</td>
<td>298</td>
<td>145</td>
<td>98</td>
</tr>
</tbody>
<tfoot>
<tr style="background-color: #f0f0f0; font-weight: bold;">
<td>Team Totals</td>
<td>59</td>
<td>1103</td>
<td>315</td>
<td>388</td>
</tr>
</tfoot>
</table>
</body>
</html>
Best Practices for Tables
✅ Do’s
- Use
<thead>,<tbody>, and<tfoot>for semantic structure - Use
<th>for header cells (not<td>) - Use tables only for tabular data
- Add
border="1"for visibility - Use
cellpaddingfor spacing inside cells - Keep tables simple and readable
❌ Don’ts
- Don’t use tables for page layout
- Don’t use nested tables (except when absolutely necessary)
- Don’t forget header rows
- Don’t mix data types randomly
- Don’t make tables too wide for screens
- Don’t leave empty cells without explanation
Common Table Uses
| Purpose | When to Use |
|---|---|
| Schedule/Timetable | Time-based data with multiple days/times |
| Price Comparison | Comparing product features and prices |
| Statistics | Sports scores, research data, rankings |
| Results | Survey results, test scores |
| Directory | Lists of people with contact info |
| Specifications | Product or service details |
Accessibility in Tables
For better accessibility:
<table border="1">
<caption>Monthly Sales Report</caption>
<thead>
<tr>
<th scope="col">Product</th>
<th scope="col">Q1</th>
<th scope="col">Q2</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Widget A</th>
<td>$5000</td>
<td>$6000</td>
</tr>
</tbody>
</table>
<caption>- Describes the table purposescope="col"- Indicates column headersscope="row"- Indicates row headers
Learn more: W3Schools Table Captions
Challenge Exercise (Optional)
Create a data table for one of the following:
- Student Grades - Show students and their grades across subjects
- Product Inventory - Products with quantities and prices
- Weather Report - Daily forecast with temperature and conditions
- Work Experience - List jobs with dates, company, and responsibilities
Requirements:
- Use proper
<thead>,<tbody>,<tfoot>structure - Use
<th>for headers withscopeattributes - Add a
<caption>describing the table - Include at least one
colspanorrowspan - Style header rows with background colors
- Use
border,cellpadding, andcellspacing - Make sure data is clear and organized
Key Takeaways
- Tables organize data into rows and columns
- Use
<thead>,<tbody>, and<tfoot>for semantic structure <th>is for headers;<td>is for data- Use
colspanandrowspanto merge cells - Add
border="1"for visible table borders - Use
cellpaddingfor space inside cells - Tables are for data, NOT for page layout
- Add captions and scope attributes for accessibility
References
- W3Schools HTML Tables
- W3Schools Table Elements
- W3Schools Table Attributes
- W3Schools Colspan & Rowspan
- W3Schools Table Captions
Chapter 5: HTML5 - Forms & User Input
Learning Objectives
By the end of this chapter, you will be able to:
- Build accessible HTML forms with various input types
- Use appropriate input types for different data
- Create form controls (text, email, password, checkbox, radio, textarea)
- Understand form attributes and validation basics
- Test and validate forms for functionality
Concept Introduction: Forms
Forms collect information from users. Common uses include:
- Contact forms
- Login/registration
- Surveys and feedback
- Search bars
- Comment sections
- Checkout processes
Forms consist of input fields that capture user data and send it to a server for processing.
Learn more: W3Schools HTML Forms
The Form Element
Every form starts with the <form> tag:
<form action="/submit" method="POST">
<!-- Form fields go here -->
<button type="submit">Submit</button>
</form>
Attributes:
action- URL where form data is sentmethod- POST (sends data) or GET (adds to URL)name- Identifies the form
Learn more: W3Schools Form Tag
Input Types
HTML5 provides many input types for different data:
| Type | Purpose | Example |
|---|---|---|
text | Single-line text | Name, username |
email | Email address (with validation) | user@example.com |
password | Masked text | Secret passwords |
number | Numeric values | Age, quantity |
tel | Phone number | +1-234-567-8900 |
date | Date picker | YYYY-MM-DD |
time | Time picker | HH:MM |
checkbox | Multiple selections | Choose multiple options |
radio | Single selection | Choose one option |
submit | Submit button | Send form |
reset | Reset button | Clear form |
hidden | Hidden field | Internal data |
Learn more: W3Schools Input Types
Input Attributes
Common input attributes:
<input type="text"
name="username"
placeholder="Enter your username"
value="default text"
required>
name- Identifies the field when submittedplaceholder- Hint text shown in empty fieldvalue- Default valuerequired- Field must be filled before submitmaxlength- Maximum characters allowedminlength- Minimum characters required
Learn more: W3Schools Input Attributes
Form Elements
Text Input
<label for="username">Username:</label>
<input type="text" id="username" name="username"
placeholder="Enter username" required>
Email Input
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
Password Input
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
Textarea (Multi-line text)
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4"
cols="50"></textarea>
Checkbox (Multiple selections)
<label>
<input type="checkbox" name="agree">
I agree to the terms
</label>
Radio Buttons (Single selection)
<fieldset>
<legend>Choose your experience level:</legend>
<label>
<input type="radio" name="level" value="beginner">
Beginner
</label>
<label>
<input type="radio" name="level" value="intermediate">
Intermediate
</label>
<label>
<input type="radio" name="level" value="advanced">
Advanced
</label>
</fieldset>
Dropdown Select
<label for="country">Country:</label>
<select id="country" name="country">
<option value="">-- Select --</option>
<option value="usa">United States</option>
<option value="canada">Canada</option>
<option value="uk">United Kingdom</option>
</select>
Submit Button
<button type="submit">Submit Form</button>
Learn more: W3Schools Form Elements
Step-by-Step Exercise: Create a Contact Form
Step 1: Create contact.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Contact Form</title>
</head>
<body>
<h1>Contact Us</h1>
<p>Please fill out this form and we'll get back to you
soon!</p>
<form action="/submit" method="POST">
<fieldset>
<legend>Personal Information</legend>
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName"
required>
<br><br>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName"
required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone"
placeholder="+1-234-567-8900">
<br><br>
</fieldset>
<fieldset>
<legend>Message</legend>
<label for="subject">Subject:</label>
<select id="subject" name="subject">
<option value="">-- Select Subject --</option>
<option value="inquiry">General Inquiry</option>
<option value="support">Technical Support</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
<br><br>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="6"
cols="50" required></textarea>
<br><br>
</fieldset>
<fieldset>
<legend>Preferences</legend>
<label>
<input type="checkbox" name="newsletter">
Subscribe to our newsletter
</label>
<br>
<label>
<input type="checkbox" name="updates" checked>
Receive email updates
</label>
<br><br>
<fieldset>
<legend>How did you hear about us?</legend>
<label>
<input type="radio" name="source"
value="search" required>
Search Engine
</label>
<br>
<label>
<input type="radio" name="source" value="social">
Social Media
</label>
<br>
<label>
<input type="radio" name="source" value="friend">
Friend Referral
</label>
<br>
<label>
<input type="radio" name="source" value="other">
Other
</label>
</fieldset>
</fieldset>
<br>
<button type="submit">Send Message</button>
<button type="reset">Clear Form</button>
</form>
</body>
</html>
Step 2: Test the Form
- Save as
contact.html - Open in your browser
- Try submitting with empty fields (required fields should prevent submission)
- Try entering invalid email (email validation should reject it)
- Select checkboxes, radio buttons, and dropdowns
- Try the Reset button to clear the form
Step-by-Step Exercise: Create a Registration Form
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Registration Form</title>
</head>
<body>
<h1>Create Account</h1>
<form action="/register" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username"
minlength="3" maxlength="20" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"
minlength="8" required>
<br><br>
<label for="confirmPassword">Confirm Password:</label>
<input type="password" id="confirmPassword"
name="confirmPassword" minlength="8" required>
<br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="13"
max="120" required>
<br><br>
<label for="birthDate">Birth Date:</label>
<input type="date" id="birthDate" name="birthDate"
required>
<br><br>
<fieldset>
<legend>Gender</legend>
<label>
<input type="radio" name="gender" value="male">
Male
</label>
<label>
<input type="radio" name="gender" value="female">
Female
</label>
<label>
<input type="radio" name="gender" value="other">
Other
</label>
</fieldset>
<br>
<label>
<input type="checkbox" name="terms" required>
I agree to the Terms of Service
</label>
<br><br>
<button type="submit">Create Account</button>
</form>
</body>
</html>
Form Best Practices
✅ Do’s
- Use appropriate input types (email for email, number for numbers)
- Include
<label>tags for accessibility - Use
requiredfor essential fields - Provide helpful placeholder text
- Use
<fieldset>and<legend>to group related fields - Include a submit button
- Clear form instructions and validation messages
❌ Don’ts
- Don’t make forms too long (split across multiple pages if needed)
- Don’t force specific formats without clear instructions
- Don’t use ambiguous field names
- Don’t forget labels (screen readers need them)
- Don’t submit forms without validation
- Don’t store passwords as plain text
Form Validation
HTML5 provides built-in validation:
<!-- Email validation -->
<input type="email" required>
<!-- Number range validation -->
<input type="number" min="1" max="100" required>
<!-- Text length validation -->
<input type="text" minlength="3" maxlength="50" required>
<!-- Pattern validation (regex) -->
<input type="text" pattern="[0-9]{3}-[0-9]{4}"
title="Format: 123-4567" required>
Learn more: W3Schools Form Validation
Accessibility in Forms
<form>
<!-- Use label for every input -->
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" required>
<!-- Group related inputs with fieldset -->
<fieldset>
<legend>Contact Method</legend>
<label>
<input type="radio" name="contact" value="email">
Email
</label>
<label>
<input type="radio" name="contact" value="phone">
Phone
</label>
</fieldset>
<!-- Use descriptive button text -->
<button type="submit">Send Form</button>
</form>
Common Form Elements
| Element | Use Case |
|---|---|
<input type="text"> | Names, usernames, single-line text |
<input type="email"> | Email addresses |
<input type="password"> | Passwords, secrets |
<input type="number"> | Ages, quantities, scores |
<input type="date"> | Dates, birthdays |
<textarea> | Long messages, comments, feedback |
<select> | Dropdown lists, country selection |
<checkbox> | Multiple selections from options |
<radio> | Single selection from options |
Challenge Exercise (Optional)
Create a survey form with the following:
- At least 5 different input types (text, email, number, select, etc.)
- Use
<fieldset>and<legend>to organize questions - Include radio buttons for one question
- Include checkboxes for another question
- Add a textarea for comments
- Use
requiredon important fields - Add helpful placeholder text
- Include both Submit and Reset buttons
- Use proper
<label>tags for accessibility - Test the form in your browser
Key Takeaways
- Forms collect user input with the
<form>element - Use appropriate input types: email, number, password, etc.
- Always include
<label>tags for accessibility - Use
requiredto mark mandatory fields - Group related inputs with
<fieldset>and<legend> <checkbox>allows multiple selections<radio>buttons allow only one selection<textarea>is for multi-line text input- Test forms to verify validation works
- HTML5 provides basic client-side validation
References
- W3Schools HTML Forms
- W3Schools Form Input Types
- W3Schools Form Elements
- W3Schools Form Attributes
- W3Schools Form Validation
Chapter 6: HTML5 - Lists & Content Organization
Learning Objectives
By the end of this chapter, you will be able to:
- Use unordered lists for non-sequential information
- Use ordered lists for sequential or numbered information
- Create description lists for term-definition pairs
- Build nested lists for hierarchical content
- Use semantic list markup for navigation menus
- Organize content effectively with lists
Concept Introduction: Lists
Lists organize content in a structured way. HTML has three types of lists:
- Unordered lists - Items without specific order (bullets)
- Ordered lists - Numbered items in sequence
- Description lists - Terms with definitions
Lists make content scannable, accessible, and easier to understand.
Learn more: W3Schools HTML Lists
Unordered Lists
Unordered lists use the <ul> tag with <li> (list item) elements:
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
This displays as bullet points:
- First item
- Second item
- Third item
Learn more: W3Schools Unordered Lists
Ordered Lists
Ordered lists use the <ol> tag with <li> elements:
<ol>
<li>First step</li>
<li>Second step</li>
<li>Third step</li>
</ol>
This displays as numbered items:
- First step
- Second step
- Third step
Learn more: W3Schools Ordered Lists
Description Lists
Description lists pair terms with definitions using <dl>, <dt> (term),
and <dd> (definition):
<dl>
<dt>HTML</dt>
<dd>HyperText Markup Language - the standard markup
language for creating web pages.</dd>
<dt>CSS</dt>
<dd>Cascading Style Sheets - used to style HTML elements
and control layout and presentation.</dd>
<dt>JavaScript</dt>
<dd>A programming language that adds interactivity and
dynamic behavior to web pages.</dd>
</dl>
Learn more: W3Schools Description Lists
Nested Lists
Lists can contain other lists for hierarchical information:
<ul>
<li>Fruits
<ul>
<li>Apples</li>
<li>Oranges</li>
<li>Bananas</li>
</ul>
</li>
<li>Vegetables
<ul>
<li>Carrots</li>
<li>Broccoli</li>
<li>Spinach</li>
</ul>
</li>
</ul>
Learn more: W3Schools Nested Lists
List Attributes
Unordered List Styles
<!-- Disc (default) -->
<ul style="list-style-type: disc;">
<li>Item 1</li>
</ul>
<!-- Circle -->
<ul style="list-style-type: circle;">
<li>Item 1</li>
</ul>
<!-- Square -->
<ul style="list-style-type: square;">
<li>Item 1</li>
</ul>
<!-- None (no bullets) -->
<ul style="list-style-type: none;">
<li>Item 1</li>
</ul>
Ordered List Styles
<!-- 1, 2, 3 (default) -->
<ol style="list-style-type: decimal;">
<li>First</li>
</ol>
<!-- a, b, c (lowercase) -->
<ol style="list-style-type: lower-alpha;">
<li>First</li>
</ol>
<!-- A, B, C (uppercase) -->
<ol style="list-style-type: upper-alpha;">
<li>First</li>
</ol>
<!-- i, ii, iii (roman numerals) -->
<ol style="list-style-type: lower-roman;">
<li>First</li>
</ol>
Learn more: W3Schools List Style Types
Step-by-Step Exercise: Create a Product Catalog
Step 1: Create catalog.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Product Catalog</title>
</head>
<body>
<h1>Online Product Catalog</h1>
<h2>Our Products</h2>
<ul>
<li>Electronics
<ul>
<li>Laptops
<ul>
<li>Gaming Laptops</li>
<li>Business Laptops</li>
<li>Ultrabooks</li>
</ul>
</li>
<li>Smartphones</li>
<li>Tablets</li>
</ul>
</li>
<li>Home & Kitchen
<ul>
<li>Kitchen Appliances</li>
<li>Furniture</li>
<li>Decor</li>
</ul>
</li>
<li>Fashion
<ul>
<li>Men's Clothing</li>
<li>Women's Clothing</li>
<li>Shoes</li>
</ul>
</li>
</ul>
</body>
</html>
Step 2: Create course-syllabus.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Course Syllabus</title>
</head>
<body>
<h1>Web Design Course Syllabus</h1>
<h2>Course Overview</h2>
<p>Learn the fundamentals of web design and development
through practical hands-on exercises.</p>
<h2>Course Topics</h2>
<ol>
<li>Introduction to Web & HTML Basics</li>
<li>HTML5 - Headings, Paragraphs & Text Formatting</li>
<li>HTML5 - Images, Links & Media</li>
<li>HTML5 - Tables & Structured Data</li>
<li>HTML5 - Forms & User Input</li>
<li>HTML5 - Lists & Content Organization</li>
<li>CSS Basics - Selectors, Colors & Backgrounds</li>
<li>CSS Intermediate - Box Model & Typography</li>
<li>CSS Advanced - Effects & Animation</li>
<li>JavaScript Basics - Interactivity & Functionality</li>
</ol>
<h2>Course Requirements</h2>
<ul>
<li>Complete all 10 practical exercises</li>
<li>Create a final portfolio project</li>
<li>Participate in weekly code reviews</li>
<li>Pass the web design assessment</li>
</ul>
<h2>Grading Breakdown</h2>
<dl>
<dt>Participation</dt>
<dd>10% - Active engagement in class and discussions</dd>
<dt>Assignments</dt>
<dd>30% - Weekly practical exercises and coding tasks</dd>
<dt>Project Work</dt>
<dd>40% - Final portfolio project demonstrating all skills</dd>
<dt>Assessment</dt>
<dd>20% - Final web design technical assessment</dd>
</dl>
</body>
</html>
Step-by-Step Exercise: Create a Navigation Menu
Step 1: Create navigation-menu.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Website Navigation</title>
</head>
<body>
<h1>My Website</h1>
<nav>
<ul style="list-style-type: none;">
<li><a href="/">Home</a></li>
<li>
Products
<ul style="list-style-type: none;">
<li><a href="/products/electronics">Electronics</a></li>
<li><a href="/products/books">Books</a></li>
<li><a href="/products/clothing">Clothing</a></li>
</ul>
</li>
<li>
Services
<ul style="list-style-type: none;">
<li><a href="/services/consulting">Consulting</a></li>
<li><a href="/services/support">Support</a></li>
<li><a href="/services/training">Training</a></li>
</ul>
</li>
<li><a href="/about">About Us</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
<h2>Welcome</h2>
<p>Use the navigation menu above to explore our website.
</p>
</body>
</html>
Step-by-Step Exercise: Create a Recipe Instructions List
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Recipe</title>
</head>
<body>
<h1>Chocolate Chip Cookies Recipe</h1>
<h2>Ingredients</h2>
<ul>
<li>2 1/4 cups flour</li>
<li>1 tsp baking soda</li>
<li>1 tsp salt</li>
<li>1 cup butter, softened</li>
<li>3/4 cup sugar</li>
<li>3/4 cup brown sugar</li>
<li>2 eggs</li>
<li>2 tsp vanilla extract</li>
<li>2 cups chocolate chips</li>
</ul>
<h2>Instructions</h2>
<ol>
<li>Preheat oven to 375°F (190°C)</li>
<li>In a small bowl, combine flour, baking soda,
and salt</li>
<li>In a large bowl, beat butter and sugars until
creamy</li>
<li>Add eggs and vanilla extract to butter mixture</li>
<li>Gradually beat in flour mixture</li>
<li>Stir in chocolate chips</li>
<li>Drop rounded tablespoons onto ungreased baking sheets</li>
<li>Bake 9-11 minutes or until light brown</li>
<li>Cool on baking sheets for 2 minutes</li>
<li>Transfer to wire racks to cool completely</li>
</ol>
<h2>Tips</h2>
<ul>
<li>Don't overbake - cookies should be slightly soft
in the center</li>
<li>Use room temperature ingredients for best results</li>
<li>Mix in nuts (walnuts, pecans) for extra flavor</li>
</ul>
</body>
</html>
Best Practices for Lists
✅ Do’s
- Use
<ul>for unordered information - Use
<ol>for sequential or ranked information - Use
<li>for each list item - Use
<dl>,<dt>,<dd>for term-definition pairs - Use semantic
<nav>with<ul>for navigation - Use nested lists for hierarchical information
- Keep list items concise and parallel in structure
❌ Don’ts
- Don’t use lists for layout or spacing
- Don’t mix ordered and unordered lists unnecessarily
- Don’t create overly deep nesting (3+ levels is hard to follow)
- Don’t leave
<li>tags unclosed - Don’t use lists for content that isn’t list-like
- Don’t forget to use meaningful list content
Common List Uses
| Use Case | List Type | Example |
|---|---|---|
| Bullet points, features | Unordered <ul> | Product features, benefits |
| Steps, instructions, ranking | Ordered <ol> | Recipes, rankings, tutorials |
| Glossary, definitions | Description <dl> | Terms and definitions |
| Navigation menu | Unordered <ul> with semantic <nav> | Site navigation |
| Categories with subcategories | Nested list | Product catalog |
| Pros and cons | Unordered <ul> | Comparison lists |
Accessibility in Lists
<!-- Good: Semantic navigation with list -->
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
<!-- Good: Using description lists -->
<dl>
<dt>Term</dt>
<dd>Definition</dd>
</dl>
<!-- Good: Nested lists for hierarchy -->
<ul>
<li>Category
<ul>
<li>Subcategory</li>
</ul>
</li>
</ul>
Screen readers and assistive technologies handle lists well when they’re properly structured and semantic.
List Styling Examples
Changing Bullet Styles
<!-- Remove bullets for navigation -->
<ul style="list-style-type: none;">
<li><a href="/">Link</a></li>
</ul>
<!-- Use squares instead of circles -->
<ul style="list-style-type: square;">
<li>Item</li>
</ul>
Changing Number Styles
<!-- Roman numerals -->
<ol style="list-style-type: upper-roman;">
<li>First</li>
</ol>
<!-- Lowercase letters -->
<ol style="list-style-type: lower-alpha;">
<li>First</li>
</ol>
Challenge Exercise (Optional)
Create a comprehensive content organization page with:
- Main navigation menu using semantic
<nav>and<ul> - Product categories using nested unordered lists
- Numbered steps or instructions using ordered list
- Glossary section using description list
<dl> - Features list using unordered list
- FAQ section organized with description lists or headings
- At least one nested list with 3 levels
- Use different
list-style-typevalues for variety - Include at least 20 list items across all lists
- Test navigation links and verify structure is semantic
Key Takeaways
<ul>for unordered bullet lists<ol>for ordered numbered lists<li>for each list item in both<dl>,<dt>,<dd>for term-definition pairs- Nested lists show hierarchical relationships
- Use semantic
<nav>with<ul>for navigation - Remove bullets with
list-style-type: none;for navigation - Lists improve accessibility and scannability
- Keep list items parallel and concise
- Test navigation and links in your lists
References
- W3Schools HTML Lists
- W3Schools Unordered Lists
- W3Schools Ordered Lists
- W3Schools Description Lists
- W3Schools Nested Lists
- W3Schools List Attributes
Chapter 7: CSS Basics - Selectors, Colors & Backgrounds
Learning Objectives
By the end of this chapter, you will be able to:
- Write valid CSS syntax and understand the cascade
- Use CSS selectors (element, class, ID, attribute)
- Apply colors using different color formats
- Add background colors and images
- Link external stylesheets to HTML
- Validate CSS code
Concept Introduction: What is CSS?
CSS (Cascading Style Sheets) controls the presentation and layout of web pages. While HTML provides structure, CSS provides styling:
- Colors and backgrounds
- Fonts and text formatting
- Layout and spacing
- Borders and shadows
- Animations and transitions
CSS works by selecting HTML elements and applying style rules to them.
Learn more: W3Schools CSS Introduction
CSS Syntax
A CSS rule consists of a selector and a declaration block:
selector {
property: value;
property: value;
}
Example:
p {
color: blue;
font-size: 16px;
}
- Selector - Which HTML element to style (
p) - Property - What to change (
color,font-size) - Value - New value for the property (
blue,16px)
Learn more: W3Schools CSS Syntax
CSS Selectors
Element Selector
Selects all elements of a specific type:
p {
color: red;
}
h1 {
font-size: 32px;
}
Learn more: W3Schools Element Selector
Class Selector
Selects elements with a specific class (starts with .):
.main-container {
width: 800px;
}
.highlight {
background-color: yellow;
}
HTML:
<div class="main-container">Content</div>
<p class="highlight">Important text</p>
Learn more: W3Schools Class Selector
ID Selector
Selects the element with a specific ID (starts with #):
#header {
background-color: navy;
}
#main-content {
padding: 20px;
}
HTML:
<header id="header">Header content</header>
<main id="main-content">Main content</main>
Note: Each ID should be unique on a page. Use classes for multiple elements with the same style.
Learn more: W3Schools ID Selector
Attribute Selector
Selects elements with specific attributes:
/* Select all links */
a[href] {
color: blue;
}
/* Select inputs of type email */
input[type="email"] {
border: 1px solid gray;
}
/* Select elements with title attribute */
[title] {
cursor: help;
}
Learn more: W3Schools Attribute Selector
Selector Specificity
When multiple CSS rules apply, the most specific selector wins:
/* Element selector (lowest specificity) */
p { color: black; }
/* Class selector (higher specificity) */
.highlight { color: yellow; }
/* ID selector (highest specificity) */
#main { color: red; }
If an element has all three, the ID selector color (red) applies.
Learn more: W3Schools CSS Specificity
Colors in CSS
Color Formats
Named Colors
p { color: red; }
h1 { background-color: navy; }
Hex Colors
p { color: #FF0000; } /* Red */
h1 { color: #0000FF; } /* Blue */
button { color: #00AA00; } /* Green */
RGB Colors
p { color: rgb(255, 0, 0); } /* Red */
h1 { color: rgb(0, 0, 255); } /* Blue */
div { background-color: rgb(100, 150, 200); }
RGBA Colors (with transparency)
p { color: rgba(255, 0, 0, 0.5); } /* Red with 50% opacity */
div { background-color: rgba(0, 0, 255, 0.7); }
Learn more: W3Schools Colors
Text and Background Colors
/* Text color */
p {
color: white;
}
/* Background color */
body {
background-color: #f0f0f0;
}
/* Combined */
.warning {
color: white;
background-color: red;
padding: 10px;
}
Background Images
Add background images to elements:
body {
background-image: url('background.jpg');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
.hero {
background-image: url('hero.png');
background-size: 100% 100%;
}
Background properties:
background-image- URL of the imagebackground-size- How to size the image (cover, contain, 100% 100%)background-position- Where to position the image (center, top, etc.)background-repeat- Repeat pattern (repeat, no-repeat, repeat-x, repeat-y)background-color- Fallback color if image fails
Learn more: W3Schools Backgrounds
External Stylesheets
Create a separate .css file and link it in the HTML <head>:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>My Website</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- Content -->
</body>
</html>
The <link> tag has these attributes:
rel="stylesheet"- Indicates it’s a stylesheethref="style.css"- Path to the CSS file
Step-by-Step Exercise: Create a Styled Website
Step 1: Create the HTML File (index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Styled Website</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header id="site-header">
<h1>My Awesome Website</h1>
<p>Welcome to my online portfolio</p>
</header>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<main>
<section class="intro">
<h2>About This Site</h2>
<p>This website demonstrates CSS selectors, colors,
and styling with an external stylesheet.</p>
</section>
<section class="features">
<h2>Key Features</h2>
<div class="feature-box">
<h3>Modern Design</h3>
<p>Clean and contemporary design principles.</p>
</div>
<div class="feature-box">
<h3>Responsive Layout</h3>
<p>Works well on different screen sizes.</p>
</div>
<div class="feature-box">
<h3>Easy to Maintain</h3>
<p>Simple structure with organized CSS.</p>
</div>
</section>
<section class="cta">
<h2>Get Started</h2>
<p>Ready to learn more? Contact us today!</p>
<a href="#contact" class="btn">Contact Us</a>
</section>
</main>
<footer id="site-footer">
<p>© 2025 My Awesome Website. All rights reserved.
</p>
</footer>
</body>
</html>
Step 2: Create the CSS File (style.css)
/* Global styles */
body {
background-color: #f5f5f5;
color: #333;
font-family: Arial, sans-serif;
}
/* Header styles */
#site-header {
background-color: #2c3e50;
color: white;
padding: 40px 20px;
text-align: center;
}
#site-header h1 {
margin: 0;
font-size: 36px;
}
#site-header p {
margin: 10px 0 0 0;
font-size: 18px;
}
/* Navigation styles */
nav {
background-color: #34495e;
padding: 0;
}
nav ul {
list-style-type: none;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
}
nav ul li {
margin: 0;
}
nav ul li a {
color: white;
text-decoration: none;
padding: 15px 20px;
display: block;
}
nav ul li a:hover {
background-color: #2c3e50;
}
/* Main content */
main {
max-width: 1000px;
margin: 40px auto;
padding: 0 20px;
}
/* Section styles */
.intro {
background-color: white;
padding: 30px;
border-radius: 5px;
margin-bottom: 40px;
}
.intro h2 {
color: #2c3e50;
}
/* Features section */
.features {
margin-bottom: 40px;
}
.features h2 {
color: #2c3e50;
text-align: center;
}
.feature-box {
background-color: white;
padding: 20px;
margin: 15px 0;
border-left: 4px solid #3498db;
border-radius: 3px;
}
.feature-box h3 {
color: #3498db;
margin-top: 0;
}
/* Call-to-action section */
.cta {
background-color: #3498db;
color: white;
padding: 40px;
text-align: center;
border-radius: 5px;
margin-bottom: 40px;
}
.cta h2 {
color: white;
margin-top: 0;
}
/* Button styles */
.btn {
display: inline-block;
background-color: #2c3e50;
color: white;
padding: 12px 30px;
text-decoration: none;
border-radius: 3px;
margin-top: 10px;
}
.btn:hover {
background-color: #1a252f;
}
/* Footer */
#site-footer {
background-color: #2c3e50;
color: white;
text-align: center;
padding: 20px;
margin-top: 40px;
}
Step 3: Save and Test
- Save the HTML as
index.html - Save the CSS as
style.cssin the same folder - Open
index.htmlin your browser - Verify that:
- Header has dark background with white text
- Navigation bar is styled with hover effects
- Feature boxes have left blue border
- Button has hover effect
- Footer is styled consistently
Step 4: Modify and Experiment
Edit style.css to:
- Change the header background color to a different hex code
- Change the feature box border color using RGB
- Add a background color to the body using a color name
- Change text colors for better contrast
- Add padding or margins to different sections
- Save and refresh browser (F5) to see changes
Color Tools and Resources
Use these tools to pick colors:
CSS Validation
Validate your CSS to catch errors:
- Visit W3C CSS Validator
- Upload your CSS file or paste the code
- Click “Check”
- Fix any errors or warnings
Selector Comparison
| Selector | Syntax | Specificity | Use Case |
|---|---|---|---|
| Element | p | Low | Style all elements of type |
| Class | .classname | Medium | Style multiple elements |
| ID | #idname | High | Style one unique element |
| Attribute | [attr="value"] | Medium | Style by attribute |
Best Practices
✅ Do’s
- Use external stylesheets for all CSS
- Use meaningful class and ID names
- Use classes more than IDs (IDs should be unique)
- Keep CSS organized and readable
- Use color names for common colors, hex for specific colors
- Test on multiple browsers
- Comment your CSS for complex rules
❌ Don’ts
- Don’t use inline styles (use external CSS instead)
- Don’t use
!importantunless absolutely necessary - Don’t use too many different colors (keep consistent)
- Don’t forget the
<link>tag in your HTML head - Don’t mix too many font sizes
- Don’t use low-contrast colors for readability
Challenge Exercise (Optional)
Create a website with CSS styling that includes:
- External stylesheet linked in HTML head
- Use at least 5 different CSS selectors (element, class, ID, attribute)
- Apply colors using three different formats (named, hex, RGB)
- At least two sections with
background-color - A hover effect on at least one element
- Proper spacing with padding and margins
- At least 3 different colors in your color scheme
- A header and footer with distinct backgrounds
- Comments in your CSS explaining sections
- Validate your CSS with the W3C validator
Key Takeaways
- CSS selectors target HTML elements for styling
- Element selectors style all elements of a type
- Class selectors (
.class) style multiple elements - ID selectors (
#id) style one unique element - Use
colorfor text color andbackground-colorfor backgrounds - Hex codes (
#FF0000), RGB (rgb(255,0,0)), and names (red) all work - Link external stylesheets with
<link rel="stylesheet" href="style.css"> - Specificity determines which rule applies when there are conflicts
- Always validate your CSS code
- External CSS is better than inline styles
References
- W3Schools CSS Introduction
- W3Schools CSS Syntax
- W3Schools CSS Selectors
- W3Schools CSS Colors
- W3Schools CSS Backgrounds
- W3C CSS Validator
Chapter 8: CSS Intermediate - Box Model & Typography
Learning Objectives
By the end of this chapter, you will be able to:
- Understand and apply the CSS box model
- Use borders, margins, and padding effectively
- Control element width and height
- Master typography: fonts, sizes, weights, and styles
- Create visual hierarchy with typography
- Build consistent layouts using the box model
Concept Introduction: The Box Model
Every HTML element is a box. The CSS box model defines the space around and within elements:
- Content - The actual content (text, images)
- Padding - Space inside the box, around content
- Border - Line around the padding
- Margin - Space outside the box, between elements
Understanding the box model is essential for controlling layout and spacing.
Learn more: W3Schools Box Model
Box Model Diagram
┌─────────────────────────────────────┐
│ Margin (outside) │
│ ┌───────────────────────────────┐ │
│ │ Border (edge) │ │
│ │ ┌─────────────────────────┐ │ │
│ │ │ Padding (inside space) │ │ │
│ │ │ ┌─────────────────┐ │ │ │
│ │ │ │ Content │ │ │ │
│ │ │ └─────────────────┘ │ │ │
│ │ └─────────────────────────┘ │ │
│ └───────────────────────────────┘ │
└─────────────────────────────────────┘
Padding
Padding is space inside the element, around the content:
/* All sides */
p {
padding: 20px;
}
/* Top & bottom, left & right */
p {
padding: 10px 20px;
}
/* Top, right, bottom, left */
p {
padding: 10px 15px 10px 15px;
}
/* Individual sides */
p {
padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 15px;
}
Learn more: W3Schools Padding
Borders
Borders are lines around elements:
/* Basic border */
p {
border: 1px solid black;
}
/* Border syntax: width style color */
div {
border: 2px dashed blue;
}
/* Border styles: solid, dashed, dotted, double, groove, ridge */
p {
border: 3px dotted red;
}
/* Individual borders */
box {
border-top: 1px solid black;
border-right: 2px solid blue;
border-bottom: 1px solid black;
border-left: 2px solid blue;
}
/* Border radius (rounded corners) */
.card {
border: 1px solid #ccc;
border-radius: 8px;
}
Border properties:
border-width- 1px, 2px, 3px, etc.border-style- solid, dashed, dotted, double, etc.border-color- color valueborder-radius- Rounded corners
Learn more: W3Schools Borders
Margins
Margins are space outside elements, between them:
/* All sides */
p {
margin: 20px;
}
/* Top & bottom, left & right */
p {
margin: 10px 20px;
}
/* Top, right, bottom, left */
p {
margin: 10px 15px 10px 15px;
}
/* Individual sides */
p {
margin-top: 10px;
margin-right: 15px;
margin-bottom: 10px;
margin-left: 15px;
}
/* Auto margins (center element) */
.container {
width: 800px;
margin: 0 auto;
}
Learn more: W3Schools Margins
Width and Height
Control element dimensions:
/* Fixed width and height */
.box {
width: 300px;
height: 200px;
}
/* Percentage width */
.container {
width: 100%;
max-width: 1000px;
}
/* Min and max dimensions */
.sidebar {
min-width: 200px;
max-width: 400px;
}
/* Auto height (content-based) */
.content {
height: auto;
}
Units:
px- Pixels (fixed size)%- Percentage of parentem- Relative to font sizerem- Relative to root font sizeauto- Let browser calculate
Learn more: W3Schools Width & Height
Typography: Fonts
Font Family
/* Specific font */
body {
font-family: "Helvetica Neue", Arial, sans-serif;
}
/* Web-safe font stacks */
p {
font-family: Georgia, serif;
}
h1 {
font-family: "Courier New", monospace;
}
/* Generic families (fallback) */
.text {
font-family: Arial, sans-serif;
}
Common font families:
Arial, sans-serif- Clean, modernGeorgia, serif- Traditional, readable"Courier New", monospace- Code-like, fixed width"Times New Roman", serif- Classic
Learn more: W3Schools Fonts
Font Size
/* Pixel size (fixed) */
p {
font-size: 16px;
}
h1 {
font-size: 32px;
}
/* Relative units */
.small {
font-size: 0.875em; /* 87.5% of parent */
}
.large {
font-size: 1.5rem; /* 1.5x of root font size */
}
/* Percentage */
.text {
font-size: 120%;
}
Best practices: Use 16px as base, scale other sizes proportionally.
Font Weight
/* Named values */
p {
font-weight: normal; /* 400 */
}
strong {
font-weight: bold; /* 700 */
}
/* Numeric values */
.light {
font-weight: 300; /* Light */
}
.regular {
font-weight: 400; /* Normal */
}
.semibold {
font-weight: 600; /* Semi-bold */
}
.bold {
font-weight: 700; /* Bold */
}
Learn more: W3Schools Font Weight
Font Style
/* Normal (default) */
p {
font-style: normal;
}
/* Italic */
em, .italic {
font-style: italic;
}
/* Oblique (similar to italic) */
.oblique {
font-style: oblique;
}
Typography: Line Height and Letter Spacing
/* Line height (space between lines) */
p {
line-height: 1.6; /* 1.6x font size */
}
.compact {
line-height: 1.2;
}
.spacious {
line-height: 2;
}
/* Letter spacing (space between characters) */
h1 {
letter-spacing: 2px;
}
.tight {
letter-spacing: -1px;
}
Good readability:
- Line height: 1.5 to 1.8 for body text
- Letter spacing: -1px to 2px for headings
Learn more: W3Schools Line Height
Step-by-Step Exercise: Create a Card Component Layout
Step 1: Create card-layout.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Card Layout</title>
<link rel="stylesheet" href="cards.css">
</head>
<body>
<h1>Product Cards</h1>
<div class="cards-container">
<div class="card">
<h2>Laptop</h2>
<p>High-performance computing device for work
and entertainment.</p>
<p class="price">$999.99</p>
<button class="btn">Learn More</button>
</div>
<div class="card">
<h2>Smartphone</h2>
<p>Latest mobile device with advanced features
and fast processor.</p>
<p class="price">$599.99</p>
<button class="btn">Learn More</button>
</div>
<div class="card">
<h2>Tablet</h2>
<p>Portable device perfect for reading, drawing,
and browsing.</p>
<p class="price">$399.99</p>
<button class="btn">Learn More</button>
</div>
</div>
</body>
</html>
Step 2: Create cards.css
/* Global styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #f0f0f0;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
font-size: 16px;
line-height: 1.6;
color: #333;
padding: 20px;
}
h1 {
text-align: center;
margin-bottom: 40px;
font-size: 32px;
font-weight: 700;
letter-spacing: 1px;
}
/* Container for cards */
.cards-container {
max-width: 1200px;
margin: 0 auto;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
/* Card styles */
.card {
background-color: white;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
/* Card heading */
.card h2 {
font-size: 24px;
font-weight: 600;
margin-bottom: 15px;
color: #2c3e50;
}
/* Card paragraph */
.card p {
font-size: 14px;
line-height: 1.8;
margin-bottom: 15px;
color: #555;
}
/* Price styling */
.card .price {
font-size: 20px;
font-weight: 700;
color: #27ae60;
margin: 15px 0;
}
/* Button styling */
.btn {
background-color: #3498db;
color: white;
border: none;
padding: 10px 20px;
font-size: 14px;
font-weight: 600;
border-radius: 4px;
cursor: pointer;
width: 100%;
margin-top: 10px;
transition: background-color 0.3s ease;
}
.btn:hover {
background-color: #2980b9;
}
/* Box sizing for all elements */
* {
box-sizing: border-box;
}
Step 3: Test and Modify
-
Save HTML as
card-layout.html -
Save CSS as
cards.css -
Open in browser and verify:
- Cards have proper padding and borders
- Cards are responsive (stack on mobile)
- Hover effects work
- Button is full width with padding
-
Try modifying:
- Change
border-radiusvalues - Adjust padding and margins
- Change font sizes and weights
- Modify colors
- Change
Step-by-Step Exercise: Create a Typography Showcase
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Typography</title>
<link rel="stylesheet" href="typography.css">
</head>
<body>
<h1>Typography Showcase</h1>
<section class="typography-section">
<h2>Headings</h2>
<h1>Heading 1 (32px, Bold)</h1>
<h2>Heading 2 (28px, Bold)</h2>
<h3>Heading 3 (24px, Semi-bold)</h3>
<h4>Heading 4 (20px, Semi-bold)</h4>
</section>
<section class="typography-section">
<h2>Body Text</h2>
<p class="body-text">
This is regular body text at 16px with a line height of 1.6.
It provides good readability for longer passages. The generous
spacing between lines makes it comfortable to read on screen.
</p>
</section>
<section class="typography-section">
<h2>Font Weights</h2>
<p class="light">This text is 300 (Light)</p>
<p class="regular">This text is 400 (Regular)</p>
<p class="semibold">This text is 600 (Semi-bold)</p>
<p class="bold">This text is 700 (Bold)</p>
</section>
<section class="typography-section">
<h2>Spacing Examples</h2>
<p class="tight-spacing">
This paragraph has tight letter spacing for a compact look.
</p>
<p class="normal-spacing">
This paragraph has normal letter spacing.
</p>
<p class="loose-spacing">
This paragraph has loose letter spacing for emphasis.
</p>
</section>
</body>
</html>
CSS for Typography Showcase:
body {
max-width: 800px;
margin: 0 auto;
padding: 40px 20px;
font-family: Georgia, serif;
background-color: #fafafa;
}
h1 {
font-size: 32px;
font-weight: 700;
margin-bottom: 30px;
text-align: center;
}
.typography-section {
background-color: white;
padding: 30px;
margin-bottom: 20px;
border-radius: 4px;
border-left: 4px solid #3498db;
}
.typography-section h2 {
font-size: 24px;
font-weight: 600;
margin-bottom: 20px;
color: #2c3e50;
}
h3 {
font-size: 24px;
font-weight: 600;
}
h4 {
font-size: 20px;
font-weight: 600;
}
.body-text {
font-size: 16px;
line-height: 1.8;
color: #555;
}
.light {
font-weight: 300;
}
.regular {
font-weight: 400;
}
.semibold {
font-weight: 600;
}
.bold {
font-weight: 700;
}
.tight-spacing {
letter-spacing: -0.5px;
}
.normal-spacing {
letter-spacing: 0;
}
.loose-spacing {
letter-spacing: 2px;
}
Box Model Properties Summary
| Property | Purpose | Example |
|---|---|---|
padding | Inner space | padding: 20px; |
border | Edge line | border: 1px solid black; |
margin | Outer space | margin: 10px; |
width | Element width | width: 300px; |
height | Element height | height: 200px; |
box-sizing | Include padding/border in width | box-sizing: border-box; |
Typography Properties Summary
| Property | Purpose | Example |
|---|---|---|
font-family | Font type | font-family: Arial, sans-serif; |
font-size | Text size | font-size: 16px; |
font-weight | Text thickness | font-weight: 700; |
font-style | Italic/normal | font-style: italic; |
line-height | Line spacing | line-height: 1.6; |
letter-spacing | Character spacing | letter-spacing: 1px; |
text-align | Alignment | text-align: center; |
Best Practices
✅ Do’s
- Use
box-sizing: border-box;for predictable sizing - Use relative units (em, rem) for scalable designs
- Keep line height between 1.5 and 1.8 for readability
- Use consistent spacing (padding/margin ratios)
- Limit font families to 2-3 for consistency
- Test typography at multiple screen sizes
- Use font weights strategically for hierarchy
❌ Don’ts
- Don’t use padding on
<body>for layout - Don’t set extreme font sizes
- Don’t use too many different font families
- Don’t forget margin/padding reset for consistency
- Don’t use line-height less than 1.4
- Don’t use all caps for body text (hard to read)
Challenge Exercise (Optional)
Create a blog post layout with:
- A header section with title and metadata
- Multiple paragraphs with consistent line height
- Headings with proper hierarchy and spacing
- At least 3 font sizes for different elements
- Use padding and margins for visual spacing
- Add borders and background colors to highlight sections
- Create a sidebar with different typography
- Use
box-sizing: border-box;globally - Implement font weights for emphasis
- Ensure good readability with proper spacing
Key Takeaways
- The box model: content → padding → border → margin
- Padding is inside space; margins are outside space
- Borders wrap around padding
- Use
box-sizing: border-box;to include padding/border in width font-familyspecifies the typefacefont-sizeshould be readable (14-16px for body)line-heightaffects readability (1.5-1.8 recommended)letter-spacingcontrols character spacing- Consistent typography improves design
- Test layouts at multiple screen sizes
References
- W3Schools Box Model
- W3Schools Padding
- W3Schools Borders
- W3Schools Margins
- W3Schools Width & Height
- W3Schools Fonts
- W3Schools Font Weight
- W3Schools Line Height
Chapter 9: CSS Advanced - Effects & Animation
Learning Objectives
By the end of this chapter, you will be able to:
- Apply CSS transitions for smooth state changes
- Use CSS transforms to manipulate elements
- Create animations with keyframes
- Style lists and tables with CSS
- Add hover effects and interactivity
- Enhance user experience with motion and effects
Concept Introduction: Effects & Animation
Effects and animations add polish and interactivity to web pages. They improve user experience by providing visual feedback and guiding attention. CSS provides powerful tools without needing JavaScript:
- Transitions - Smooth changes between states
- Transforms - Rotate, scale, skew, translate elements
- Animations - Complex sequences with keyframes
Learn more: W3Schools CSS Transitions
CSS Transitions
Transitions smoothly animate changes from one property value to another:
/* Basic transition */
button {
background-color: blue;
transition: background-color 0.3s ease;
}
button:hover {
background-color: darkblue;
}
Transition properties:
transition-property- Which property to animatetransition-duration- How long the animation takes (ms or s)transition-timing-function- How animation progressestransition-delay- Delay before animation starts
/* Individual properties */
div {
transition-property: background-color;
transition-duration: 0.5s;
transition-timing-function: ease-in;
transition-delay: 0.2s;
}
/* Shorthand */
div {
transition: background-color 0.5s ease-in 0.2s;
}
/* Animate multiple properties */
div {
transition: background-color 0.3s, color 0.3s, transform 0.3s;
}
/* Animate all properties */
div {
transition: all 0.3s ease;
}
Timing functions:
linear- Constant speedease- Slow start and endease-in- Slow startease-out- Slow endease-in-out- Slow start and end
Learn more: W3Schools Transitions
CSS Transforms
Transforms change the shape and position of elements:
Translate (Move)
/* Move element 50px right and 30px down */
.box {
transform: translate(50px, 30px);
}
/* Move only horizontally */
.box {
transform: translateX(50px);
}
/* Move only vertically */
.box {
transform: translateY(30px);
}
Scale (Resize)
/* Scale uniformly */
.box {
transform: scale(1.5); /* 150% size */
}
/* Scale differently */
.box {
transform: scale(1.2, 0.8); /* 120% width, 80% height */
}
/* Scale only width */
.box {
transform: scaleX(2);
}
/* Scale only height */
.box {
transform: scaleY(0.5);
}
Rotate (Spin)
/* Rotate 45 degrees clockwise */
.box {
transform: rotate(45deg);
}
/* Rotate counter-clockwise */
.box {
transform: rotate(-45deg);
}
/* Rotate only around X axis */
.box {
transform: rotateX(45deg);
}
/* Rotate only around Y axis */
.box {
transform: rotateY(45deg);
}
Skew (Distort)
/* Skew on both axes */
.box {
transform: skew(20deg, 10deg);
}
/* Skew only horizontally */
.box {
transform: skewX(20deg);
}
/* Skew only vertically */
.box {
transform: skewY(10deg);
}
Combine Transforms
/* Multiple transforms */
.box {
transform: translate(50px, 30px) rotate(45deg) scale(1.2);
}
Learn more: W3Schools Transforms
CSS Animations
Animations create complex sequences using keyframes:
/* Define animation keyframes */
@keyframes slide-in {
0% {
opacity: 0;
transform: translateX(-100px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
/* Apply animation */
.box {
animation: slide-in 0.5s ease-out;
}
Animation properties:
animation-name- Name of the keyframe animationanimation-duration- How long animation takesanimation-timing-function- Animation pacinganimation-delay- Delay before startinganimation-iteration-count- How many times to repeatanimation-direction- Forward, backward, alternateanimation-fill-mode- How element looks before/after
/* Individual properties */
.box {
animation-name: slide-in;
animation-duration: 1s;
animation-timing-function: ease-in-out;
animation-delay: 0.2s;
animation-iteration-count: infinite;
animation-direction: alternate;
}
/* Shorthand */
.box {
animation: slide-in 1s ease-in-out 0.2s infinite alternate;
}
Animation fill modes:
none- Return to original stateforwards- Keep final keyframe statebackwards- Apply initial keyframe before delayboth- Apply both forwards and backwards
Learn more: W3Schools Animations
Hover Effects
Create interactive effects on hover:
/* Button hover effect */
button {
background-color: #3498db;
transition: all 0.3s ease;
}
button:hover {
background-color: #2980b9;
transform: scale(1.05);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
/* Link hover effect */
a {
color: #3498db;
text-decoration: none;
border-bottom: 2px solid transparent;
transition: border-color 0.3s ease;
}
a:hover {
border-bottom: 2px solid #3498db;
}
/* Card hover effect */
.card {
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}
Learn more: W3Schools Hover
List Styling
Style lists with CSS:
/* Remove bullet points */
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
/* Custom list styling */
ul li {
padding: 10px;
border-bottom: 1px solid #eee;
}
/* Add custom content before items */
ul li:before {
content: "→ ";
color: #3498db;
font-weight: bold;
margin-right: 10px;
}
/* Alternate row colors */
ul li:nth-child(odd) {
background-color: #f9f9f9;
}
/* Hover effect on list items */
ul li {
transition: background-color 0.3s ease;
}
ul li:hover {
background-color: #e8f4f8;
}
Learn more: W3Schools List Styling
Table Styling
Style tables for better appearance and readability:
/* Table styling */
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
/* Table header */
thead {
background-color: #2c3e50;
color: white;
}
/* Table headers and cells */
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
/* Striped table (alternating rows) */
tbody tr:nth-child(even) {
background-color: #f9f9f9;
}
/* Hover effect on rows */
tbody tr:hover {
background-color: #e8f4f8;
transition: background-color 0.3s ease;
}
/* Footer styling */
tfoot {
font-weight: bold;
background-color: #ecf0f1;
}
Learn more: W3Schools Table Styling
Step-by-Step Exercise: Create an Interactive Button Gallery
Step 1: Create buttons.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Interactive Buttons</title>
<link rel="stylesheet" href="buttons.css">
</head>
<body>
<h1>Interactive Button Gallery</h1>
<div class="button-container">
<button class="btn btn-primary">Primary Button</button>
<button class="btn btn-success">Success Button</button>
<button class="btn btn-warning">Warning Button</button>
<button class="btn btn-danger">Danger Button</button>
</div>
<div class="button-container">
<button class="btn btn-scale">Scale on Hover</button>
<button class="btn btn-rotate">Rotate on Hover</button>
<button class="btn btn-bounce">Bounce Animation</button>
<button class="btn btn-glow">Glow Effect</button>
</div>
</body>
</html>
Step 2: Create buttons.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 40px 20px;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
h1 {
color: white;
text-align: center;
margin-bottom: 40px;
font-size: 36px;
}
.button-container {
max-width: 600px;
margin: 0 auto 40px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 20px;
}
/* Base button styles */
.btn {
padding: 12px 24px;
font-size: 16px;
font-weight: 600;
border: none;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s ease;
}
/* Primary button */
.btn-primary {
background-color: #3498db;
color: white;
}
.btn-primary:hover {
background-color: #2980b9;
box-shadow: 0 4px 12px rgba(52, 152, 219, 0.4);
}
/* Success button */
.btn-success {
background-color: #27ae60;
color: white;
}
.btn-success:hover {
background-color: #229954;
box-shadow: 0 4px 12px rgba(39, 174, 96, 0.4);
}
/* Warning button */
.btn-warning {
background-color: #f39c12;
color: white;
}
.btn-warning:hover {
background-color: #e67e22;
box-shadow: 0 4px 12px rgba(243, 156, 18, 0.4);
}
/* Danger button */
.btn-danger {
background-color: #e74c3c;
color: white;
}
.btn-danger:hover {
background-color: #c0392b;
box-shadow: 0 4px 12px rgba(231, 76, 60, 0.4);
}
/* Scale on hover */
.btn-scale {
background-color: #9b59b6;
color: white;
}
.btn-scale:hover {
transform: scale(1.1);
}
/* Rotate on hover */
.btn-rotate {
background-color: #16a085;
color: white;
}
.btn-rotate:hover {
transform: rotate(-5deg);
}
/* Bounce animation */
@keyframes bounce {
0%, 100% {
transform: translateY(0);
}
50% {
transform: translateY(-10px);
}
}
.btn-bounce {
background-color: #2980b9;
color: white;
}
.btn-bounce:hover {
animation: bounce 0.6s ease;
}
/* Glow effect */
@keyframes glow {
0% {
box-shadow: 0 0 5px rgba(255, 107, 107, 0.5);
}
50% {
box-shadow: 0 0 20px rgba(255, 107, 107, 0.8);
}
100% {
box-shadow: 0 0 5px rgba(255, 107, 107, 0.5);
}
}
.btn-glow {
background-color: #e74c3c;
color: white;
}
.btn-glow:hover {
animation: glow 1s ease infinite;
}
Step-by-Step Exercise: Create an Animated Card Slider
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Card Slider</title>
<link rel="stylesheet" href="cards-animated.css">
</head>
<body>
<h1>Animated Card Slider</h1>
<div class="cards-container">
<div class="card">
<h2>Card 1</h2>
<p>Hover over me to see the animation effect!</p>
</div>
<div class="card">
<h2>Card 2</h2>
<p>Each card has a unique animation on hover.</p>
</div>
<div class="card">
<h2>Card 3</h2>
<p>Watch the transformation effects in action.</p>
</div>
<div class="card">
<h2>Card 4</h2>
<p>CSS animations make the UI interactive and fun!</p>
</div>
</div>
</body>
</html>
CSS for Animated Cards:
body {
background-color: #f0f0f0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
padding: 40px 20px;
}
h1 {
text-align: center;
margin-bottom: 40px;
color: #2c3e50;
}
.cards-container {
max-width: 1200px;
margin: 0 auto;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}
@keyframes slide-up {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes flip {
0% {
transform: rotateY(0deg);
}
100% {
transform: rotateY(360deg);
}
}
.card {
background: white;
border-radius: 8px;
padding: 30px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
cursor: pointer;
transition: all 0.3s ease;
animation: slide-up 0.6s ease-out forwards;
}
.card:nth-child(1) { animation-delay: 0.1s; }
.card:nth-child(2) { animation-delay: 0.2s; }
.card:nth-child(3) { animation-delay: 0.3s; }
.card:nth-child(4) { animation-delay: 0.4s; }
.card h2 {
color: #2c3e50;
margin-bottom: 15px;
}
.card p {
color: #555;
line-height: 1.6;
}
.card:hover {
transform: translateY(-10px) scale(1.05);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}
Animation Performance Tips
For smooth animations:
/* Use transform and opacity (GPU accelerated) */
.good-animation {
animation: slide 0.3s ease-out;
}
@keyframes slide {
from { transform: translateX(-100px); }
to { transform: translateX(0); }
}
/* Avoid animating layout properties (position, width) */
.bad-animation {
animation: bad-slide 0.3s ease-out;
}
@keyframes bad-slide {
from { left: -100px; }
to { left: 0; }
}
Best animated properties:
transform- Very fastopacity- Very fastfilter- Fast- Avoid:
width,height,left,top, etc.
Challenge Exercise (Optional)
Create an interactive dashboard with:
- Animated buttons with at least 3 different hover effects
- A list with hover effects on items
- A styled table with striped rows and hover effects
- At least 2 keyframe animations
- Use transitions on at least 5 elements
- Include transform effects (scale, rotate, translate)
- Create a card component with complex animation
- Add timing delays to stagger animations
- Use different timing functions (ease, ease-in, ease-out)
- Test animations run smoothly without stuttering
Key Takeaways
- Transitions smoothly animate between state changes
- Use
transition: property duration timing-function; - Transforms rotate, scale, translate, and skew elements
- Animations use @keyframes for complex sequences
- Hover effects make interfaces interactive
- List styling controls bullets and spacing
- Table styling improves readability with alternating rows
- Use transform and opacity for best performance
- Add animation-delay to stagger multiple elements
- Test animations on different devices
References
- W3Schools CSS Transitions
- W3Schools CSS Transforms
- W3Schools CSS Animations
- W3Schools Hover
- W3Schools List Styling
- W3Schools Table Styling
Chapter 10: JavaScript Basics - Interactivity & Functionality
Learning Objectives
By the end of this chapter, you will be able to:
- Write basic JavaScript syntax with variables and data types
- Handle user input and manipulate the DOM
- Create event listeners for interactivity
- Build simple interactive web applications
Concept Introduction: JavaScript in Web Design
JavaScript adds interactivity and behavior to web pages. While HTML provides structure and CSS provides styling, JavaScript creates dynamic functionality and responds to user actions.
Learn more: W3Schools JavaScript
Including JavaScript
The recommended way is to link an external script at the bottom of the
<body> tag:
<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<script src="script.js"></script>
</body>
</html>
You can also write JavaScript directly in HTML:
<script>
console.log("Hello from JavaScript!");
</script>
Learn more: W3Schools JavaScript HTML
Variables and Data Types
Use let and const to declare variables:
let name = "Alice"; /* String */
let age = 25; /* Number */
let isActive = true; /* Boolean */
const MAX = 100; /* Constant */
let colors = ["red", "green", "blue"]; /* Array */
let person = {name: "Alice", age: 25}; /* Object */
/* Access values */
console.log(colors[0]); /* "red" */
console.log(person.name); /* "Alice" */
Learn more: W3Schools Variables
DOM Manipulation
Getting elements:
let element = document.getElementById("myId");
let element = document.querySelector("#myId");
let elements = document.querySelectorAll(".myClass");
Updating content:
element.textContent = "New text";
element.innerHTML = "<strong>Bold</strong>";
element.classList.add("active");
element.id = "newId";
Learn more: W3Schools DOM
Basic Operators
/* Arithmetic */
let sum = 10 + 5; /* 15 */
let product = 10 * 5; /* 50 */
/* Comparison */
10 === 10; /* true (strict equality) */
10 > 5; /* true */
10 < 5; /* false */
/* Logical */
true && false; /* false (AND) */
true || false; /* true (OR) */
!true; /* false (NOT) */
Learn more: W3Schools Operators
Control Flow
If statements:
if (age >= 18) {
console.log("You are an adult");
} else {
console.log("You are a minor");
}
Loops:
/* For loop */
for (let i = 0; i < 5; i++) {
console.log(i);
}
/* For-of loop */
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
Learn more: W3Schools If Else, W3Schools Loops
Functions
Functions are reusable blocks of code:
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); /* "Hello, Alice" */
/* Arrow function */
const add = (a, b) => a + b;
console.log(add(5, 3)); /* 8 */
Learn more: W3Schools Functions
Event Handling
Event listeners respond to user interactions:
let button = document.getElementById("myButton");
button.addEventListener("click", () => {
console.log("Button clicked!");
});
/* Common events: click, input, submit, keydown, mouseenter */
let input = document.getElementById("myInput");
input.addEventListener("input", (event) => {
console.log("User typed: " + event.target.value);
});
let form = document.getElementById("myForm");
form.addEventListener("submit", (event) => {
event.preventDefault(); /* Prevent form submission */
console.log("Form submitted!");
});
Learn more: W3Schools Events
Step-by-Step Exercise: Create an Interactive Calculator
Step 1: Create calculator.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Simple Calculator</title>
<link rel="stylesheet" href="calculator.css">
</head>
<body>
<div class="calculator-container">
<h1>Simple Calculator</h1>
<input type="number" id="num1" placeholder="First number">
<input type="number" id="num2" placeholder="Second number">
<div class="button-group">
<button id="addBtn" class="btn">Add</button>
<button id="subtractBtn" class="btn">Subtract</button>
<button id="multiplyBtn" class="btn">Multiply</button>
<button id="divideBtn" class="btn">Divide</button>
</div>
<div id="result" class="result"></div>
</div>
<script src="calculator.js"></script>
</body>
</html>
Step 2: Create calculator.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.calculator-container {
background: white;
padding: 40px;
border-radius: 8px;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
max-width: 400px;
width: 100%;
}
h1 {
text-align: center;
color: #333;
margin-bottom: 30px;
font-size: 28px;
}
input {
width: 100%;
padding: 12px;
margin-bottom: 15px;
border: 2px solid #ddd;
border-radius: 4px;
font-size: 16px;
transition: border-color 0.3s;
}
input:focus {
outline: none;
border-color: #667eea;
}
.button-group {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-bottom: 20px;
}
.btn {
padding: 12px;
background-color: #667eea;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
}
.btn:hover {
background-color: #5568d3;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4);
}
.btn:active {
transform: translateY(0);
}
.result {
background-color: #f0f0f0;
padding: 20px;
border-radius: 4px;
text-align: center;
font-size: 20px;
color: #333;
min-height: 30px;
display: flex;
align-items: center;
justify-content: center;
}
.result.error {
background-color: #fee;
color: #c33;
}
.result.success {
background-color: #efe;
color: #3c3;
}
Step 3: Create calculator.js
/* Get elements */
const num1Input = document.getElementById("num1");
const num2Input = document.getElementById("num2");
const resultDiv = document.getElementById("result");
const addBtn = document.getElementById("addBtn");
const subtractBtn = document.getElementById("subtractBtn");
const multiplyBtn = document.getElementById("multiplyBtn");
const divideBtn = document.getElementById("divideBtn");
/* Perform calculation */
function performCalculation(operation) {
const num1 = parseFloat(num1Input.value);
const num2 = parseFloat(num2Input.value);
/* Validate inputs */
if (isNaN(num1) || isNaN(num2)) {
showError("Please enter valid numbers");
return;
}
let result;
switch (operation) {
case "add":
result = num1 + num2;
break;
case "subtract":
result = num1 - num2;
break;
case "multiply":
result = num1 * num2;
break;
case "divide":
if (num2 === 0) {
showError("Cannot divide by zero");
return;
}
result = num1 / num2;
break;
default:
showError("Unknown operation");
return;
}
showResult(result);
}
/* Display result */
function showResult(value) {
resultDiv.textContent = "Result: " + value.toFixed(2);
resultDiv.classList.remove("error");
resultDiv.classList.add("success");
}
/* Display error */
function showError(message) {
resultDiv.textContent = message;
resultDiv.classList.remove("success");
resultDiv.classList.add("error");
}
/* Add event listeners */
addBtn.addEventListener("click", () => performCalculation("add"));
subtractBtn.addEventListener("click", () => performCalculation("subtract"));
multiplyBtn.addEventListener("click", () => performCalculation("multiply"));
divideBtn.addEventListener("click", () => performCalculation("divide"));
Step-by-Step Exercise: Create an Interactive Quiz
HTML Structure
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Interactive Quiz</title>
<link rel="stylesheet" href="quiz.css">
</head>
<body>
<div class="quiz-container">
<h1>JavaScript Quiz</h1>
<div id="quizContent">
<div id="startScreen">
<p>Test your JavaScript knowledge!</p>
<button id="startBtn" class="btn">Start Quiz</button>
</div>
<div id="questionScreen" style="display: none;">
<div class="progress">
<span id="questionNumber"></span>
</div>
<h2 id="question"></h2>
<div id="options" class="options"></div>
<button id="nextBtn" class="btn" style="display: none;">
Next
</button>
</div>
<div id="resultScreen" style="display: none;">
<h2>Quiz Complete!</h2>
<p id="scoreMessage"></p>
<button id="retakeBtn" class="btn">Retake Quiz</button>
</div>
</div>
</div>
<script src="quiz.js"></script>
</body>
</html>
JavaScript Quiz Logic
const questions = [
{
question: "What does HTML stand for?",
options: ["Hyper Text Markup Language", "High Tech Modern Language",
"Home Tool Markup Language", "Hyperlinks and Text Markup Language"],
correct: 0
},
{
question: "Which symbol is used for comments in JavaScript?",
options: ["//", "<!--", "/*", "#"],
correct: 0
},
{
question: "What keyword declares a variable in JavaScript?",
options: ["var", "let", "const", "all of the above"],
correct: 3
},
{
question: "How do you add a comment in JavaScript?",
options: ["# This is a comment", "<!-- This is a comment -->",
"// This is a comment", "-- This is a comment"],
correct: 2
},
{
question: "What does DOM stand for?",
options: ["Data Object Model", "Document Object Model",
"Dynamic Object Model", "Display Object Model"],
correct: 1
}
];
let currentQuestion = 0;
let score = 0;
let selectedAnswer = null;
/* Get elements */
const startBtn = document.getElementById("startBtn");
const nextBtn = document.getElementById("nextBtn");
const retakeBtn = document.getElementById("retakeBtn");
const startScreen = document.getElementById("startScreen");
const questionScreen = document.getElementById("questionScreen");
const resultScreen = document.getElementById("resultScreen");
const questionNumber = document.getElementById("questionNumber");
const questionElement = document.getElementById("question");
const optionsElement = document.getElementById("options");
const scoreMessage = document.getElementById("scoreMessage");
/* Start quiz */
startBtn.addEventListener("click", () => {
startScreen.style.display = "none";
questionScreen.style.display = "block";
showQuestion();
});
/* Display question */
function showQuestion() {
const question = questions[currentQuestion];
questionNumber.textContent =
`Question ${currentQuestion + 1} of ${questions.length}`;
questionElement.textContent = question.question;
optionsElement.innerHTML = "";
selectedAnswer = null;
nextBtn.style.display = "none";
question.options.forEach((option, index) => {
const optionDiv = document.createElement("div");
optionDiv.className = "option";
const input = document.createElement("input");
input.type = "radio";
input.name = "answer";
input.value = index;
input.addEventListener("change", () => {
selectedAnswer = index;
nextBtn.style.display = "block";
});
const label = document.createElement("label");
label.appendChild(input);
label.appendChild(document.createTextNode(" " + option));
optionDiv.appendChild(label);
optionsElement.appendChild(optionDiv);
});
}
/* Next question */
nextBtn.addEventListener("click", () => {
if (selectedAnswer === null) return;
const question = questions[currentQuestion];
if (selectedAnswer === question.correct) {
score++;
}
currentQuestion++;
if (currentQuestion < questions.length) {
showQuestion();
} else {
showResults();
}
});
/* Show results */
function showResults() {
questionScreen.style.display = "none";
resultScreen.style.display = "block";
const percentage = Math.round((score / questions.length) * 100);
scoreMessage.textContent =
`You scored ${score} out of ${questions.length} (${percentage}%)`;
}
/* Retake quiz */
retakeBtn.addEventListener("click", () => {
currentQuestion = 0;
score = 0;
selectedAnswer = null;
resultScreen.style.display = "none";
startScreen.style.display = "block";
});
Debugging Tips
Open the browser DevTools with F12:
- Console tab: View errors and
console.log()messages - Inspector tab: Inspect and edit HTML/CSS
- Debugger tab: Set breakpoints and step through code
Key Takeaways
- JavaScript adds interactivity to web pages
- Use
letandconstfor variables - Data types include String, Number, Boolean, Array, Object
- DOM manipulation updates page content dynamically
- Event listeners respond to user actions
- Functions create reusable code blocks
- Operators perform calculations and comparisons
- Control flow (if/else, loops) makes decisions
- Validation ensures data quality before processing
- Testing and debugging are essential skills