HTML Notes (1) SOME
HTML Notes (1) SOME
HTML OUTLINE
1. Introduction to HTML
• What is HTML?
• Importance of HTML in Web Development
• History and Evolution
HTML (Hypertext Markup Language) is the fundamental markup language used to create web
pages. It provides the structure and layout for web content by defining various elements such as
headings, paragraphs, images, links, and multimedia.
• Hypertext: Refers to text that contains links to other content, enabling users to navigate
between different pages or sections.
• Markup Language: A system for annotating text to define the structure and presentation
of the document’s content.
• Content Structure: HTML offers a logical framework to organize content on a web page.
• Interactivity: It works seamlessly with CSS (Cascading Style Sheets) and JavaScript to
style and add dynamic interactivity to the page.
• Cross-Browser Compatibility: HTML is supported by all modern web browsers, ensuring
that the content is accessible on different platforms.
• Search Engine Optimization (SEO): Proper use of semantic HTML improves the page’s
visibility and ranking in search engines.
Here’s a simple example of an HTML document that includes a heading, a paragraph, and a
hyperlink:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Introduction to HTML</title>
</head>
<body>
<h1>Welcome to HTML</h1>
<p>This is a simple example of an HTML webpage.</p>
<a href="[Link] Example</a>
</body>
</html>
Explanation
1. Document Type Declaration (<!DOCTYPE html>): Informs the browser that the
document follows HTML5 standards.
2. HTML Element (<html>): The root element that encapsulates all the content on the page.
3. Head Section (<head>): Contains metadata, including the character set and page title.
4. Meta Tags (<meta>): Provides additional information about the webpage, such as
encoding and viewport settings.
5. Title (<title>): Specifies the title that appears on the browser tab.
6. Body Section (<body>): Contains the visible content of the webpage.
7. Heading (<h1>): Defines the main heading on the page.
8. Paragraph (<p>): Represents a block of text.
9. Anchor (<a>): Creates a hyperlink to another webpage.
HTML offers several key features that make it an essential tool for web development:
• Platform Independent: HTML works across all devices and operating systems, making it
universally compatible.
Consider an online portfolio website for a web developer. The homepage might include:
Example HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Developer Portfolio</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<header>
<h1>Welcome to My Portfolio</h1>
<nav>
<ul>
<li><a href="#projects">Projects</a></li>
<li><a href="#blog">Blog</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<section id="projects">
<h2>My Projects</h2>
<p>Here are some of the amazing projects I have worked on.</p>
</section>
<section id="contact">
<h2>Contact Me</h2>
<form action="submit_form.php" method="POST">
SOMATECH IT – 0726 674 946 3
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<button type="submit">Send</button>
</form>
</section>
<footer>
<p>© 2025 My Portfolio. All Rights Reserved.</p>
</footer>
</body>
</html>
Explanation
• Header Section: Contains a welcoming heading and a navigation menu linking to various
sections of the website.
• Projects Section: Displays a heading and a description of the developer's projects.
• Contact Section: Contains a form with fields for the user's name, email, and message,
allowing visitors to contact the developer.
• Footer: Includes a copyright notice.
This example demonstrates how HTML can be used to structure a complete and functional
portfolio website, with navigation links, sections for content, and a contact form.
The <!DOCTYPE html> declaration tells the web browser which version of HTML is being
used. It is crucial because it ensures that the page is rendered using modern HTML standards,
avoiding compatibility issues with older browsers.
• Placement: It must appear as the very first line in the HTML document.
• In HTML5: The declaration is simple and case-insensitive:
<!DOCTYPE html>
• Purpose: This declaration prompts browsers to render the page in standards mode rather
than in quirks mode, providing consistent rendering across different browsers.
• The <html> element is the root element that wraps all other HTML content.
• It usually includes a lang attribute, which specifies the language of the document.
<html lang="en">
<!-- Document content goes here -->
</html>
The <head> section contains metadata and resources that are not directly visible on the webpage
but are important for the document's functioning and SEO (Search Engine Optimization).
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>My Web Page</title>
<link rel="stylesheet" href="[Link]">
</head>
The <body> section contains the visible content of the webpage, including text, images, videos,
and other multimedia elements.
Example:
<body>
<h1>Welcome to My Website</h1>
<p>This is a sample paragraph.</p>
</body>
The <title> element specifies the title of the document, which is displayed in the browser's tab
and used by search engines for indexing.
Example:
Meta tags provide additional information about the webpage that helps browsers and search
engines process the content.
<meta charset="UTF-8">
The <link> element is used to link external resources, such as CSS stylesheets, to the document.
• Common Attributes:
o rel: Defines the relationship between the document and the linked resource (e.g.,
"stylesheet").
o href: Specifies the URL of the linked resource.
Example:
Here’s a comprehensive example of a basic HTML document that incorporates all of the discussed
elements:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>HTML Basic Structure</title>
<link rel="stylesheet" href="[Link]">
</head>
Summary
This template highlights the essential structural components needed to create a functional HTML
document. By understanding how to properly use the <!DOCTYPE html> declaration, <html>,
<head>, and <body> elements, you can ensure that your web pages are well-formed, accessible,
and ready for browsers to render correctly. This foundation is crucial for creating web pages that
are both visually appealing and maintainable.
HTML provides a variety of elements for structuring and formatting text on a webpage.
Understanding these elements is essential for creating well-organized, readable, and visually
appealing content.
Headings are used to define the titles and subtitles of a webpage, helping to organize content
hierarchically. HTML offers six levels of headings, with <h1> representing the most important
and <h6> the least.
• Usage:
o <h1> is typically reserved for the main title of the page or section.
Example:
<h1>Main Heading</h1>
<h2>Subheading Level 2</h2>
<h3>Subheading Level 3</h3>
<h4>Subheading Level 4</h4>
<h5>Subheading Level 5</h5>
<h6>Subheading Level 6</h6>
The <p> element defines a block of text and is commonly used to group content into readable
paragraphs. Web browsers automatically add some space between paragraphs for better
readability.
Example:
The <br> element is used to insert a line break within a block of text. It doesn't create a new
paragraph, making it ideal for situations where you need to break the text without starting a new
block.
Example:
• Bold Text:
o <b>: Used to make text bold for stylistic purposes, without conveying any special
importance.
Examples:
3.5 Lists
Lists are used to organize related items, either in a specific order or without any particular order.
HTML provides three types of lists:
An ordered list displays a set of items in a numbered sequence, useful for instructions, rankings,
or items that need to follow a specific order.
• Usage: Each item in an ordered list is defined using the <li> (list item) element.
Example:
<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
An unordered list displays a set of items without any specific order, using bullet points by default.
• Usage: Each item in an unordered list is also defined with the <li> element.
Example:
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
A definition list is used to display terms and their corresponding definitions. It consists of <dt>
(definition term) for the term and <dd> (definition description) for the definition.
Example:
<dl>
<dt>HTML</dt>
<dd>Hypertext Markup Language</dd>
<dt>CSS</dt>
<dd>Cascading Style Sheets</dd>
</dl>
Summary
These HTML text and formatting elements help structure and present content in a readable and
organized way. Whether you are defining headings, creating paragraphs, formatting text with bold
or italic styles, or organizing items into lists, using these elements correctly ensures that your
webpage is both functional and visually appealing. By employing these elements, you create a
more user-friendly and accessible web experience.
• Hyperlinks (<a>)
o Anchor Links
o External and Internal Links
• Navigation Bar Basics
HTML provides powerful tools for linking web pages and creating navigational structures. This
section covers hyperlinks and basic navigation bar concepts.
The <a> (anchor) element is used to create hyperlinks, allowing users to navigate to other web
pages or sections of the same page.
Example:
Anchor links enable navigation within the same webpage by linking to specific sections marked
by id attributes.
Example:
Example:
Example:
A navigation bar is a collection of links that help users navigate a website. Typically, it is structured
using <nav>, <ul>, and <li> elements.
Example:
Explanation:
Navigation bars can be styled with CSS to enhance usability and appearance.
<style>
nav ul {
list-style: none;
display: flex;
background-color: #333;
}
nav ul li {
margin: 0 15px;
}
nav ul li a {
color: white;
text-decoration: none;
}
nav ul li a:hover {
text-decoration: underline;
}
</style>
This setup covers the fundamentals of links and navigation in HTML, providing essential tools for
building user-friendly and interconnected web pages.
In HTML, images, audio, video, and external media can be included with the following elements
and attributes:
Example:
2. Audio (<audio>)
• The <audio> tag is used to embed sound content in a document, such as music or other
audio files.
o Attributes:
▪ controls: Adds audio controls (like play, pause, etc.).
▪ src: Specifies the path to the audio file.
Example:
<audio controls>
<source src="audio.mp3" type="audio/mp3">
Your browser does not support the audio element.
</audio>
Example:
• The <iframe> tag is used to embed external content like other web pages, videos, and
more.
o Attributes:
▪ src: Specifies the URL of the content to be embedded.
▪ width: Specifies the width of the iframe.
▪ height: Specifies the height of the iframe.
Example:
<iframe src="[Link]
width="560" height="315"></iframe>
These HTML tags are essential for embedding multimedia content within a webpage.
The <form> element is a container for all user input elements such as text fields, checkboxes,
radio buttons, and buttons. It represents an interactive form used to collect and submit user data.
Attributes:
• action: Specifies the URL to which the form data will be sent when the form is
submitted. This is required for the form to know where the data should go after submission.
o Example: action="submit_form.php"
• method: Specifies the HTTP method to be used when sending the form data. There are
two main methods:
o GET: Appends form data to the URL, usually for non-sensitive data.
o POST: Sends form data as part of the HTTP request body, typically used for
sensitive or large amounts of data.
o Example: method="POST"
• name: Defines the name of the form. It can be useful if you want to access the form
dynamically through JavaScript.
o Example: name="contactForm"
Example:
The <input> element is one of the most used HTML elements in forms. It is a versatile tag that
allows for various types of user input, such as text, password, radio buttons, checkboxes, and more.
Attributes:
Example:
The <select> element is used to create a dropdown list, allowing the user to choose from
multiple options. Each option within the dropdown is defined by the <option> element.
Attributes:
• name: Defines the name of the select element. This is important for submitting the form
data.
o Example: name="country"
• multiple: When included, this attribute allows users to select more than one option at a
time.
o Example: multiple
Example:
<select name="country">
<option value="usa">United States</option>
<option value="canada">Canada</option>
<option value="uk">United Kingdom</option>
</select>
The <textarea> element is used for multi-line input, such as when a user needs to type a
paragraph or message. Unlike <input>, <textarea> is typically used for larger blocks of text.
Attributes:
Example:
5. Buttons (<button>)
The <button> element is used to create clickable buttons. These buttons can trigger different
actions like submitting the form or resetting form fields.
Attributes:
Example:
<button type="submit">Submit</button>
The <fieldset> element is used to group related elements within a form, providing a visual
structure. The <legend> element provides a title or description for the group of form elements.
SOMATECH IT – 0726 674 946 18
Attributes
• name: Defines the name of the fieldset (although not often used in modern practice).
Example:
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
</fieldset>
7. Form Validation
HTML5 includes built-in form validation features that help ensure users provide correct input
before submitting the form. These validations can be set with attributes.
• required: Specifies that the field must be filled out before the form can be submitted.
o Example: required
• pattern: Specifies a regular expression that the input must match. This is used for more
specific validation, such as ensuring an input matches an email format or a custom pattern.
o Example: pattern="[A-Za-z]{3,}"
• min, max: Defines the range of acceptable values for numeric inputs.
o Example: min="18" max="100"
• maxlength: Defines the maximum number of characters allowed in a text field.
o Example: maxlength="50"
Example:
<label for="email">Email:</label>
<input type="email" id="email" name="email"
required><br>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" cols="50"
required></textarea><br>
<button type="submit">Submit</button>
</fieldset>
</form>
This form includes fields for name, email, and a message, and it validates that the fields are filled
out before submission.
HTML tables are used to represent tabular data (such as a list of items or statistics) in a structured
format. A table is composed of rows and columns. Below are the essential components of a table:
Table Element:
• <table>: This is the container element for the entire table structure. It is used to define a
table.
Example:
<table>
<!-- Rows and columns go here -->
</table>
• <tr>: Represents a row in the table. A table can have multiple <tr> elements inside it,
each representing a row.
SOMATECH IT – 0726 674 946 20
Example:
<tr>
<!-- Cells go here -->
</tr>
• <td>: Defines a table cell that holds data. Each <td> is placed inside a <tr>, and each
<tr> represents a row of data in the table.
Example:
<td>John Doe</td>
<td>30</td>
<td>USA</td>
• <th>: Defines a header cell in the table, typically used for titles or headings of columns
or rows. The content of a <th> is bold by default, and it is centered in the cell.
Example:
<th>Name</th>
<th>Age</th>
<th>Country</th>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>John Doe</td>
<td>30</td>
<td>USA</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>28</td>
<td>Canada</td>
This creates a table with 3 columns (Name, Age, Country) and 2 rows of data.
There are several attributes that can be used to enhance the appearance and behavior of tables.
Although HTML5 recommends using CSS for table styling, some older attributes are still
supported.
border:
• The border attribute is used to define the thickness of the border around the table cells.
It takes a value in pixels, which represents the width of the border.
o Example: border="1"
Example:
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>John Doe</td>
<td>30</td>
<td>USA</td>
</tr>
</table>
cellpadding:
• The cellpadding attribute defines the space between the content of a cell and its border.
It is set in pixels.
o Example: cellpadding="10"
Example:
In this case, there will be 10 pixels of space between the text in each cell and its border.
cellspacing:
• The cellspacing attribute defines the space between each cell. It is also specified in
pixels.
o Example: cellspacing="5"
Example:
To create more semantic and accessible tables, HTML5 introduced grouping elements that allow
you to divide the table into different sections: the header, body, and footer. This is particularly
useful for complex tables with large amounts of data.
• The <thead> element groups the header content of the table. It typically contains the
table headings (<th>) that describe the data in each column.
• This element can be styled separately from the rest of the table and can also be fixed on
scrolling when combined with CSS.
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
</thead>
• The <tbody> element contains the body of the table, which holds the actual data
represented by <td> elements. It is used to group the data rows (<tr>).
• This allows browsers and assistive technologies to distinguish between header and body
content.
Example:
<tbody>
<tr>
<td>John Doe</td>
<td>30</td>
<td>USA</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>28</td>
<td>Canada</td>
</tr>
</tbody>
• The <tfoot> element is used to group footer content. It often contains summary
information or totals for columns, such as a total amount in a financial table.
• Like the header, the footer can be styled separately, and it can be displayed at the bottom
of the table when data is too large and requires scrolling.
Example:
<tfoot>
<tr>
<td>Total</td>
<td>58</td>
<td>-</td>
• Basic Table Structure: The <table> tag holds rows (<tr>), and each row holds either
data cells (<td>) or header cells (<th>).
• Table Attributes:
o border: Controls the thickness of the table border.
o cellpadding: Adds space between cell content and the cell border.
o cellspacing: Adds space between adjacent cells.
• Table Sections:
o <thead>: Groups header content.
o <tbody>: Groups body content (data rows).
o <tfoot>: Groups footer content (such as totals or summaries).
These elements allow developers to structure tables semantically, making them more accessible,
maintainable, and visually appealing.
Semantic HTML elements help to structure the content of a web page in a meaningful way, which
improves accessibility, search engine optimization (SEO), and maintainability of the code.
<section> (Section):
• The <section> element is used to group related content within a webpage. Each section
typically has its own heading and represents a thematic grouping of content. It’s used for
organizing the content into distinct sections, like chapters in a book or groups of content in
an article.
• Example uses: news sections, feature sections, or grouped content on a page.
Example:
<section>
<h2>Latest News</h2>
<article> (Article):
• The <article> element is used to represent a standalone piece of content that can be
distributed independently or reused. Articles are typically used for blog posts, news
articles, or user-generated content.
• An <article> is typically a complete, self-contained unit of content that could exist on
its own.
Example:
<article>
<h2>How to Improve Your Website’s SEO</h2>
<p>In this article, we will explore ways to improve your
website's visibility...</p>
</article>
<aside> (Aside):
• The <aside> element represents content that is tangentially related to the content around
it. This is often used for sidebars, related links, advertisements, or additional information
that is relevant but not central to the main content.
• Asides can be included within sections, articles, or other content areas to offer additional
context or supplementary information.
Example:
<aside>
<h3>Related Articles</h3>
<ul>
<li><a href="#">SEO Tips</a></li>
<li><a href="#">Optimizing for Mobile</a></li>
</ul>
</aside>
<header> (Header):
• The <header> element represents the introductory content or navigational links for a
section or the entire page. A page can have multiple headers, but the most common one is
the header for the entire document, which typically contains the website logo, main
navigation, and title.
<header>
<h1>Website Title</h1>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
</ul>
</nav>
</header>
<footer> (Footer):
• The <footer> element represents the footer of a section or the entire page. It usually
contains information like copyright notices, contact information, or links to privacy
policies.
Example:
<footer>
<p>© 2025 My Website. All rights reserved.</p>
</footer>
<main> (Main):
• The <main> element represents the primary content of the document. There should only
be one <main> element per page, and it excludes content like headers, footers, and
sidebars. It is the part of the document that is directly related to or expands upon the central
topic of the page.
Example:
<main>
<h2>Welcome to My Website</h2>
<p>This is the main content of the page...</p>
</main>
Inline elements do not cause a line break and can be placed within other block-level elements.
They are generally used for small portions of content like text or links that need to be styled or
identified separately without affecting the flow of the document.
<span> (Span):
• The <span> element is a generic inline container used to apply styles or group small
chunks of text. It does not inherently have any meaning and is often used with CSS to style
or manipulate specific parts of text or content.
• Example uses: highlighting part of a paragraph, styling a specific word, or marking inline
text for JavaScript manipulation.
Example:
In this case, the word "quick" is wrapped with a <span> to apply red color styling.
<mark> (Mark):
• The <mark> element is used to highlight text that is relevant to the user's current context,
such as a search result or keyword match. The content inside the <mark> tag is typically
highlighted with a yellow background by default.
Example:
The word "best" is highlighted because it is marked with the <mark> element.
Accessibility:
• Screen Readers: Semantic HTML elements like <header>, <footer>, <main>, and
<section> provide a clearer structure to assistive technologies, such as screen readers,
making it easier for visually impaired users to navigate the page. Screen readers can
interpret the meaning of the page structure, helping users to quickly understand the layout
and find the information they need.
Other Benefits
• Maintainability: Semantic HTML elements make the code more readable and easier to
maintain, especially in large websites. Developers can quickly identify the purpose of
different sections of a page, which is beneficial for collaboration and long-term code
maintenance.
• Mobile Accessibility: Semantic HTML provides a consistent structure across devices,
ensuring that mobile users can also benefit from well-structured, accessible content.
• Sectioning Elements:
o <section>: Groups related content.
o <article>: Represents standalone content.
o <aside>: Contains tangentially related content, like sidebars.
o <header>: Defines introductory content or navigation.
o <footer>: Defines footer content (like copyright or contact info).
o <main>: Represents the main content of the page, excluding headers, footers, and
sidebars.
• Inline Elements:
o <span>: A generic inline container used for styling or small chunks of text.
o <mark>: Highlights text, typically used for search results or relevant content.
Using semantic HTML not only makes your website more accessible and SEO-friendly but also
improves the overall user experience and helps with future scalability.
SVG (Scalable Vector Graphics) is an XML-based markup language used for creating vector
graphics. SVGs are resolution-independent, which means they can scale to any size without losing
quality, making them ideal for high-resolution displays and responsive designs.
What is SVG?
• SVG is used to define vector-based graphics directly in the browser using XML. Unlike
raster images (like JPEG or PNG), SVG images are composed of paths, lines, curves, and
shapes that are defined by mathematical expressions, making them infinitely scalable.
• SVGs are used for various graphical elements such as icons, logos, illustrations, and
diagrams.
• <circle>: Draws a circle. You define its center (cx, cy) and radius (r).
• <rect>: Draws a rectangle. You define its position (x, y), width (width), and height
(height).
• <line>: Draws a straight line between two points (x1, y1 to x2, y2).
• <path>: Defines more complex shapes with specific paths, curves, and lines.
Benefits of SVG
The <canvas> element in HTML5 is used for rendering dynamic graphics on the fly using
JavaScript. It is essentially a blank area in which you can draw and manipulate graphics, such as
shapes, images, and animations, through the HTML5 canvas API.
SOMATECH IT – 0726 674 946 32
What is the <canvas> Element?
• The <canvas> element does not have any visual content by itself. It creates an area in
the web page where graphics can be drawn using JavaScript.
• Unlike SVG, which is based on markup and handles vector graphics, <canvas> is a
bitmap-based approach where you draw pixels directly.
This example defines a canvas with a width and height of 200 pixels.
Drawing on Canvas
You use JavaScript to interact with the <canvas> element and draw shapes, images, or even
animations. The CanvasRenderingContext2D object provides methods for drawing and
manipulating graphics.
// Draw a rectangle
[Link] = "blue"; // Set the color to blue
[Link](10, 10, 150, 100); // Draw a rectangle at (10,
10) with width 150 and height 100
// Draw a circle
[Link]();
[Link](300, 50, 40, 0, 2 * [Link]); // Draw a circle at
(300, 50) with radius 40
[Link] = "red";
[Link]();
</script>
In this example
[Link] = function() {
[Link](img, 0, 0, 100, 100); // Draw the image on
the canvas
}
</script>
In this example, the image is drawn to the canvas once it has loaded.
Benefits of Canvas
• Dynamic and Interactive: Canvas allows for dynamic creation of graphics, which makes
it perfect for applications like games, real-time visualizations, or interactive graphics.
• Pixel Manipulation: Since canvas is pixel-based, you can manipulate every pixel directly
for advanced effects like pixel art or photo editing.
• Performance: Canvas can be more efficient than SVG when working with complex or
dynamic graphics because it doesn’t need to re-render the entire graphic for every small
change.
• SVG Graphics:
o SVG is a vector graphics format that allows you to define shapes, paths, and lines
in XML format.
o It is scalable without loss of quality and is useful for static, resolution-independent
images like logos and icons.
o SVGs can be styled with CSS and animated with JavaScript.
• Canvas:
o The <canvas> element allows for drawing dynamic graphics on a web page using
JavaScript.
o It is pixel-based, ideal for real-time applications like games, visualizations, and
animations.
o Canvas is flexible and can be used to manipulate every pixel, making it suitable for
complex, interactive graphics.
Both SVG and Canvas have their unique strengths and can be used together to build interactive,
visually rich web applications depending on the requirements.
HTML attributes provide additional information about HTML elements and modify their behavior
or appearance. They are always specified in the opening tag and come in key-value pairs.
• Purpose: The class attribute is used to assign one or more class names to an element,
which can be targeted by CSS styles and JavaScript for styling or manipulation.
• Usage: It allows you to apply the same style to multiple elements that share the same class
name.
Example:
<div class="container">
<p class="highlighted">This is highlighted text.</p>
</div>
In this example, both the <div> and <p> elements have class attributes, allowing them to be
styled together or individually.
id Attribute
• Purpose: The id attribute uniquely identifies an element on the page. Each id must be
unique within a document.
• Usage: It is often used for element targeting in CSS, JavaScript, and anchor navigation.
Example:
Here, the paragraph is given a unique identifier (id="intro") which can be referenced by CSS
or JavaScript.
title Attribute:
Example:
When a user hovers over the link, a small tooltip will appear with the text "Visit [Link]."
style Attribute:
Example:
Here, the style attribute applies inline styles directly to the <p> element, making its text blue
and adjusting its font size.
Data attributes provide a way to store custom data for an element. They allow you to store extra
information that doesn't affect the rendering of the page. Data attributes are often used for adding
data that can be accessed via JavaScript.
• Purpose: The data-* attributes are used to embed custom data in HTML elements. The
* can be replaced with any name you choose, and it can store any string of information.
• Usage: Data attributes do not influence the element's behavior or appearance, but they can
be accessed and manipulated using JavaScript to add dynamic functionality.
Example:
In this example
• The div element has two data attributes: data-user and data-role, which store the
user ID and role information.
You can retrieve the value of data attributes using JavaScript through the dataset property.
<script>
const userInfo = [Link]('user-info');
[Link]([Link]); // Outputs: 123
[Link]([Link]); // Outputs: admin
</script>
Here, the dataset property provides easy access to the data attributes (data-user and data-
role), allowing you to manipulate or use them dynamically within your JavaScript code.
• Store Custom Data: They offer a way to store extra data that is associated with an element
but isn't part of the content or visible to the user.
• Interaction with JavaScript: Data attributes allow you to store information that can later
be accessed by JavaScript, enabling dynamic page behavior.
• No Need for Additional Markup: Data attributes eliminate the need for extra HTML
elements (like hidden <input> fields) for storing data.
3. Global Attributes
Global attributes are attributes that can be used on any HTML element. These attributes apply
universally across all elements, and not just to a specific type of tag.
HTML attributes provide critical metadata and additional functionality for web elements, making
the content more interactive, accessible, and customizable. Data attributes offer a flexible way to
store and interact with custom data in a web page.
• Geolocation API
• Drag and Drop API
• Web Storage API (LocalStorage and SessionStorage)
1. Geolocation API
The Geolocation API allows web applications to access the geographical location of a user's
device. This API is commonly used in applications such as maps, location-based services, and
geotagging.
• The Geolocation API provides a way to retrieve the user's current geographic location,
which can include latitude, longitude, altitude, and other location-related information.
• This data is useful for building features like location-aware maps, location-based
recommendations, or gathering geographical data for analytics.
To use the Geolocation API, you can call the [Link] object and its
methods:
<p id="location"></p>
<script>
function getLocation() {
if ([Link]) {
[Link](showPosition,
showError);
} else {
[Link]("location").innerHTML =
"Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
let lat = [Link];
let lon = [Link];
[Link]("location").innerHTML =
"Latitude: " + lat + "<br>Longitude: " + lon;
}
function showError(error) {
switch([Link]) {
case error.PERMISSION_DENIED:
In this example, clicking the button triggers the getLocation() function, which attempts to
retrieve the user's geographic location using
[Link](). If successful, it displays the
latitude and longitude; if not, it shows an error message.
Important Considerations:
• Privacy: Geolocation data is sensitive, so users must grant permission for websites to
access their location.
• Accuracy: The accuracy of location data can vary depending on the device and method
used (e.g., GPS, Wi-Fi, IP address).
• Error Handling: Proper error handling is important to inform users if location data is
unavailable or permission is denied.
The Drag and Drop API allows users to drag and drop elements within a web page. This feature
is commonly used for interactive user interfaces like file uploads, organizing content, or
rearranging elements on a page.
• The Drag and Drop API enables a web page to handle drag events and specify elements
that can be dragged and dropped.
• It uses event listeners for the dragstart, dragover, dragenter, dragleave, and
drop events to define the drag-and-drop behavior.
1. Draggable Element: The element that the user can drag. This can be specified with the
draggable attribute or JavaScript.
2. Drop Target: The area where the dragged item can be dropped. This is typically an HTML
element where a user can place a dragged item.
<script>
function allowDrop(ev) {
[Link](); // Prevent the default behavior
(e.g., opening as link for some elements)
}
function drag(ev) {
[Link]("text", [Link]); //
Store the ID of the dragged element
}
function drop(ev) {
[Link]();
var data = [Link]("text"); // Get the
stored data (ID of dragged element)
var draggedElement = [Link](data);
[Link](draggedElement); // Append the
dragged element to the drop target
}
</script>
In this example
• The div with the ID drag1 is draggable, and when it’s dragged, the dragstart event
stores its ID in the data transfer object.
• The div with the ID div2 serves as the drop target, and it uses the drop event to append
the dragged element inside it.
The Web Storage API provides storage options in the browser that allow data to persist on the
client side. There are two main types of web storage:
• LocalStorage
• SessionStorage
These storage options are typically used for saving user data, preferences, session states, and more.
The Web Storage API provides a way to store data as key-value pairs in the user's browser,
allowing you to persist data across page reloads and sessions.
• LocalStorage: Stores data with no expiration time. The data remains available even after
the browser is closed and reopened.
• SessionStorage: Stores data for the duration of the page session. Once the browser or tab
is closed, the data is cleared.
Basic Usage
Example
<script>
function saveData() {
[Link]("username", "john_doe");
}
In this example
Example
<script>
function saveSessionData() {
[Link]("sessionID", "12345");
}
function retrieveSessionData() {
let sessionID = [Link]("sessionID");
alert("Stored session ID: " + sessionID);
}
</script>
In this example:
Key Methods
Important Considerations
• Storage Limitations: Both LocalStorage and SessionStorage have storage size limits
(typically around 5-10MB).
• Security: Data stored in web storage is not encrypted and can be accessed by JavaScript
running on the same domain. Sensitive data should not be stored here.
• Persistence: localStorage persists across browser sessions, whereas
sessionStorage is cleared when the page session ends.
• Geolocation API: Allows web applications to retrieve the user's geographic location
(latitude, longitude, etc.) using the [Link] object.
• Drag and Drop API: Enables users to drag and drop elements within a web page,
supporting interactive UIs like file uploads or element reordering.
• Web Storage API: Provides two types of storage: localStorage for data persistence
across sessions and sessionStorage for temporary data storage during a single
session.
These HTML APIs and advanced features enable the creation of more interactive, dynamic, and
personalized web applications that can respond to the user's actions and provide richer experiences.
Proper indentation refers to the consistent use of spaces or tabs to align the code and make it
visually structured. This helps developers (and anyone reading the code) quickly understand its
hierarchy and relationships.
• Improves Code Readability: Proper indentation makes code easier to read, understand,
and maintain.
• Facilitates Collaboration: When multiple developers work on the same codebase, proper
indentation ensures that everyone can easily follow and contribute to the code.
• Helps Debugging: Well-indented code makes it easier to spot errors in logic or structure.
Best Practices:
• Use Consistent Indentation: Choose either spaces or tabs for indentation and stick with it
across the entire project.
• Indent Nested Elements: Any nested HTML elements (inside <div>, <ul>, etc.) should
be indented to show their relationship to parent elements.
• Align Closing Tags: Place closing tags at the same level of indentation as the opening tag.
Example:
<div class="container">
<header>
<h1>Welcome to My Website</h1>
</header>
<main>
<p>This is a paragraph.</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</main>
<footer>
<p>© 2025 My Website</p>
</footer>
</div>
In this example, you can clearly see the hierarchical structure with consistent indentation.
ARIA (Accessible Rich Internet Applications) roles are attributes that can be added to HTML
elements to improve the accessibility of web pages for users with disabilities. ARIA roles help
assistive technologies (like screen readers) understand the purpose and behavior of elements on
the page.
• Inclusivity: Ensures that all users, including those with disabilities, can interact with and
understand the content.
• Legal Compliance: Many countries have laws requiring websites to be accessible, such as
the Americans with Disabilities Act (ADA) in the U.S. and the Web Content Accessibility
Guidelines (WCAG).
• SEO Benefits: Accessible sites are easier for search engines to crawl, improving the
overall SEO.
Best Practices
• Use Semantic HTML: Whenever possible, use native HTML elements like <nav>,
<article>, <header>, and <footer>, which inherently have ARIA roles.
• Apply ARIA Roles: Use ARIA attributes to define the role and state of non-semantic
elements, like divs or spans. For example, a button styled as a div should use
role="button".
• Provide Text Alternatives: Use ARIA attributes such as aria-label, aria-
labelledby, or aria-describedby to provide alternative text for elements that
cannot have visible text, such as icons or images.
Example
<button aria-label="Close"
onclick="closeWindow()">X</button>
In this example, the aria-label provides a text description for the button that will be read by
screen readers, improving accessibility.
Performance optimization ensures that your web pages load quickly and run efficiently, providing
a better user experience and improving SEO. Slow pages can frustrate users and negatively impact
conversion rates.
• Minimize HTTP Requests: Reduce the number of HTTP requests needed to load your
page by combining CSS and JavaScript files and using image sprites.
• Compress Files: Minify CSS, JavaScript, and HTML files to reduce file sizes, which in
turn reduces the time required to download them.
• Optimize Images: Compress images and use appropriate formats (JPEG, PNG, WebP).
Ensure that images are not larger than necessary and use responsive images for different
screen sizes.
• Lazy Loading: Use lazy loading for images and other assets, so they are only loaded when
they are visible in the viewport. This reduces initial page load time.
• Use Caching: Implement browser caching to store assets locally, reducing the need to re-
download resources on subsequent visits.
• Use a Content Delivery Network (CDN): Serve static assets like images, CSS, and
JavaScript from a CDN to reduce load times by distributing content across multiple servers
worldwide.
Example
In this example, the loading="lazy" attribute ensures that the image is only loaded when it
becomes visible in the viewport.
4. Cross-browser Compatibility
Cross-browser compatibility refers to the practice of ensuring that a web page works consistently
across different browsers (like Chrome, Firefox, Safari, Edge) and devices (desktops, smartphones,
tablets).
Why is it Important?
• User Experience: Ensures that all users, regardless of their browser or device, can access
and use the website without issues.
• Market Reach: Increases the potential audience by supporting various browsers and
devices, some of which may be preferred by different users.
• Consistent Appearance: Ensures that your website looks and functions as intended on all
platforms.
• Use Vendor Prefixes: Some CSS properties may require vendor prefixes for different
browsers (e.g., -webkit- for Safari/Chrome, -moz- for Firefox).
• Test Across Browsers: Regularly test your site on multiple browsers and devices to ensure
consistent performance and appearance.
• Graceful Degradation: Ensure that the core functionality of the website remains usable,
even if some advanced features don't work in older browsers.
• Feature Detection: Use JavaScript libraries like Modernizr to detect which features are
supported in the user’s browser and provide fallbacks or alternatives.
• Avoid Browser-Specific Features: Stick to standard HTML, CSS, and JavaScript to avoid
browser-specific quirks or incompatibilities.
Example:
In this example, the -webkit- and -moz- prefixes ensure that the transition property works in
Webkit-based (Safari/Chrome) and Gecko-based (Firefox) browsers, while the standard
transition property works in other modern browsers.
By following these best practices, you can create websites that are well-structured, accessible,
performant, and compatible across different browsers and devices, providing a seamless user
experience for all.
CSS is used to style HTML elements. To keep your HTML and CSS code separate and
maintainable, it's common to link external CSS files to your HTML document.
• Linking CSS in the <head> Section: Use the <link> tag to reference an external CSS
file. The href attribute specifies the path to the CSS file, and the rel="stylesheet"
attribute defines the relationship between the document and the linked file.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>My Website</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Welcome to My Website</h1>
</body>
</html>
In this example, the [Link] file is linked in the <head> section, which means all the styles
defined within that file will be applied to the HTML content.
JavaScript is used to add interactivity to your web pages. To link an external JavaScript file, use
the <script> tag with the src attribute pointing to the JavaScript file.
• Placing JavaScript at the Bottom: It is a common practice to place the <script> tag
right before the closing </body> tag, to ensure that the page content is loaded before the
JavaScript is executed.
SOMATECH IT – 0726 674 946 50
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>My Website</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<script src="[Link]"></script>
</body>
</html>
In this example, the [Link] file is linked at the end of the body section, ensuring that the
HTML content is loaded before the script is executed.
Inline CSS
Inline CSS is defined directly within an HTML element using the style attribute. It is typically
used for quick, small styles on a single element.
• Use Case: Inline CSS is useful when you need to apply a style to just one specific element,
but it should be avoided for large-scale styling because it mixes content with presentation
and makes the code harder to maintain.
Example:
In this example, the <p> element has the styles color: red and font-size: 20px directly
applied via the style attribute.
Internal CSS
Internal CSS is written within the <style> tag in the HTML document's <head> section. It is
used to apply styles to elements on a specific page and keeps the HTML and CSS separated, while
still being part of the same file.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>My Website</title>
<style>
body {
background-color: lightblue;
}
h1 {
color: navy;
text-align: center;
}
</style>
</head>
<body>
<h1>Welcome to My Website</h1>
</body>
</html>
In this example, the <style> tag within the <head> section contains the internal CSS, which is
applied to the body and heading elements.
JavaScript can be added to an HTML page in two primary ways: inline within an element (using
the onclick, onchange, etc. attributes) or by using the <script> tag to reference external
JavaScript files.
You can add JavaScript directly within HTML elements by using event handler attributes like
onclick, onmouseover, etc. This approach is useful for simple interactions.
In this example, when the button is clicked, an alert box appears with the message "Button
clicked!" thanks to the inline JavaScript function defined within the onclick attribute.
To add JavaScript code within your HTML file, use the <script> tag. JavaScript can be placed
either in the <head> or at the end of the <body> section.
• Inline JavaScript: You can write JavaScript directly between the <script> tags.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>My Website</title>
<script>
function showMessage() {
alert('Hello, this is a message!');
}
</script>
</head>
<body>
<button onclick="showMessage()">Click Me</button>
</body>
</html>
In this example, the showMessage() function is written inside the <script> tag, and when
the button is clicked, it triggers the function, displaying the alert.
• External JavaScript: It's a better practice to keep JavaScript code in a separate file and
link to it from the HTML document.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
In this example, the [Link] file contains the JavaScript code, and it is linked in the <head>
section. The function showMessage() would be defined in the external JavaScript file.
• Place JavaScript at the End of the Body: To ensure that HTML elements are loaded
before JavaScript is executed, it’s generally a good practice to place <script> tags just
before the closing </body> tag.
Example:
<body>
<h1>Welcome to My Website</h1>
<script src="[Link]"></script>
</body>
• Use defer or async for External Scripts: If you must place the <script> tag in the
<head>, use the defer attribute to ensure the script executes after the HTML document
is fully parsed, or async to load the script asynchronously.
Example:
• Linking External CSS and JS Files: Use <link> for external CSS files and <script>
for JavaScript files to separate concerns and maintain modular code.
• Inline and Internal CSS: Inline CSS is used for styling individual elements, while internal
CSS is placed in the <style> tag in the document's <head> section for page-specific
styles.
• Using JavaScript in HTML: JavaScript can be added inline via event attributes or
included using <script> tags, either embedded in the HTML or linked as an external
file. External JavaScript is preferred for maintainability and performance.
SOMATECH IT – 0726 674 946 54
By properly integrating CSS and JavaScript, you can build dynamic, interactive, and well-styled
web pages while keeping your code organized and maintainable.
Developer tools (DevTools) are built-in tools provided by most modern web browsers (such as
Chrome, Firefox, and Edge) that allow developers to inspect, debug, and analyze their web pages.
These tools are essential for troubleshooting and optimizing web pages during the development
process.
Example: Right-click on an element and select "Inspect" to view its HTML and CSS in
the browser.
2. Console
o The Console Panel is used to view logged messages, warnings, and errors in your
JavaScript code. It's a useful tool for debugging JavaScript issues, testing snippets
of code, and reviewing logs.
o It can also be used to interact with the JavaScript runtime directly by typing
commands.
Example: Set a breakpoint in the code and refresh the page to pause at the breakpoint for
detailed inspection.
• Inspect HTML Structure: You can view how the HTML is rendered and check for
missing or misplaced elements.
• Edit CSS: You can dynamically modify the page's CSS to test changes without needing to
refresh the page, which speeds up the process of troubleshooting layout and styling issues.
• View Console Errors: Errors related to HTML, CSS, or JavaScript are displayed in the
console, helping you quickly pinpoint problems.
2. HTML Validators
An HTML Validator is a tool that checks the syntax and structure of your HTML code to ensure
it adheres to the official HTML specifications (W3C standards). Validators help identify errors or
warnings that may affect the functionality or appearance of your web page.
• Ensure Syntax Compliance: HTML Validators check your code for syntax errors (e.g.,
missing closing tags, incorrect nesting) and provide suggestions for corrections.
1. W3C Markup Validation Service: The W3C Validator is the most used validator,
provided by the World Wide Web Consortium (W3C). It checks the validity of your HTML
code against the W3C's official standards.
o To use the W3C Validator, simply enter the URL of your website, or you can
directly upload the HTML file for validation.
Example:
o URL: [Link]
o This tool will scan your HTML and provide a detailed report of any errors,
warnings, and suggestions.
2. HTMLHint: HTMLHint is an open-source HTML linting tool that checks for various
issues, including syntax errors, accessibility problems, and best practices.
o It provides a more configurable set of rules and can be used both online and locally
as part of your development workflow.
o You can integrate HTMLHint into your build tools or IDE (Integrated Development
Environment) to automatically validate HTML files as you write code.
Example:
o URL: [Link]
3. Nu HTML Checker ([Link]): The Nu HTML Checker is a validator that checks
HTML5 documents. It is known for its accuracy and modern HTML5 features.
Example:
o URL: [Link]
• Unclosed Tags: Missing closing tags for elements like <div>, <span>, <p>, etc.
• Unmatched Tags: A tag that is not properly nested or is incorrectly placed.
• Deprecated Elements: HTML elements that are no longer recommended or supported in
modern HTML (e.g., <font>, <center>).
• Attribute Errors: Missing or invalid attributes, such as using the wrong type for href or
src.
In this example, the validator detects that an image is missing the alt attribute, which is important
for accessibility.
1. Upload a File or URL: You can either upload an HTML file directly or enter the URL of
a live webpage for validation.
2. Check for Errors: The validator will provide a report detailing any errors or warnings
found in your HTML.
3. Fix the Issues: Review the errors and make the necessary corrections in your HTML code.
4. Re-Validate: After fixing the issues, re-run the validator to ensure your HTML is now
valid.
By utilizing both Developer Tools for real-time inspection and HTML Validators for
comprehensive code checks, you can debug and test your HTML code efficiently and ensure a
robust, accessible, and well-structured website.
<main> Element:
The <main> element is a structural HTML5 element introduced to define the dominant content
of the <body> of the document. It represents the primary content of the document, excluding
elements like headers, footers, and sidebars.
• Purpose: The <main> element improves document structure, making it clear to browsers
and assistive technologies what the central content is. It helps with accessibility and SEO
because search engines and screen readers can quickly identify the core content of the page.
• Usage: The <main> tag is typically used to wrap the most significant content of a
webpage. It can only appear once per page.
Example:
<body>
<header>
<h1>Website Header</h1>
</header>
<main>
<h2>Main Content Area</h2>
<p>This is where the primary content of the page goes.</p>
</main>
<footer>
<p>Website Footer</p>
</footer>
</body>
<nav> Element:
The <nav> element is another structural HTML5 element that defines a navigation section,
typically used to wrap links or navigation menus. It indicates that the enclosed links are for
navigating the website or document.
Example:
<header>
<h1>My Website</h1>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
HTML5 introduced several new input types that provide enhanced form functionalities, making it
easier to create more interactive and user-friendly forms.
• <input type="email">: Used for entering an email address. Browsers often validate
the email format before submitting.
Example:
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
• <input type="tel">: Allows for phone number input. Browsers may display a
number-specific keyboard on mobile devices.
Example:
<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone">
• <input type="url">: Used for entering URLs. It also validates that the entered value
is in the correct URL format.
<label for="website">Website:</label>
<input type="url" id="website" name="website">
• <input type="date">: Used for selecting a date. This displays a calendar widget for
easy date selection.
Example:
<label for="birthday">Birthday:</label>
<input type="date" id="birthday" name="birthday">
Example:
Example:
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" min="1"
max="10">
• <input type="range">: Used for creating a slider to choose a value from a range.
Example:
<label for="volume">Volume:</label>
<input type="range" id="volume" name="volume" min="0"
max="100">
• <input type="color">: Allows the user to select a color using a color picker.
Example:
These new input types reduce the need for JavaScript to handle common validations and form
enhancements, providing better user experience and interface design.
HTML5 introduced native support for embedding and playing audio and video content without
relying on third-party plugins like Flash.
<audio> Element:
The <audio> element is used to embed sound content such as music, podcasts, or sound effects.
It supports various file formats like MP3, Ogg, and WAV.
• Attributes:
o controls: Adds built-in playback controls (play, pause, volume).
o autoplay: Automatically starts playing when the page loads.
o loop: Loops the audio when it finishes playing.
Example:
<audio controls>
<source src="audio/song.mp3" type="audio/mp3">
Your browser does not support the audio element.
</audio>
<video> Element:
The <video> element allows you to embed video content directly in HTML. It supports formats
like MP4, WebM, and Ogg.
• Attributes:
o controls: Adds built-in video controls (play, pause, volume, fullscreen).
o autoplay: Automatically starts playing the video when the page loads.
o loop: Loops the video when it finishes playing.
o muted: Mutes the audio of the video by default.
Example:
These new HTML5 elements remove the need for plugins like Flash, ensuring better browser
compatibility and user experience.
HTML5 introduced several new elements that allow for better interactivity and user engagement
on web pages.
The <details> element allows you to create a collapsible content block. The <summary>
element is used to define the clickable header that toggles the visibility of the content.
• Purpose: These elements provide a way to show and hide content on demand, improving
the user experience, especially for FAQs, menus, and information that may be secondary.
Example:
<details>
<summary>Click to learn more</summary>
<p>This is some additional information that can be
toggled.</p>
</details>
<progress> Element:
The <progress> element represents a progress bar to indicate the completion of a task (e.g., file
upload or download).
• Attributes:
o value: Specifies the current progress value.
o max: Specifies the maximum value.
Example:
<meter> Element:
The <meter> element represents a scalar measurement within a known range (e.g., disk usage,
temperature, or battery level).
• Attributes:
o value: Specifies the current value.
o min and max: Define the range of the value.
These new features in HTML5 significantly improve the functionality, interactivity, and
accessibility of web pages, making it easier to build modern, dynamic websites without relying on
external plugins.