Fundamental Of HTML
Responsive Design With Media Queries
Module 1: Introduction to HTML
Welcome to the world of web development! This first module will introduce you to the very basics of HTML, the language that forms the backbone of every website you visit.
What is HTML?
HTML stands for HyperText Markup Language. Let's break that down:
- HyperText: This refers to text that contains links to other texts. The ability to link pages together is the foundation of the World Wide Web.
- Markup Language: This means that HTML uses "tags" to "mark up" or describe the content of a web page. These tags tell the web browser how to display the content, such as identifying headings, paragraphs, images, and more.
In simple terms, HTML is the standard language used to create and structure the content of a web page. It's the skeleton that gives a website its form.
The History and Evolution of HTML
HTML was created by Tim Berners-Lee in 1991. The first version was very simple. Over the years, it has gone through several versions, with each one adding new features and capabilities. The current standard is HTML5, which introduced many new elements for better structuring web pages, handling multimedia, and more.
The Roles of HTML, CSS, and JavaScript
Think of building a website like building a house:
- HTML (The Skeleton): As we've discussed, HTML provides the basic structure and content of the website. It's the foundation and the framework.
- CSS (The Interior Design): CSS, or Cascading Style Sheets, is used to style the HTML content. It controls the colors, fonts, layout, and overall visual presentation. If HTML is the skeleton, CSS is the skin, hair, and clothing.
- JavaScript (The Functionality): JavaScript is a programming language that brings interactivity to a website. It handles things like animations, form validations, and dynamic content updates. It's what makes the house "smart" – allowing you to open doors, turn on lights, and interact with it.
In this course, we will focus exclusively on HTML. Once you have a strong foundation here, you can move on to learning CSS and JavaScript.
Setting Up Your Development Environment
To start writing HTML, you only need two things:
-
A Text Editor: This is where you will write your code. While you could use a simple program like Notepad (Windows) or TextEdit (Mac), it's highly recommended to use a more powerful, free text editor designed for coding. Popular choices include:
- Visual Studio Code (VS Code): A very popular and feature-rich editor.
- Sublime Text: A lightweight and fast editor.
- Atom: A modern and customizable editor.
-
A Web Browser: This is what you will use to view your HTML files. You already have one! Common browsers include:
- Google Chrome
- Mozilla Firefox
- Microsoft Edge
- Safari
Creating Your First HTML File
Let's create your very first web page!
-
Open your text editor.
-
Type the following code:
<!DOCTYPE html> <html> <head> <title>My First Web Page</title> </head> <body> <h1>Hello, World!</h1> <p>This is my first paragraph.</p> </body> </html>
-
Save the file:
- Go to "File" -> "Save As...".
- Name the file
index.html
. It is a common convention to name the main page of a websiteindex.html
. - Make sure to save it with the
.html
extension.
-
View your page:
- Navigate to where you saved the file on your computer.
- Double-click the
index.html
file. It should open in your default web browser, and you will see "Hello, World!" as a large heading and "This is my first paragraph." as text.
Congratulations! You have just created your first web page. In the next module, we'll break down what all of that code actually means.
Module 2: Basic HTML Structure
In this module, we will dissect the code you wrote in Module 1 to understand the essential elements that form the foundation of every HTML document.
The <!DOCTYPE html>
Declaration
The very first line of an HTML document should be the doctype declaration:
<!DOCTYPE html>
This tells the browser that the document is an HTML5 document. It's a standard that ensures your page is displayed correctly by the browser.
The <html>
Element
The <html>
element is
the root element of an HTML page. All other elements are nested inside it.
<html>
<!-- All other elements go here -->
</html>
The opening <html>
tag
signals the beginning of the HTML document, and the closing </html>
tag signals the end.
The <head>
Section
The <head>
element
contains meta-information about the HTML document. This information is not displayed in the main browser
window but is important for the browser and search engines.
<head>
<meta charset="UTF-8">
<title>My First Web Page</title>
</head>
<meta>
Tags: These provide metadata about the document.<meta charset="UTF-8">
is a common and important declaration that specifies the character encoding for the document, ensuring that text is displayed correctly.<title>
Tag: This is a required element that sets the title of the web page. You'll see this title in the browser tab.
The <body>
Section
The <body>
element
contains all the visible content of the web page, such as headings, paragraphs, images, links, tables, etc.
<body>
<h1>Hello, World!</h1>
<p>This is my first paragraph.</p>
</body>
Everything you want your users to see goes inside the <body>
tags.
Understanding HTML Elements and Tags
HTML is made up of elements. An element is usually composed of:
- An opening tag: e.g.,
<p>
- Content: The text or other elements inside.
- A closing tag: e.g.,
</p>
For example, <p>This is a
paragraph.</p>
is an HTML element.
Some elements are "empty" or "void," meaning they don't have a
closing tag, as they don't enclose any content. An example we'll see later is the line break tag, <br>
.
Self-Check: Can you identify the opening tag,
content, and closing tag in this line of code: <h1>Hello, World!</h1>
?
Module 3: Text Formatting and Content
Now that you understand the basic structure, let's learn how to add and format text content.
Headings (<h1>
to <h6>
)
Headings are used to structure your content and define a hierarchy of importance. <h1>
is the most important heading, and <h6>
is the least important.
<h1>This is a Main Heading</h1>
<h2>This is a Subheading</h2>
<h3>This is a Smaller Subheading</h3>
Best Practice: Use headings in their logical order. You
should have only one <h1>
per page, which
typically represents the main title of that page.
Paragraphs (<p>
)
The <p>
element is used
to define a paragraph of text. Browsers automatically add some space (a margin) before and after a paragraph.
<p>This is a paragraph of text. It can contain multiple sentences.</p>
<p>This is another paragraph. It will be displayed as a separate block of text.</p>
Emphasis and Importance
-
<em>
(Emphasis): This tag is used to add emphasis to text. Most browsers will render this as italicized text. It's used to stress a word or phrase.<p>You <em>must</em> complete this by Friday.</p>
-
<strong>
(Strong Importance): This tag is used to indicate that the text is important. Most browsers will render this as bold text.<p><strong>Warning:</strong> Do not touch the wires.</p>
Note: While <em>
and <strong>
often look like italics and bold, their
primary purpose is to add semantic meaning to the text. If you just want text to be bold or italic for stylistic
reasons, you should use CSS.
Line Breaks (<br>
)
and Horizontal Rules (<hr>
)
-
<br>
(Line Break): This is an empty element used to insert a single line break. It's useful for things like addresses or poems where the division of lines is significant.<p>My address is:<br> 123 Main Street<br> Anytown, USA</p>
-
<hr>
(Horizontal Rule): This tag is used to create a thematic break in the content, which is often displayed as a horizontal line.<p>This is the first topic.</p> <hr> <p>This is the second topic.</p>
Comments in HTML
As your HTML documents get more complex, it's helpful to leave notes for yourself or other developers. You can do this with HTML comments. Comments are ignored by the browser and are not visible on the page.
<!-- This is a comment. It will not be displayed. -->
<p>This is a paragraph.</p>
Practice Exercise: Create a new HTML file. Add a main
heading (<h1>
), a subheading (<h2>
), a paragraph with some emphasized and
strong text, and then use a horizontal rule to separate it from another paragraph that includes your address
formatted with line breaks.
Module 4: Lists and Links
Organizing information and connecting pages are fundamental aspects of web design. This module covers lists and hyperlinks.
Unordered Lists (<ul>
)
An unordered list is a list of items where the order does not matter. It is created with
the <ul>
tag, and each list item is defined with
the <li>
tag. By default, these are displayed
with bullet points.
<ul>
<li>Apples</li>
<li>Oranges</li>
<li>Bananas</li>
</ul>
Ordered Lists (<ol>
)
An ordered list is a list where the order of items is important. It is created with the
<ol>
tag, and each list item is also defined
with the <li>
tag. By default, these are
displayed with numbers.
<ol>
<li>First, preheat the oven.</li>
<li>Second, mix the ingredients.</li>
<li>Third, bake for 30 minutes.</li>
</ol>
Description Lists (<dl>
)
A description list is a list of terms, with a description of each term. It is created with
the <dl>
tag. Each term is specified with <dt>
(description term), and each description
with <dd>
(description details).
<dl>
<dt>HTML</dt>
<dd>- HyperText Markup Language</dd>
<dt>CSS</dt>
<dd>- Cascading Style Sheets</dd>
</dl>
Creating Hyperlinks (<a>
)
The <a>
tag, or anchor
tag, is used to create a link to another web page or resource. The most important attribute of the <a>
tag is href
, which specifies the destination of the link.
<a href="https://www.google.com">Click here to visit Google</a>
The text between the opening <a>
tag and the closing </a>
tag is the visible part of the link.
Absolute and Relative URLs
-
Absolute URL: This is a full web address that includes the protocol (
https://
), domain name, and path. You use this when linking to an external website.<a href="https://www.wikipedia.org/">Visit Wikipedia</a>
-
Relative URL: This is a partial address that points to a file within your own website. It's "relative" to the current page.
Let's say you have two files in the same folder:
index.html
andabout.html
. To link fromindex.html
toabout.html
, you would write:<a href="about.html">About Us</a>
Linking to Email Addresses
You can also create a link that opens the user's default email client to send an email to a specific address.
<a href="mailto:contact@example.com">Email Us</a>
Practice Exercise: On your practice page, create an ordered list of your favorite movies. Then, create an unordered list of your hobbies. Finally, add a link to your favorite website using an absolute URL.
Module 5: Working with Images and Multimedia
A picture is worth a thousand words. This module will teach you how to embed images and other media into your web pages.
The <img>
Tag
The <img>
tag is an empty
element used to embed an image in an HTML page. It has two required attributes:
src
(Source): This specifies the path (URL) to the image.alt
(Alternative Text): This provides a text description of the image. It is crucial for screen readers (for visually impaired users) and will be displayed if the image fails to load.
<img src="images/dog.jpg" alt="A photo of a happy dog playing in a field.">
It is a best practice to keep your images in a subfolder, such as images/
.
You can also include width
and
height
attributes to specify the size of the image in
pixels.
<img src="images/dog.jpg" alt="A happy dog" width="500" height="300">
Image Formats
Common image formats for the web include:
- JPEG (.jpg): Best for photographs.
- PNG (.png): Good for images with transparency.
- GIF (.gif): Used for simple animations.
- SVG (.svg): A vector format that is scalable and great for logos and icons.
Multimedia with <video>
and <audio>
HTML5 introduced elements for embedding video and audio directly into your web pages without needing plugins like Flash.
-
<video>
Tag:<video controls width="600"> <source src="videos/my-video.mp4" type="video/mp4"> Your browser does not support the video tag. </video>
The
controls
attribute adds video controls, like play, pause, and volume. -
<audio>
Tag:<audio controls> <source src="audio/my-song.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio>
Embedding Content with <iframe>
The <iframe>
tag is used
to embed another HTML document within the current one. This is commonly used for embedding maps, videos from
services like YouTube, and other external content.
<!-- Embedding a YouTube Video -->
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Practice Exercise: Find an image online (or use one of
your own). Save it to an images
folder next to your
HTML file. Add the image to your page. Then, find a YouTube video you like and embed it below the image.
Module 6: Tables
Tables are used to display data in a structured, grid-like format of rows and columns.
Basic Table Structure
<table>
: The container for the entire table.<tr>
(Table Row): Defines a row in the table.<td>
(Table Data): Defines a cell in the table. This is where the actual data goes.<th>
(Table Header): Defines a header cell. The text in a header cell is typically bold and centered.
Here is a simple table:
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
By default, tables do not have borders. You can add them with a simple CSS attribute for
now: <table border="1">
.
Spanning Rows and Columns
You can make a cell span across multiple columns or rows using the colspan
and rowspan
attributes.
colspan="2"
: Makes a cell span two columns.rowspan="2"
: Makes a cell span two rows.
<table border="1">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>55577854</td>
<td>55577855</td>
</tr>
</table>
Structuring Tables Semantically
For more complex tables, you can use <thead>
, <tbody>
, and <tfoot>
to group the header, body, and footer
content of the table.
<table border="1">
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apples</td>
<td>$1.50</td>
</tr>
<tr>
<td>Oranges</td>
<td>$2.00</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$3.50</td>
</tr>
</tfoot>
</table>
This structure helps with accessibility and can also be useful for styling with CSS.
Practice Exercise: Create a table that lists your weekly schedule. The columns should be the days of the week, and the rows should be times of the day.
Module 7: Forms
Forms are a crucial part of the interactive web, allowing users to input data. This module covers the essentials of creating HTML forms.
The <form>
Element
The <form>
element is a
container for different types of input elements. Key attributes include:
action
: Specifies the URL where the form data should be sent when submitted.method
: Specifies the HTTP method to be used (GET
orPOST
).
For now, we will focus on the structure of the form itself.
<form action="/submit-form" method="post">
<!-- Form elements go here -->
</form>
Input Types
The <input>
element is
the most versatile form element. Its behavior is determined by its type
attribute.
-
type="text"
: A single-line text input field.<label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br>
-
type="password"
: A single-line text input where the characters are masked. -
type="email"
: A field for an email address, with built-in validation in some browsers. -
type="submit"
: A button for submitting the form.<input type="submit" value="Submit">
Labels (<label>
)
The <label>
tag is
important for accessibility. It defines a label for an <input>
element. The for
attribute of the <label>
should be the same as the id
of the <input>
element to bind them together.
Textareas (<textarea>
)
For multi-line text input, like a comment box, use the <textarea>
element.
<label for="comment">Comment:</label><br>
<textarea id="comment" name="comment" rows="4" cols="50"></textarea>
Dropdown Lists (<select>
)
A dropdown list is created with the <select>
element, and each option is defined
with the <option>
element.
<label for="cars">Choose a car:</label>
<select id="cars" name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
Radio Buttons and Checkboxes
-
Radio Buttons (
type="radio"
): Allow the user to select only one option from a group. All radio buttons in a group must have the samename
attribute.<input type="radio" id="html" name="fav_language" value="HTML"> <label for="html">HTML</label><br> <input type="radio" id="css" name="fav_language" value="CSS"> <label for="css">CSS</label><br>
-
Checkboxes (
type="checkbox"
): Allow the user to select one or more options.<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike"> <label for="vehicle1"> I have a bike</label><br> <input type="checkbox" id="vehicle2" name="vehicle2" value="Car"> <label for="vehicle2"> I have a car</label><br>
Practice Exercise: Create a simple contact form with fields for a name (text), email (email), a message (textarea), and a submit button. Use labels for each input field.
Module 8: Semantic HTML
Semantic HTML means using HTML tags for their intended purpose. It's about describing the content's meaning, not just its appearance. This is vital for accessibility and Search Engine Optimization (SEO).
The Importance of Semantic HTML
- Accessibility: Screen readers use the HTML structure to interpret the page for visually impaired users. A well-structured page is much easier to navigate.
- SEO: Search engines like Google use the semantics of your page to understand its content and rank it in search results.
- Maintainability: Semantic code is easier for you and other developers to read and understand.
<div>
and <span>
<div>
: A generic block-level container. It's used to group large sections of content. It has no semantic meaning on its own.<span>
: A generic inline container. It's used to group small pieces of content within a line, often for styling purposes. It also has no semantic meaning.
Before HTML5, web layouts were often built using many <div>
elements with IDs or classes to describe
them, like <div id="header">
. HTML5
introduced new elements to make this much more semantic.
HTML5 Structural Elements
These elements are designed to structure the main parts of a web page:
-
<header>
: Represents introductory content for a page or a section. It can contain headings, a logo, a search form, etc. -
<nav>
: Contains the main navigation links for the site. -
<main>
: Specifies the main, unique content of the document. There should only be one<main>
element per page. -
<section>
: Defines a thematic grouping of content, typically with a heading. Think of it as a chapter in a book. -
<article>
: Represents a self-contained piece of content that could be distributed independently, like a blog post, a news story, or a forum post. -
<aside>
: Defines content that is tangentially related to the main content, such as a sidebar or a call-out box. -
<footer>
: Defines the footer for a document or section. It typically contains information like authorship, copyright, and links to related documents.
Here's an example of how these elements might be used to structure a page:
<body>
<header>
<h1>My Awesome Blog</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
</header>
<main>
<article>
<h2>My First Blog Post</h2>
<p>This is the content of my first post.</p>
</article>
<article>
<h2>My Second Blog Post</h2>
<p>This is the content of my second post.</p>
</article>
</main>
<aside>
<h3>Related Links</h3>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</aside>
<footer>
<p>© 2025 My Awesome Blog</p>
</footer>
</body>
Final Project:
Now it's time to put everything you've learned together! Your final project is to create a simple, multi-page personal website.
-
Create a Home Page (
index.html
):- Use semantic HTML5 elements (
<header>
,<nav>
,<main>
,<footer>
). - Include a main heading.
- Write a short introductory paragraph about yourself.
- Include a picture of yourself (or something that represents you).
- Use semantic HTML5 elements (
-
Create an About Page (
about.html
):- This page should include more details about you.
- Use headings and paragraphs.
- Include an unordered list of your hobbies.
-
Create a Contact Page (
contact.html
):- Create a simple contact form.
-
Link the Pages Together:
- Your navigation menu in the
<nav>
element on each page should link to the other two pages.
- Your navigation menu in the
This project will solidify your understanding of all the core concepts of HTML. Good luck
Fundamental Of CSS
Responsive Design With Media Queries
Module 1: Introduction to CSS
Welcome to the world of web design! This module will introduce you to the core concepts of CSS and show you how to start applying styles to your HTML documents.
What is CSS?
CSS stands for Cascading Style Sheets. It is a stylesheet language used to describe the presentation and visual formatting of a document written in HTML. CSS handles the look and feel of a web page. With CSS, you can control:
- Colors and backgrounds
- Fonts and typography
- Layout and positioning
- And much more!
Why Use CSS? The Power of Separation
The most important concept is the separation of concerns. HTML is for content and structure, while CSS is for presentation and style. Keeping them separate has huge advantages:
- Maintainability: You can change the entire look of a website by editing just one CSS file, without ever touching the HTML.
- Consistency: A single stylesheet can be applied to multiple pages, ensuring a consistent look and feel across your entire website.
- Cleaner Code: Your HTML remains clean and focused on its semantic meaning, making it easier to read and manage.
Three Ways to Add CSS to a Page
-
External Stylesheet (Best Practice) This is the most common and recommended method. You write your CSS in a separate file with a
.css
extension (e.g.,style.css
) and link to it from your HTML file using the<link>
tag inside the<head>
section.In your HTML file (
index.html
):<head> <title>My Website</title> <link rel="stylesheet" href="style.css"> </head>
-
Internal Stylesheet You can place CSS rules directly inside the
<head>
of an HTML document using the<style>
tag. This is useful for single-page styles but is less maintainable for a multi-page site.In your HTML file:
<head> <title>My Website</title> <style> body { background-color: lightblue; } </style> </head>
-
Inline Styles You can apply styles directly to a specific HTML element using the
style
attribute. This method should be used sparingly as it mixes content and presentation, making it difficult to manage.In your HTML file:
<h1 style="color: blue; text-align: center;">This is a Blue, Centered Heading</h1>
Basic CSS Syntax
A CSS rule consists of a selector and a declaration block.
/* This is a CSS comment */
selector {
property: value;
another-property: another-value;
}
- Selector: Points to the HTML element you want to style
(e.g.,
h1
,p
). - Declaration Block: Surrounded by curly braces
{}
, it contains one or more declarations. - Declaration: A property-value pair.
- Property: The style attribute you want to change
(e.g.,
color
,font-size
). - Value: The setting you want to apply to the property.
- Property: The style attribute you want to change
(e.g.,
- Each declaration must end with a semicolon
;
.
Let's Get Started!
-
Take the
index.html
file from your final HTML project. -
Create a new file in the same folder and name it
style.css
. -
In your
index.html
file, add the following line inside the<head>
section to link your new stylesheet:<link rel="stylesheet" href="style.css">
-
In your
style.css
file, add the following rule:body { background-color: #f4f4f4; /* A light gray background */ }
-
Save both files and open
index.html
in your browser. The background of your page should now be light gray!
Module 2: Selectors, Specificity, and the Cascade
How does the browser know which element to style? Through selectors! This module covers how to target elements precisely.
Core Selectors
-
Element Selector: Targets all elements of a specific type.
/* Styles all <p> elements */ p { color: navy; }
-
Class Selector: Targets all elements with a specific
class
attribute. Classes are reusable. The selector starts with a period (.
). HTML:<p class="highlight">This is important.</p>
CSS:.highlight { background-color: yellow; }
-
ID Selector: Targets a single element with a specific
id
attribute. An ID must be unique per page. The selector starts with a hash (#
). HTML:<header id="main-header">...</header>
CSS:#main-header { border-bottom: 2px solid black; }
-
Grouping Selector: Apply the same styles to multiple selectors by separating them with a comma.
h1, h2, h3 { font-family: Arial, sans-serif; } ```* **Descendant Selector:** Targets an element that is nested inside another element. ```css /* Styles only <a> tags that are inside a <nav> tag */ nav a { color: green; }
Pseudo-classes
A pseudo-class is used to define a special state of an element.
- :hover: Applies when the user's mouse is over the
element.
/* Changes the button color when hovered over */ button:hover { background-color: darkgray; }
- :focus: Applies when an element has focus (e.g., an
<input>
field that has been clicked).
The Cascade and Specificity
What happens when two rules target the same element? The browser follows two main principles:
-
The Cascade: The "C" in CSS stands for Cascade. Styles "cascade" down from multiple sources. The last rule defined is the one that wins (if they have the same importance).
-
Specificity: This is how the browser decides which rule is more important. A more specific selector will always override a less specific one. The hierarchy is:
Inline Styles (most specific) > ID Selectors > Class & Pseudo-class Selectors > Element Selectors (least specific)
Example: HTML:
<h1 id="main-title" class="page-heading">Hello</h1>
CSS:h1 { color: blue; } /* Least specific */ .page-heading { color: green; } #main-title { color: red; } /* Most specific, so the text will be red */
Module 3: Core CSS Properties - Color and Typography
Let's start making things look good. This module covers essential properties for styling text and using color.
Colors in CSS
There are several ways to define colors:
- Color Names:
red
,blue
,lightgray
(Simple, but limited). - HEX Codes:
#RRGGBB
format, where RR, GG, and BB are hexadecimal values for Red, Green, and Blue.#FFFFFF
is white,#000000
is black. - RGB:
rgb(red, green, blue)
, where each value is from 0-255.rgb(255, 0, 0)
is red. - RGBA:
rgba(red, green, blue, alpha)
. Thealpha
value is for transparency, from 0 (fully transparent) to 1 (fully opaque).rgba(0, 0, 0, 0.5)
is semi-transparent black.
Text and Font Properties
color
: Sets the color of the text.p { color: #333333; /* A dark gray color */ }
font-family
: Sets the typeface for the text. Provide fallback fonts (a "font stack") in case the first one isn't available.body { font-family: Helvetica, Arial, sans-serif; }
font-size
: Sets the size of the font. Common units arepx
(pixels),em
(relative to the parent element's font size), andrem
(relative to the root element's font size).rem
is often preferred for scalability.h1 { font-size: 32px; }
font-weight
: Sets the thickness of the font. Common values arenormal
,bold
, or numeric values like400
(normal) and700
(bold).text-align
: Aligns the text horizontally:left
,right
,center
, orjustify
.text-decoration
: Adds decoration to text. Most commonly used to remove the default underline from links.a { text-decoration: none; /* Removes underline from links */ }
line-height
: Sets the distance between lines of text, improving readability. A unitless value like1.5
is recommended, meaning 1.5 times the font size.
Practice Exercise: In your style.css
file, set a font-family
and color
for the body
. Then, style your h1
element with a different color and a larger font-size
. Remove the underline from all your
navigation links and change their color.
Module 4: The Box Model
Every element on a web page is a rectangular box. The CSS Box Model is a crucial concept that describes how this box is constructed.
<img src="https://i.imgur.com/39h3Qo5.png" alt="Diagram of the CSS Box Model" width="400"/>
The box is made of four parts, from the inside out:
- Content: The actual content of the box (text, an image,
etc.). Its size is defined by
width
andheight
. - Padding: The transparent space between the content and the border. It's inside the box.
- Border: A line that goes around the padding and content.
- Margin: The transparent space outside the border. It pushes other elements away.
Box Model Properties
width
andheight
: Sets the dimensions of the content area.padding
: Can be set for each side (padding-top
,padding-right
, etc.) or with shorthand:.box { padding: 10px; /* 10px on all 4 sides */ padding: 10px 20px; /* 10px top/bottom, 20px left/right */ padding: 10px 20px 30px 40px; /* top, right, bottom, left */ }
border
: Typically set with shorthand:.box { border: 1px solid black; /* width, style, color */ }
margin
: Uses the same shorthand as padding to control the space around the element.
A Better Box Model: box-sizing
By default, when you set width:
200px;
, this only applies to the content area. Padding and border are added on
top, which can make calculations tricky. A modern and more intuitive approach is to use box-sizing: border-box;
. This tells the browser to
include padding and border in the element's total width and height.
It is a very common practice to apply this to all elements for a more predictable layout:
* {
box-sizing: border-box;
}
(The *
is a
universal selector that selects all elements.)
Practice Exercise: Find a div
or section
on your HTML page. Give it a class, then use
that class to set a width
, padding
, and a border
. Also, give it a margin
to push it away from other elements.
Module 5: Layout and Positioning
Now we'll move from styling individual boxes to arranging them on the page.
The display
Property
This property determines how an element behaves and is displayed.
-
display: block;
:- Starts on a new line.
- Takes up the full width available.
- Examples:
<h1>
,<p>
,<div>
,<section>
.
-
display: inline;
:- Does not start on a new line.
- Only takes up as much width as necessary.
width
,height
,margin-top
, andmargin-bottom
have no effect.- Examples:
<a>
,<span>
,<strong>
,<em>
.
-
display: inline-block;
:- The best of both worlds: it flows with the text like an inline element, but you can
set
width
,height
,margin
, andpadding
on it.
- The best of both worlds: it flows with the text like an inline element, but you can
set
-
display: none;
:- Completely removes the element from the page.
The position
Property
The position
property
specifies the type of positioning method used for an element.
-
position: static;
: The default value. Elements render in order, as they appear in the document flow. -
position: relative;
: The element is positioned relative to its normal position. You can then usetop
,right
,bottom
, andleft
to shift it around without affecting the layout of other elements. -
position: absolute;
: The element is removed from the normal document flow and positioned relative to its nearest positioned ancestor (i.e., the closest parent that isn'tstatic
). If no positioned ancestor is found, it uses the<body>
. -
position: fixed;
: The element is positioned relative to the browser window (the viewport). It will stay in the same place even if the page is scrolled. Perfect for "sticky" headers or footers.
Module 6: Modern Layouts with Flexbox
For many years, creating complex layouts in CSS was difficult. Flexbox is a modern layout model that makes it much easier to align and distribute space among items in a container.
Core Flexbox Concepts
To use Flexbox, you define a flex container and the items inside it become flex items.
HTML Structure:
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
CSS Activation:
.container {
display: flex;
}
Once display: flex
is applied,
you can use a set of properties to control the layout.
Key Flex Container Properties
-
flex-direction
: Defines the direction of the main axis.row
(default): Left to right.column
: Top to bottom.
-
justify-content
: Aligns flex items along the main axis.flex-start
: Items are packed toward the start.center
: Items are centered.flex-end
: Items are packed toward the end.space-between
: Items are evenly distributed; the first item is on the start line, the last on the end line.space-around
: Items are evenly distributed with equal space around them.
-
align-items
: Aligns flex items along the cross axis (the axis perpendicular toflex-direction
).flex-start
: Items are packed to the start of the cross axis.center
: Items are centered on the cross axis.flex-end
: Items are packed to the end of the cross axis.stretch
(default): Items stretch to fill the container.
Practical Example: A Centered Navigation Bar Flexbox makes creating a navigation bar incredibly simple.
HTML:
<nav>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</nav>
CSS:
nav {
display: flex;
justify-content: center; /* Horizontally center the links */
background-color: #333;
padding: 1rem;
}
nav a {
color: white;
margin: 0 1rem; /* Add space between the links */
}
Module 7: Responsive Design with Media Queries
Today, people browse the web on phones, tablets, and desktops of all sizes. Responsive Web Design is the practice of building websites that adapt and look great on any device.
The Viewport Meta Tag
First, you must add this line to the <head>
of your HTML. It tells the browser how to
control the page's dimensions and scaling.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Fluid Layouts and Relative Units
Instead of using fixed widths like width: 960px;
, use relative units that can scale.
- Percentages (
%
):width: 80%;
will make an element 80% of its parent's width. - Viewport Units:
vw
(viewport width) andvh
(viewport height).1vw
is 1% of the viewport's width.
Media Queries: The Magic of Responsive CSS
Media queries allow you to apply CSS rules only when certain conditions are met, such as the screen being a certain size.
The syntax is:
@media (condition) { /* CSS rules go here */ }
A common practice is "mobile-first design": you write the base styles for mobile
and then use media queries with min-width
to add
styles for larger screens.
Example: Let's create a two-column layout on desktops that stacks into a single column on mobile.
HTML:
<div class="container">
<main class="main-content">Main Content Here</main>
<aside class="sidebar">Sidebar Here</aside>
</div>
CSS:
/* --- Mobile First Styles (Default) --- */
.container {
/* No flexbox needed yet, items will stack by default */
}
.main-content, .sidebar {
padding: 1rem;
}
/* --- Tablet and Desktop Styles --- */
/* This rule applies only when the screen is 768px wide or wider */
@media (min-width: 768px) {
.container {
display: flex;
}
.main-content {
flex: 3; /* Takes up 3/4 of the space */
order: 2; /* Make the main content appear second */
}
.sidebar {
flex: 1; /* Takes up 1/4 of the space */
order: 1; /* Make the sidebar appear first */
}
}
Now, if you resize your browser window, you will see the layout change at the 768px "breakpoint."
Fundamental Of JavaScript
Responsive Design With Media Queries
Module 1: Introduction to JavaScript
This is where the magic happens! JavaScript (JS) is a programming language that allows you to implement complex features on web pages. If a webpage just sits there and looks pretty, it's using HTML and CSS. If it shows timely content updates, interactive maps, animated graphics, or online forms that give you instant feedback, you can bet that JavaScript is involved.
What is JavaScript?
JavaScript is the programming language of the web. It is:
- High-level: It's designed to be relatively easy for humans to read and write.
- Interpreted: The browser executes the code directly, without needing a compilation step.
- Dynamic: It can change the HTML and CSS of a page on the fly, in response to user actions.
In our house analogy:
- HTML: The skeleton and structure.
- CSS: The paint, carpets, and decoration.
- JavaScript: The electrical wiring, the doorbell, the garage door opener—everything that does something.
How to Add JavaScript to a Page
Just like CSS, there are three main ways to include JavaScript.
-
External JavaScript File (Best Practice) This is the cleanest and most maintainable method. You write your JS code in a separate file with a
.js
extension (e.g.,script.js
) and link to it from your HTML. The<script>
tag is usually placed right before the closing</body>
tag. This ensures that the HTML content has loaded before the script tries to manipulate it.In your HTML file (
index.html
):<body> <!-- All your HTML content --> <script src="script.js"></script> </body> </html>
-
Internal JavaScript You can write JavaScript directly inside a
<script>
tag within your HTML document. This is fine for small, page-specific scripts.In your HTML file:
<body> <!-- All your HTML content --> <script> // JavaScript code goes here console.log("Hello from inside the HTML!"); </script> </body> </html>
-
Inline JavaScript This method involves placing JavaScript code directly into an HTML attribute, like
onclick
. It is generally considered bad practice and should be avoided as it mixes structure and behavior.
Your First JavaScript: The Browser Console
Every modern browser has a built-in set of developer tools. One of the most important is the Console. The console is a place where you can write JavaScript and see messages from your code.
Let's write our "Hello, World!":
- Take your
index.html
file from the CSS project. - Create a new file in the same folder called
script.js
. - Add
<script src="script.js"></script>
right before the</body>
tag inindex.html
. - In your
script.js
file, add this line:console.log("Hello, World! My script is connected.");
- Open
index.html
in your browser. Right-click on the page and select "Inspect" or "Inspect Element." This will open the developer tools. Find and click on the "Console" tab. You should see your message!
The console.log()
command is
a programmer's best friend. It allows you to print out values and messages to see what your code is doing.
Another simple command is alert()
, which creates a pop-up dialog box.
alert("This is an alert box!");
Add this to your script.js
file, save, and refresh the page. You'll see the pop-up immediately.
Module 2: The Building Blocks - Variables & Data Types
To do anything useful in programming, you need to be able to store and manage information. We do this with variables.
What is a Variable?
Think of a variable as a labeled box where you can store a piece of information. You give the box a name, and you can put things in it, take things out, or change what's inside.
In JavaScript, we declare variables using keywords: let
and const
.
let
: Use this when you expect the value of the variable to change.let userAge = 30; userAge = 31; // This is allowed console.log(userAge); // Will print 31
const
: Use this for values that will not change (constants). Trying to change aconst
will result in an error. This is generally preferred for safety.const birthYear = 1990; // birthYear = 1991; // This will cause an error! console.log(birthYear);
Core Data Types
Variables can hold different types of data. The most common are:
- String: Textual data. Must be enclosed in single (
'
) or double ("
) quotes.const greeting = "Hello, JavaScript learner!";
- Number: Any numerical value, including integers and
decimals.
const score = 100; const pi = 3.14;
- Boolean: A simple true or false value. Very important
for making decisions.
const isLoggedIn = true; const isGameOver = false;
Practice Exercise: In your script.js
file, create a const
variable to store your name (a string) and a
let
variable to store your current age (a number).
Use console.log()
to print out a sentence that
includes both variables. Example: console.log("My
name is " + myName + " and I am " + myAge + " years old.");
Module 3: Making Decisions - Operators & Conditionals
JavaScript can perform actions based on whether a certain condition is true or false. This is the foundation of logic in your code.
Operators
- Arithmetic Operators:
+
(add),-
(subtract),*
(multiply),/
(divide). - Assignment Operator:
=
(assigns a value to a variable). - Comparison Operators: Used to compare two values. They
always result in a boolean (
true
orfalse
).===
: Strict equality (value and type are the same). Always use this for equality checks.!==
: Strict inequality.>
: Greater than.<
: Less than.>=
: Greater than or equal to.<=
: Less than or equal to.
Conditional Statements: if...else
The if...else
statement
executes a block of code if a specified condition is true, and another block if it is false.
const age = 19;
if (age >= 18) {
console.log("You are old enough to vote.");
} else {
console.log("You are not old enough to vote yet.");
}
You can also chain conditions with else if
:
const time = 14; // 2 PM
if (time < 12) {
console.log("Good morning!");
} else if (time < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
Practice Exercise: Write an if...else
statement that checks a variable temperature
. If the temperature is above 25, log
"It's a hot day!". Otherwise, log "It's not too hot today."
Module 4: Grouping Code - Functions
A function is a reusable block of code designed to perform a specific task. Functions help you organize your code, make it more readable, and avoid repetition.
Defining and Calling a Function
You define a function using the function
keyword, followed by a name, parentheses
()
, and a code block {}
.
// Define the function
function greet() {
console.log("Welcome to the website!");
}
// Call the function to execute its code
greet();
greet(); // We can call it as many times as we want
Parameters and Arguments
Functions become even more powerful when you can pass information into them. Parameters are variables listed in the function definition. Arguments are the actual values passed to the function when it is called.
// 'name' is a parameter
function greetUser(name) {
console.log("Hello, " + name + "!");
}
// "Alice" and "Bob" are arguments
greetUser("Alice"); // Outputs: "Hello, Alice!"
greetUser("Bob"); // Outputs: "Hello, Bob!"
The return
Statement
Functions can also compute a value and send it back. The return
statement stops the execution of a function
and returns a value.
function add(num1, num2) {
return num1 + num2;
}
const sum = add(5, 10); // The 'sum' variable now holds the value 15
console.log(sum);
Practice Exercise: Create a function named calculateArea
that takes two parameters, width
and height
. Inside the function, it should calculate the
area (width * height
) and return
the result. Call the function with some
numbers and log the returned value.
Module 5: The Bridge to HTML - Introduction to the DOM
This is where everything connects. How does JavaScript actually interact with the HTML page? It does so through the DOM.
What is the DOM?
DOM stands for Document Object Model. When a browser loads a webpage, it creates a model of the page's content in memory. The DOM is this model, and it represents the entire HTML document as a tree of objects. JavaScript can access and manipulate this tree.
With the DOM, JavaScript can:
- Find and select any HTML element.
- Change the content of an element.
- Change the styles (CSS) of an element.
- React to user events (like clicks).
- Create and delete elements.
Selecting Elements
To manipulate an element, you first have to select it.
-
document.getElementById('idName')
: Selects the one element that has the given ID. HTML:<h1 id="main-title">My Website</h1>
JS:const mainTitle = document.getElementById('main-title');
-
document.querySelector('cssSelector')
: A more modern and versatile method. It returns the first element that matches a given CSS selector. HTML:<p class="intro">Welcome!</p>
JS:const introParagraph = document.querySelector('.intro');
Manipulating Elements
Once you have an element stored in a variable, you can change its properties.
element.textContent
: Changes the text content of the element.const mainTitle = document.getElementById('main-title'); mainTitle.textContent = "Welcome to My Interactive Page!";
element.style
: Changes the inline CSS styles of an element.mainTitle.style.color = 'blue'; mainTitle.style.backgroundColor = 'yellow';
element.classList
: A better way to change styles is by adding or removing CSS classes. CSS:
JS:.highlight { background-color: yellow; border: 2px solid red; }
mainTitle.classList.add('highlight'); // Adds the class mainTitle.classList.remove('highlight'); // Removes it mainTitle.classList.toggle('highlight'); // Adds it if not present, removes it if present
Practice Exercise: Go to your index.html
file. Give your main <h1>
an ID of page-title
. In your script.js
, select this element and use JavaScript to
change its text content to "My JavaScript-Powered Site".
Module 6: Making the Page React - Events
Interactive websites respond to user actions. These actions are called events.
What are Events?
An event is something that happens in the browser, which JavaScript can be notified of. Examples include:
- The user clicks the mouse (
click
). - The user moves the mouse over an element (
mouseover
). - The user presses a key on the keyboard (
keydown
). - A form is submitted (
submit
).
Event Listeners
To make something happen when an event occurs, you attach an event listener to an HTML element. The standard method is addEventListener()
.
It takes two main arguments:
- The type of event to listen for (e.g.,
'click'
). - A function to run when the event happens (this is often called a "callback function").
Example: A Clickable Button
HTML:
<button id="change-text-btn">Click Me!</button>
<p id="status-text">Waiting for a click...</p>
JavaScript:
// 1. Select the elements
const myButton = document.getElementById('change-text-btn');
const statusText = document.getElementById('status-text');
// 2. Add an event listener to the button
myButton.addEventListener('click', function() {
// 3. This code runs ONLY when the button is clicked
statusText.textContent = "Button was clicked!";
statusText.style.color = 'green';
});```
Now, when you click the button, the paragraph's text and color will change.
**Practice Exercise:** Add a button to your `index.html` with an ID. In your script, add an event listener to this button. When the button is clicked, make it change the background color of the `<body>` element. (Hint: you can select the body with `document.querySelector('body')`).
Module 7: Working with Collections - Arrays & Loops
What if you have a list of items you want to work with, like all the links in your navigation bar? You can store them in an Array.
Arrays
An array is a special variable that can hold more than one value at a time, in an ordered list.
// An array of strings
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Access the first item (indexing starts at 0) -> "Apple"
console.log(fruits.length); // Get the number of items in the array -> 3
You can also get a list of elements from the DOM. querySelectorAll()
returns a collection that acts
like an array.
HTML:
<nav>
<a href="#" class="nav-link">Home</a>
<a href="#" class="nav-link">About</a>
<a href="#" class="nav-link">Contact</a>
</nav>
JS:
const navLinks = document.querySelectorAll('.nav-link'); // Selects all matching elements
Loops
A loop is a way to repeat a block of code multiple times. This is perfect for working
with arrays. The most common is the for...of
loop.
const navLinks = document.querySelectorAll('.nav-link');
// Loop through each link in the navLinks collection
for (const link of navLinks) {
// 'link' represents the current item in the loop
console.log(link.textContent);
link.style.color = 'purple';
}
This code will select all your navigation links and, one by one, change their color to purple.
Practice Exercise: Give all the <li>
items in a list on your page a common
class name. Use querySelectorAll()
to select all of
them. Then, use a for...of
loop to iterate through
them and add a border
to each one using element.style.border
.
Ready to Get Started?
Creating a website has never been this Senang!
Sign up for SenangWebs today and build
a stunning online presence.
Highly Customizable
No Coding Required
Drag-and-Drop
Powered by AI