HTML Essentials
HTML Essentials
HTML is like the skeleton of a website, giving it structure and form. It sets up
everything you see online, from text and images to forms and buttons. Without HTML,
websites would just be plain text without any organization.
•
• Over the years, HTML has evolved and new versions have been introduced,
each bringing new elements, attributes, and features to enhance the capabilities
of web development. HTML 5, the current version, was released in 2014 and
introduced many exciting features such as native multimedia support, semantic
elements, and improved form controls. So, next time you're building a web page,
remember the journey that HTML has taken to become the versatile and powerful
language it is today!
However, using a dedicated text editor specifically designed for coding can greatly
enhance your learning process. Text editors like:
To view an HTML file in a web browser, you can simply double-click on the file in your file
system, and the web browser associated with HTML files should open and display the file.
Alternatively, you can open the web browser and then use its File menu or a keyboard shortcut to
open the HTML file. Once the file is open in the browser, you can interact with its content,
follow links, and navigate between pages, as you would with any other web page.
Open your text editor and create a new file. It's time to give life to your web page! Save
the file with a memorable name and make sure to use the .html extension, such
as sample.html. This tells the computer that it's an HTML file.
Here comes the exciting part! Inside your HTML file, you'll start by adding the essential
structure of an HTML document. We've got you covered with the code you need. Just
copy the following:
<!DOCTYPE html>
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is my first web page.</p>
</body>
</html>
Look at that! You've laid the foundation for your web page. The code sets up the
structure, adds a title, and includes a heading and a paragraph. Feel free to customize
the content to express your creativity and personality.
Don't worry if you're not familiar with all the concepts just yet. We'll cover everything in
detail later in the course, so you'll have a solid understanding. For now, let's focus on
getting started with creating your HTML file and opening it in a web browser. Exciting
times ahead!
Now it's time to see your creation come to life! Save the HTML file and navigate to the
location where you saved it. Double-click on the file, and like magic, it will open in your
default web browser. Voila! You'll see your web page displayed beautifully.
Wow, you did it! You've successfully created and opened your first HTML file. Take a
moment to appreciate your accomplishment and the incredible possibilities that lie
ahead in your web development journey.
Remember, this is just the beginning. The more you practice and explore, the more
you'll learn and discover. We hope you’ll soon have fun experimenting with different
HTML elements, adding images, and playing with styles to make your web page
uniquely yours.
To access Edube Sanbox, simply find and click the Editor button on your screen, or
click the "Run" button next to the HTML code we provide in the course, like this:
Once there, you can edit your code in the editor. With a click of the "Run" button, you'll
see your code come to life. We hope you enjoy it!
Why numbers? Because computers process and store information using electronic
signals, and the signals are represented by binary digits, also known as bits1, which can
only have two possible states: "on" or "off" (represented by 1 or 0). These binary digits
are used to represent all the information that is processed and stored by computers,
such as images, sound, video, and text.
So, when you look at a web page, the text on it needs to be changed into a special
code that computers can understand in order for it to be shown correctly. This is
called character encoding. But before we delve into various character encoding
standards, let's first understand the basics of binary digits and the binary system.
In the binary system, each bit can have only one of two values: 0 or 1. This may seem limited,
but by combining bits in various ways, we can represent and process complex data like text,
images, video, and sound.
The binary system is used in a variety of digital devices and technologies, including computers,
mobile devices, Internet, communication systems, and electronics. For example, a single bit can
represent the state of a light switch: 0 for "off" and 1 for "on".
In the decimal system, you use ten digits (0-9) to represent all numbers. The value of
each digit depends on its position in the number, where each position is ten times the
value of the position to its right. For example, in the number 123, the
digit 1 represents one hundred, the digit 2 represents twenty (two tens), and the
digit 3 represents three units.
In the binary system, you use only two numbers, 0 and 1, to represent all numbers. Just
like how you use the numbers 0-9 in the decimal system, you use these two numbers to
make up all the different numbers in the binary system.
The value of each number depends on its position in the number. Each number in a
binary number represents a power of 2. For example, the first number from the right
represents 20 (which is 1), the second number from the right represents 21 (which is 2),
the third number from the right represents 22 (which is 4), and so on.
And now, to find the decimal value of a binary number, you need to add up the values of
each number, using the powers of 2. For example, in the binary number 1011, the digit
on the right represents 20 (which is 1), the next digit to the left represents 21 (which is 2),
the next digit to the left represents 22 (which is 4), and the leftmost digit represents
23 (which is 8). To calculate the value of the whole number, you now have to add up the
values of each digit:
. 1101
Hide
100101
Hide
11111111
Hide
In the hexadecimal system, you use 16 digits and letters (0-9 and A-F) to represent
all numbers. Each digit's value depends on its position in the number, where each
position is 16 times the value of the position to its right.
In the hexadecimal system, just like the binary system, each digit represents a power of
16. The first digit from the right represents 160 (which is 1), the second digit from the
right represents 161 (which is 16), the third digit from the right represents 162 (which is
256), and so on.
1. 4A
Hide
2. FF
Hide
3. 1B7
Hide
There are several character encoding standards available, each with its own benefits and
limitations.
• ASCII, or the American Standard Code for Information Interchange, is the most basic
character encoding standard. It uses 7 bits to represent 128 characters, which includes
letters, numbers, and symbols commonly used in the English language. However, ASCII
encoding is not suitable for representing characters from other languages.
• Unicode is a more comprehensive character encoding standard that supports a much
larger number of characters from different languages and scripts. It can use up to 32 bits
to represent over a million characters, including those from non-Latin scripts like
Chinese, Arabic, and Cyrillic. Unicode includes several different encodings, including
UTF-8, UTF-16, and UTF-32.
• UTF-8 is a widely used character encoding standard that is compatible with ASCII. It
uses a variable-length encoding that can represent characters using between 1 and
4 bytes2, depending on the character being encoded. UTF-8 can represent all characters in
the Unicode standard, making it an ideal choice for web development.
2
A byte is a unit of digital information that is equivalent to eight bits. Each bit is a binary digit that can be either 0 or 1.
Therefore, a byte is a sequence of eight binary digits (bits), which can represent a range of values from 0 to 255 (28 - 1).
To specify the character encoding standard as UTF-8 in an HTML document, you can use the
following code in the head section of your document: <meta charset="UTF-8">.
This tells the web browser that the document is encoded using UTF-8, and the browser can use
the appropriate decoding algorithm to render3 the characters correctly.
If you are not yet familiar with the terms or how to use them, don't worry - we'll cover them in
more detail later in the course. For now, just remember that it's crucial to use the correct
character encoding standard for your web pages to ensure that all characters are displayed
accurately, and that UTF-8 is a recommended choice for most modern web applications as it can
handle a wide range of characters and is widely supported by browsers and other web tools.
If you’re interested in learning more about UTF-8 encoding and the Unicode character set, visit
the UTF-8 Wiki page for more information and examples.
Similarly, HTML syntax refers to the rules, guidelines, and conventions that define
how HTML code should be structured and written. By following the correct syntax,
you can ensure that your HTML code is properly understood by web browsers and
displayed as intended.
HTML syntax defines the correct way to use HTML tags, attributes, and values (you'll
learn what they are in a few moments) to create web pages that are both readable and
functional by web browsers. Understanding it is essential for creating and maintaining
effective and valid HTML code.
1.5.2 The DOCTYPE declaration
The DOCTYPE declaration is an integral part of HTML syntax and an important element
in an HTML document1 that helps web browsers understand how to interpret the
document's content.
In simple terms, the DOCTYPE declaration tells the web browser which version of
HTML is being used in the document. This is important because different versions of
HTML have different rules and features. By including the DOCTYPE declaration, you
are ensuring that the web browser knows which set of rules to follow when it displays
the web page.
The DOCTYPE declaration is a special line of code that should appear at the very
beginning of an HTML document, before any other content or elements. It consists of
a string of characters2 that identifies the version of HTML being used. The DOCTYPE
declaration for HTML5 is <!DOCTYPE html>:
index.html
<!DOCTYPE html>
This tells the web browser that the document is written in HTML5, and the browser
will therefore expect to see HTML5 syntax and features throughout the rest of the
document.
HTML Elements
HTML Tags
Tags are the markers that define the start and end of an element. They are written with
angle brackets, like <tag> for the start of an element and </tag> (with a forward slash
before the tag name) for the end. Tags label the type of content they enclose,
instructing the browser on how to process it.
For instance, a paragraph is created with a <p> tag, indicating the start, and a </p> tag,
marking the end, with the actual text content in between.
Understanding Tags and Elements
An HTML element encompasses everything from the start tag to the end tag, including
the content and the tags themselves.
In essence, the opening tag marks the start of an element and can include attributes,
which are extra details that configure or adjust the element's behavior. Attributes have a
name and a value, separated by an equals sign, with the value enclosed in quotes. The
content of the element is what's displayed or used, such as text or an image link, and
the closing tag indicates the end of the element.
Self-Closing Tags
Some elements, like the image element (<img>), don't contain content and
therefore don't have a closing tag. These are known as self-closing tags.
For example:
index.html
<img src="image.jpg" alt="Description of the image">
• An element refers to the whole structure, including the opening tag, the
content, and the closing tag (if present). It's what you see rendered on a
webpage.
• A tag refers specifically to the opening and closing markers that define the
start and end of an element. They are not displayed on the webpage but instruct
the browser on how to interpret the content.
HTML offers a variety of tags to organize and display content on the web. The number
of these tags can vary with different versions of HTML, but HTML5 includes over 140
standard tags. Developers can also create custom elements to add new functionalities.
As HTML evolves, the list of available tags and elements changes, introducing new
features and occasionally deprecating older ones. Staying updated with HTML
standards is crucial for creating compatible and efficient web pages.
Through the course, we'll dive deeper into the various elements and tags HTML offers,
helping you to effectively structure and style your web pages.
Block-Level Elements
Block-level elements are used to create the main structure of a web page, such as headers,
paragraphs, and lists. They start on a new line and take up the full width of the page, which
means that any content placed inside a block-level element will create a new block of content,
separate from the content before or after it.
Inline Elements
Inline elements, on the other hand, are used to style content within block-level elements, such
as links and images. They don't start on a new line and only take up as much space as needed to
display their content. This means that multiple inline elements can appear on the same line,
separated by a space.
HTML comments are a way to add notes or remarks in an HTML document that won't be
visible to the user. Comments can be used to explain what certain parts of the code do or
to temporarily disable parts of the code during development.
To create a comment, you simply need to enclose the text you want to comment out
between <!-- and -->.
For example:
index.html
<!-- This is a comment. -->
Now, let's try something out. What do you think will show up on the webpage? Go ahead, run
the code to find out.
index.html
<p>This is paragraph one.</p>
<!--
<p>This is paragraph two.</p>
-->
In the example, you'll see that only the first paragraph <p>This is paragraph
one.</p> appears on the webpage because it's not inside comment tags. But the second
paragraph <p>This is paragraph two.</p> is inside comment tags, so it's hidden from
view.
As you learn more about HTML in this course, you'll find that commenting out code is a useful
trick. It lets you temporarily turn off or hide specific parts of your code without deleting them.
This can be really helpful for testing and fixing different parts of your HTML without messing
up your whole webpage.
You can add attributes to an HTML element by using the attribute name, followed by an
equal sign and the attribute value. The value can be enclosed in quotes, single quotes,
or left unquoted, depending on the specific attribute and the values it accepts.
For example, the <img> tag is used to insert an image in an HTML document. It has
several attributes that can be used to specify the source of the image, its width and
height, the text description for accessibility purposes, and other properties.
The most commonly used attributes for <img> are the src attribute, which specifies the
path to the image file, and the alt attribute, which provides a text description of the
image that is displayed when the image cannot be loaded or seen. Here's an
example: <img src="image.jpg" alt="A detached house">.
Attributes are a key feature in HTML and can be used with almost all HTML elements.
They allow developers to customize the behavior and appearance of HTML
elements with greater precision and flexibility. They can be used to specify the color,
size, and other properties of text, as well as to define links, forms, and multimedia
elements. Given their versatility and importance, attributes are a fundamental aspect of
building web pages and applications.
• global attributes, which can be applied to any HTML element. They are useful
for a wide range of purposes, such as assigning unique identifiers, adding
classes for styling, or providing additional information about an element.
Examples include id, class, style, and title.
• element-specific attributes, which are specific to particular HTML elements and
cannot be used with all elements. They provide functionality or modify the
behavior of specific elements, making them essential for proper usage of those
elements. Examples include href (specific to <a> elements), src (specific
to <img> and media elements), and type (specific to <input> elements).
These elements set the stage for the content and functionality of your web page. By
understanding the role and implementation of each tag, you'll be able to effectively
structure your HTML documents, ensuring proper display and behavior in web
browsers.
The HTML tag is an opening tag that comes at the beginning of the document and a
closing tag that comes at the end. Everything in the document appears between these
two tags, and it does not have any attributes associated with it.
index.html
<!DOCTYPE html>
<html>
<!-- The hidden content of an HTML document: the head section will
go here. -->
<!-- The visible content of an HTML document: the body section will
go here. -->
</html>
Note: The HTML tag appears after the <!DOCTYPE html> declaration, and it's opened
with the <html> tag. The HTML tag encompasses the entire document, and all the
content on the web page appears between the opening and closing HTML tags. The
closing HTML tag is denoted by </html> and appears at the end of the document.
1.7.3 The Head Section
The head section is an important component of an HTML document that contains information
used by the browser to display and interact with the web page. It can optimize the web page
for search engines and furnish additional context to users. The head section is hidden from the
user's view and does not appear on the web page (it is a background portion of the document that
operates behind the scenes).
Some of the key pieces of information that can be included in the head section are:
• Page title, i.e. the title of the web page that appears in the title bar of the browser and is
used by search engines to display the page title in search results.
• Metadata, which includes the description and keywords that are used by search engines
to index and rank the web page, instructions for web crawlers how to index and display
the web page, or information about the author and creation date of the page.
• Links to external files, which includes CSS stylesheets and JavaScript files that add
styling and functionality to the web page.
Example: <link rel="stylesheet" href="styles.css"> <script
src="script.js"></script>
• Character encoding, which tells the browser what character set to use when displaying
the web page. (You already know that, don’t you?)
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<meta name="description" content="This is a website about
soccer!">
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<!-- The visible content of an HTML document: the body section will
go here. -->
</html>
Note that the head section is enclosed by the <head> and </head> tags.
Examples of content that you can include in the body section are:
• Text: You can use headings, paragraphs, and other text elements to present your content
to the user.
• Images: You can include all types of images, such as photos, icons, and logos, to make
your web page visually appealing.
• Videos: You can add video content, such as tutorials and product demos, to provide more
information to the user. Videos are a great way to engage users and provide a more
interactive experience.
• Forms: You can create elements that allow users to submit information, such as text
boxes, dropdown menus, and buttons, to gather data from the user.
• Links: You can include links to other pages on the web or within the same website,
making it easier for the user to navigate through your content.
• Lists: You can use lists to organize content, including unordered and ordered lists. Lists
can be used to break up content into smaller, more manageable chunks, making it easier
for users to read and understand.
• Tables: You can use tables to present data in a structured way, such as pricing
information, product specifications, or schedules. Tables can be customized with colors,
borders, and other visual elements to make them more engaging.
• and many more…
index.html
<!DOCTYPE html>
<html>
<head>
<title>John Smith Photography</title>
<meta name="description" content="John Smith Photography
specializes in capturing authentic and compelling images that tell the
story of your business, project, or cause.">
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<h1>Bringing Your Brand to Life with Striking Visuals</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<img src="/resources/media/html-ess-1-7-1-apple-photo.jpg"
alt="Apple photo">
</body>
</html>
TIP
You may have noticed that in the body section, we've used a text that starts with "Lorem ipsum."
Have you ever wondered what it is? Well, Lorem ipsum is a type of dummy text that's used as
a placeholder in print and digital media design and layout. It's essentially a scrambled and
meaningless version of Latin text that's designed to imitate the look and feel of real text, without
actually conveying any coherent information.
The use of Lorem ipsum allows designers, developers, and publishers to create layout designs
that are focused on the visual appearance of the text, without being distracted by the actual
content of the text. It is often used as a placeholder for text content in web pages, desktop
publishing, and graphic design projects.
All right! Now that we have covered the html, head, and body tags and discussed the basic
structure of an HTML document, it's time to move on to understanding the relationship between
HTML, CSS, and JavaScript. These three technologies work together to create dynamic and
engaging web pages.
• HTML provides the basic structure and content of the web page.
• CSS defines the presentation of HTML content, including its layout, colors, and fonts.
• JavaScript adds interactivity to the web page, making it more engaging and dynamic for
the user.
To make things even simpler, if we were to describe each technology using just three words, it
could look like this:
The DOM is a programming interface that enables developers to dynamically manipulate the
structure and content of web pages using JavaScript. A more comprehensive understanding of
the DOM can help you create more engaging and dynamic web pages that keep your users
interested. So let's continue our journey and explore the world of DOM!
The DOM represents the HTML document as a tree-like structure, which consists of
various types of nodes, including document nodes, element nodes, attribute nodes, text
nodes, and comment nodes. The document node represents the entire HTML
document, while element nodes correspond to HTML elements, attribute nodes
represent HTML attributes, text nodes contain the actual text within HTML elements,
and comment nodes represent comments in the HTML code.
Here's an example of a simple HTML DOM tree for a web page with a heading and a
paragraph:
index.html
<!DOCTYPE html>
<html>
<head>
<title>This is the title of my page</title>
</head>
<body>
<h1>This is a heading</h1>
<p>Lorem ipsum dolor sit amet…</p>
</body>
</html>
And here's an example of a DOM tree for the same HTML document:
- document
- html
- head
- title (This is the title of my page)
- body
- h1 (This is a heading)
- p (Lorem ipsum dolor sit amet…)
The DOM tree of our example represents the structure of an HTML document with three
levels:
The document is the root of the tree, with one child: the html element. The html element
has two children: head and body, which are the third level in this DOM tree.
The head element contains one child: the title element, which represents the title of the
page. The body element has two children: h1 and p, representing a heading and a
paragraph, respectively.
The Document Object Model (DOM) is an important tool for web developers as it
enables them to access and modify the content and structure of HTML documents
using JavaScript. Although we didn't cover how to make direct changes to HTML code
in this section, we aimed to provide an introduction to the DOM to help you understand
the structure of the DOM tree, as well as the relationships between its nodes. By
gaining a better understanding of how the different components of HTML syntax relate
to each other, we hope you're now better equipped to create effective and user-friendly
web pages.
In the Module 1 Project, you'll get to practice what you've learned so far. This project is a simple
one to start with, so don't worry if it feels a bit basic – we'll add more exciting challenges as you
progress.
Your task will be to create a basic webpage using the elements you've learned, like headings
(<h1>, <h2>), paragraphs (<p>), and images (<img>). Keep it minimalistic and
straightforward. This project will help you understand how to structure a webpage and add
content to it using HTML.
Feel free to take your time and experiment with what you've learned. Don't worry if you run into
any difficulties – that's all part of the learning process. Ready to give it a try?
Bloom & Petal Haven is a neighborhood flower shop known for its beautiful flower
arrangements and indoor plants. They want to start selling their products online. The
shop offers a variety of flowers, plants, and plant accessories for people who want to
decorate their homes or surprise their friends and family with special gifts.
As part of the interview process for the Front End Developer position at Bloom & Petal
Haven, you've been asked to show your skills by creating a simple and minimalistic
webpage using HTML.
Your job is to make a basic webpage that features two of their popular indoor plants:
the Peace Lily and the Zanzibar Gem. The webpage should give some details about
each plant, like a short description and price. Also, it should have nice pictures to catch
people's attention.
Instructions
2. Head Section
• Create the <head> section of your HTML document. Inside the <head> section,
set the title of your page to "Indoor Plants" using the <title> tag.
• Add meta descriptions for your page using <meta> tags. Include the following:
o Name: Set the name attribute to "description".
o Content: Set the content attribute to the following description of the
webpage: "Explore a variety of indoor plants for your home or office."
3. Charset Encoding
• Set the character encoding for your webpage to UTF-8 using the <meta> tag.
This ensures proper display of special characters.
4. Body Section
• Create the <body> section of your HTML document. Within the <body> section,
start by adding an <h1> tag with a title for your webpage, such as "Indoor
Plants".
• Next, add two <h2> tags – one for each plant name: "Peace Lily" and "Zanzibar
Gem".
• Following each <h2> tag, add a <p> tag containing a short description of the
plant:
o For the Peace Lily: "The Peace Lily, known for its elegant white flowers, is
a popular choice for indoor spaces."
o For the Zanzibar Gem: "The Zanzibar Gem, with its glossy green foliage,
is a low-maintenance indoor plant perfect for beginners."
• Insert another <p> tag after the description to display the price of each plant:
o For the Peace Lily: "Price: $15"
o For the Zanzibar Gem: "Price: $20"
• Following the price, incorporate an image of the plant using the <img> tag, with
the location of the image file specified in the src attribute, and the name of the
plant provided in the alt attribute:
o For the Peace Lily – source:
"https://edube.org/uploads/media/default/0001/04/spathiph
yllum-peace-lily.jpg", alternative text: "Peace Lily".
o For the Zanzibar Gem – source:
"https://edube.org/uploads/media/default/0001/04/zamiocul
cas-zanzibar-gem.jpg", alternative text: "Zanzibar Gem".
• Review your webpage to ensure all elements are properly structured and
displayed.
• Experiment and Customize – Feel free to experiment by adding additional
information or elements to enhance the webpage if you wish.
• index.html
• style.css
• app.js
• play_arrow
• download
• light_modedark_mode
• sync
1
<!-- Your HTML Code Goes Here -->
• Browser
• Console
Sample Solution
If you're finding the tasks challenging or need some assistance, you can check out the
sample solution provided below.
However, we encourage you to try tackling the project independently first. Doing so will
help you strengthen your HTML skills and deepen your understanding. Remember,
facing obstacles is a natural part of learning. Stay persistent, keep practicing, and you'll
see improvement over time. Best of luck!
<!DOCTYPE html>
<html>
<head>
<title>Indoor Plants</title>
<meta name="description" content="Explore a variety of
indoor plants for your home or office.">
<meta charset="UTF-8">
</head>
<body>
<!-- Title -->
<h1>Indoor Plants</h1>
Question 1
What does the DOCTYPE declaration do in an HTML document?
Inline elements are primarily used for content that is part of a paragraph, such as links, while
block-level elements structure the main parts of a page, like sections and articles.
Inline elements are removed from the normal flow of the document, whereas block-level
elements remain within the flow.
Block-level elements are used for styling while inline elements are used for structuring content.
done
Block-level elements start on a new line and take up the full width available, whereas inline
elements do not start on a new line and only take up as much width as necessary.
signal_cellular_4_bar
Question 3
What is the main purpose of the <head> section in an HTML document?
done
<js>
done
<script>
signal_cellular_4_bar
<code>
<javascript>
Question 7
How is the Document Object Model (DOM) utilized in web development?
It allows developers to dynamically manipulate the content and structure of web pages.
signal_cellular_4_bar
Question 8
Which HTML element is used to link a webpage to an external CSS file named "styles.css"?
<style src="styles.css">
<css src="styles.css">
done
<html lang="en">
Defines the language of the document's content for search engines and screen readers.
signal_cellular_4_bar
Specifies the default language of the web page and changes the text direction of the document to
support languages written from left to right.
Question 10
What is the function of the <meta charset="UTF-8"> tag in an HTML document?
It specifies that the HTML document can only be opened using browsers that support UTF-8
encoding.
done
It defines the character encoding for the HTML document, ensuring that all characters are
displayed correctly across different browsers and platforms.
signal_cellular_4_bar
It encrypts the HTML document using UTF-8 encryption for security purposes.
It sets the entire document's font to the UTF-8 style, overriding any CSS styling.
Question 11
What is the role of the <html> tag in an HTML document?
done
It indicates the beginning and end of an HTML document, encompassing all content within the
document.
signal_cellular_4_bar
It declares the document type and version of HTML being used.
It defines the metadata of the document, including the character encoding and viewport settings.
It is used to link external CSS files to style the HTML document.
Question 12
What distinguishes global attributes from element-specific attributes in HTML?
Global attributes define the document's structure, such as <header>, <footer>, and <article>,
while element-specific attributes modify the document's metadata like charset and viewport.
Global attributes are used exclusively within the <head> section of an HTML document to
specify metadata, while element-specific attributes are used within the <body> section to define
content properties.
done
Global attributes can be applied to any HTML element for various purposes, such as styling and
unique identification, while element-specific attributes are tailored to modify the behavior of
specific elements.
signal_cellular_4_bar
Global attributes specify external resources required by the HTML document, such as CSS files
and JavaScript scripts, whereas element-specific attributes are used to define inline styling and
scripts.
Question 13
Do all HTML elements require a closing tag?
Closing tags are optional for all HTML elements as modern web browsers can automatically
infer the end of elements.
Only HTML elements that contain other elements or content require a closing tag, while
standalone elements do not.
Yes, every HTML element must have a corresponding closing tag to ensure proper rendering by
the web browser.
done
No, not all HTML elements require a closing tag. Some elements, known as self-closing or void
elements, do not need a closing tag, such as <img>, <br>, and <input>.
signal_cellular_4_bar
Question 14
What best describes the difference between an HTML tag and an HTML element?
close
An HTML tag is used to add content to a webpage, whereas an HTML element is used
exclusively for styling purposes.
signal_cellular_4_bar
HTML tags are only used in the head section of a document, while HTML elements make up
the body section.
An HTML element refers to the complete structure, including the opening tag, content, and
closing tag, while a tag specifically denotes the opening and closing markers.
HTML elements are a new feature in HTML5, replacing the older system of HTML tags for
better compatibility and efficiency.
Question 15
Consider the binary number 10110 and the hexadecimal number B. Which statement accurately
describes their decimal equivalents?
The binary number 10110 represents the decimal number 5, while the hexadecimal number B
stands for the decimal number 12.
done
The binary number 10110 equals 22 in decimal, and the hexadecimal number B equals 11 in
decimal.
signal_cellular_4_bar
Both the binary number 10110 and the hexadecimal number B represent the decimal number 11.
The binary number 10110 equals 11 in decimal, and the hexadecimal number B equals 22 in
decimal.
Skills you'll gain: Mastery of text formatting, structuring content with lists and tables,
and creating organized and accessible web layouts.
At the end of this module, you'll complete a project that consolidates your knowledge
and a test to evaluate your progress.
2.1 Headings
There are six levels of HTML headings, ranging from <h1> to <h6>, with <h1> being the
most important heading and <h6> being the least important. The heading level is
determined by the number in the heading tag. For example, <h1> indicates the most
important heading, while <h2> indicates a subheading under <h1>, and so on.
It's important to use headings appropriately and not misuse them for stylistic purposes. The
content of the headings should accurately reflect the content they precede, and they should not be
skipped or misused to create a visual effect.
For example, don't use <h3> as a subheading for an <h1> without including an <h2> in
between. This can be confusing for users and search engines.
Overall, using HTML headings correctly is an important element of web development and can
help make websites more accessible and user-friendly.
1
Indexing a website refers to the process of search engines analyzing and storing its web pages to make them searchable and
display them in search results.
2
The practice of optimizing your website and its content to improve its visibility and ranking on search engine results pages.
Typically, the default font size for the different heading levels in most web browsers is as
follows:
• <h1>: 32px
• <h2>: 24px
• <h3>: 18px
• <h4>: 16px
• <h5>: 14px
• <h6>: 12px
While the size of the heading can be adjusted using CSS, it's generally best to use the default
sizes provided by HTML5, as this ensures that the headings are consistent across different
browsers and devices.
The content that can be included between headings can include any text or other HTML elements
that are relevant to the content on the page. For example, an <h1> heading might be used for
the title of the page, while <h2> headings might be used for major sections of the page, with
relevant text or other HTML elements included between each of the headings to provide more
specific information.
• <h1>: The largest and most important heading on the page. This is typically used for the
title of the page or the main heading.
• <h2>: A subheading of <h1>. This is often used for the main section headings on a page.
• <h3>: A subheading of <h2>. This is often used for subsection headings or less important
main headings.
• <h4>: A subheading of <h3>. This is often used for subsection headings or less important
main headings.
• <h5>: A subheading of <h4>. This is often used for subsection headings or less important
main headings.
• <h6>: The smallest and least important heading on the page. This is often used for minor
headings or subheadings.
It's important to remember that the size of the heading doesn't always correspond to its level of
importance. Instead, the level of the heading tag should be used to convey the hierarchy of the
content on the page.
To create a paragraph, you can use the opening <p> tag before the text and the closing </p> tag
after the text that you want to display as a paragraph.
For example, to create a paragraph that reads "Hello, world!", you would write:
1
A box on a web page that holds and organizes other elements like text or pictures. It helps structure the layout, making it easier
to style and manage content. For example, you can use a container to group a heading, paragraph, and image together in one
section. We'll talk more about these boxes in the CSS Essentials course.
The <strong> tag is used to make the enclosed text bold. For example, to make the word
"important" bold in a paragraph, you would write:
index.html
<p>This is some <strong>important</strong> text.</p>
The <em> Tag
The <em> tag is used to make the enclosed text italic. For example, to make the word
"emphasis" italic in a paragraph, you would write:
index.html
<p>This is some text that requires <em>emphasis</em>.</p>
The <u> Tag
The <u> tag is used to underline the enclosed text. For example, to underline the word
"underlined" in a paragraph, you would write:
index.html
<p>This is some text that needs to be <u>underlined</u>.</p>
The <sup> Tag
The <sup> tag is used to make the enclosed text superscript (slightly above the regular text).
For example, to write ordinal numbers, such as first, second, and third in the following form: "1st,
2nd, and 3rd", you would write:
index.html
<p>1<sup>st</sup>, 2<sup>nd</sup>, and 3<sup>rd</sup></p>
The <sub> tag is used to make the enclosed text subscript (slightly below the regular text). For
example, to write a chemical formula for water, you would write:
index.html
<p>The chemical formula for water is H<sub>2</sub>O.</p>
The <del> Tag
The <del> tag is used to strike through text, indicating that it has been deleted or is no longer
relevant. For example:
index.html
<p>Special Price: <del>$100</del> $75.</p>
The <mark> tag is used to highlight text with a background color, indicating that it is of special
importance. For example, to highlight the date “Monday, March 12th", and draw attention to the
deadline, you would wrap it within the <mark> tag:
index.html
<p>The deadline for submitting the report is <mark>Monday, March
12th</mark>.</p>
The <q> tag is used for short, inline quotes (typically just a few words or a short phrase). It is
often rendered with quotation marks around the text. For example:
index.html
<p><q>The only way to do great work is to love what you do.</q>
- Steve Jobs</p>
The <blockquote> tag is used for longer, block quotes. It is often used to quote entire
paragraphs or sections of text, and is typically rendered with indentation or a different font to set
it apart from the surrounding text. For example:
index.html
<p>As Albert Einstein once said:</p>
<blockquote>
<p>"Imagination is more important than knowledge. Knowledge is
limited. Imagination encircles the world. The true sign of
intelligence is not knowledge but imagination."</p>
</blockquote>
<p>This quote speaks to the idea that creativity and original
thinking are more important than simply accumulating knowledge.
It suggests that being able to see beyond what is already known
and to imagine new possibilities is a key characteristic of
intelligence.</p>
2.3.2 The <cite> Tag
When you want to mark up the title or source of a book, film, song, or any other creative
work, provide attribution or credit for an idea or information, or indicate a reference to
another source, you can use the <cite> element.
For example:
index.html
<p>I recently read <cite>The Great Gatsby</cite> by F. Scott
Fitzgerald.</p>
The content within the <cite> element is typically displayed in italic style.
For example:
index.html
<p>As Steve Jobs once said, <q
cite="https://www.brainyquote.com/quotes/steve_jobs_416096">Inno
vation distinguishes between a leader and a follower.</q></p>
The <cite> attribute typically doesn't have a visible effect in a web browser, but it can be used
by screen readers to provide additional context.
For example:
index.html
<blockquote>
<p>The more that you read, the more things you will know. The
more that you learn, the more places you'll go.</p>
<footer>- Dr. Seuss</footer>
</blockquote>
Remember – incorporating quotations and avoiding plagiarism is essential in everyday,
academic, and professional writing as it recognizes the original sources, enhances credibility, and
showcases your commitment to ethical writing practices.
Line Breaks
In HTML, a line break is a simple element that creates a new line of text within a
block-level element. This is typically represented by the <br> tag and is used to
separate lines of text, such as in poetry or song lyrics.
To add a line break, insert the <br> tag wherever you want to create a new line of text.
It's important to note that the <br> tag is an empty element, meaning it doesn't require
a closing tag.
For example, the following code creates two lines of text with a line break between
them:
index.html
<p>This is the first line.<br>This is the second line.</p>
Horizontal Rules
A horizontal rule is a visual element that creates a horizontal line across the width of
a block-level element. It is typically used to separate sections of content within a
page.
To add a horizontal rule, insert the <hr> tag wherever you want to add a line.
The <hr> element is self-closing and does not require a closing tag.
index.html
<p>This is some text above the line.</p>
<hr>
<p>This is some text below the line.</p>
These tags are useful when displaying code examples or preserving the formatting of text that
has been entered with spaces or line breaks.
Hello, World!
If you want to display a code snippet in a block, you’ll need to use the <pre> tag instead.
index.html
<pre>Hello, World!
What a sight to see,
A vast and endless web,
Connecting you and me.</pre>
Hello, World!
What a sight to see,
A vast and endless web,
Connecting you and me.
The <pre> tag preserves all white space characters and displays the text in a monospaced
font, which makes it particularly useful for displaying code examples. For instance, the
following HTML code:
index.html
<pre><body>
<h1>Hello, World!</h1>
<p>Welcome to my first HTML page.</p>
</body></pre>
<body>
<h1>Hello, World!</h1>
<p>Welcome to my first HTML page.</p>
</body>
The <pre> tag preserves all white space characters and displays the text in a monospaced
font, which makes it particularly useful for displaying code examples. For instance, the
following HTML code:
The text enclosed within the <kbd> tag is typically displayed in a monospace font, sometimes in
a rectangular box, which indicates that it represents keyboard input. For example, the
code <kbd>Ctrl + C</kbd> would be displayed as Ctrl + C (a monospace font, maybe
enclosed within a box).
The <samp> tag is used to indicate sample output in a web page. When text is enclosed within
the <samp> tag, it is typically displayed in a monospace font and emphasized in some way, such
as bold or italicized, to indicate that it represents sample output.
Both the <kbd> and <samp> tags are useful for indicating specific types of content in a web
page and can help make the page more accessible and easier to read for users.
2.6 Lists
2.6.1 What are HTML Lists
Lists are a fundamental part of HTML and are used to present information in an organized and
structured manner. They allow you to group a set of related items or pieces of information
together.
Whether you're creating a to-do list, a shopping list, a recipe, or a list of fun facts, HTML lists
have got you covered!
• unordered lists,
• ordered lists, and
• definition lists.
For example:
index.html
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
2.6.3 Ordered Lists
Ordered lists are created with the <ol> tag, and are used to display a list of items in a specific
order. Just like in the case of unordered lists, each item in an ordered list is represented by
the <li> tag.
For example:
index.html
<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
For example:
index.html
<dl>
<dt>Term 1</dt>
<dd>Definition 1</dd>
<dt>Term 2</dt>
<dd>Definition 2</dd>
<dt>Term 3</dt>
<dd>Definition 3</dd>
</dl>
To create a nested list, simply place a new <ul> or <ol> element within an
existing <li> element. For example:
index.html
<ul>
<li>First item</li>
<li>Second item
<ul>
<li>Sub-item 1</li>
<li>Sub-item 2</li>
</ul>
</li>
<li>Third item</li>
</ul>
In the example, the second list item has a nested <ul> element with two <li> items. These sub-
items are indented to show they belong to the second item in the main list.
Nested lists can also be mixed, meaning you can have an ordered list within an unordered list
or vice versa:
index.html
<ul>
<li>First item</li>
<li>Second item
<ol>
<li>Sub-item 1</li>
<li>Sub-item 2</li>
</ol>
</li>
<li>Third item</li>
</ul>
In the example, the second list item has a nested <ol> element with two <li> items. These sub-
items are also indented to show they belong to the second item in the main list.
To sum up, nested lists can be a powerful tool for organizing information in a hierarchical
manner, making it easier for users to understand the relationships between different pieces of
information.
For example, in a recipe website, a nested list could be used to show the ingredients for each
step of a recipe, with the main steps as parent items and the ingredients as sub-items.
Another example of using nested lists could be for a table of contents on a webpage or in a
document. The main sections could be listed as parent items, with the sub-sections listed as sub-
items under each main section. This allows for a clear and organized structure for the reader to
navigate through the content.
2.7 Tables
Tables are made up of rows and columns, and each intersection of a row and a column is
called a cell. Each cell in a table can contain text, images, or other HTML elements.
2.7.2 Creating a Basic Table
To create a basic table, you need to use three elements: <table>, <tr>, and <td>.
The <table> element defines the entire table, and the <tr> element defines a row within the
table. The <td> element defines a cell within a row.
Here's an example of a basic table with two rows and two columns:
index.html
<table>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
index.html
<table>
<tr>
<th>Service</th>
<th>Price</th>
</tr>
<tr>
<td>Web design</td>
<td>$500</td>
</tr>
<tr>
<td>Graphic design</td>
<td>$300</td>
</tr>
<tr>
<td>Content writing</td>
<td>$200</td>
</tr>
<tr>
<td>Social media management</td>
<td>$150</td>
</tr>
</table>
2.7.4 Merging Cells
In HTML tables, it is possible to merge two or more cells in a row or a column to create a
larger cell that spans multiple rows or columns. This can be useful for creating headings,
subheadings, or data cells that have to span across several columns or rows.
You can merge cells in a table using the colspan and rowspan attributes.
The colspan attribute specifies how many columns a cell should span (merges cells
horizontally), while the rowspan attribute specifies how many rows a cell should
span (merges cells vertically).
Here's an example of a table with merged cells:
index.html
<table>
<tr>
<th rowspan="2">Product</th>
<th colspan="2">Price</th>
</tr>
<tr>
<th>Old</th>
<th>New</th>
</tr>
<tr>
<td>Product 1</td>
<td>$10.00</td>
<td>$12.00</td>
</tr>
<tr>
<td>Product 2</td>
<td>$15.00</td>
<td>$18.00</td>
</tr>
</table>
Here’s what happens in our HTML code. The first cell in the first row has a rowspan of 2,
which means it spans across two rows. This results in the first cell of the second row being
merged with the first cell of the first row.
The second row has two cells with a colspan of 2, which means each of these cells spans
across two columns. This results in these cells spanning across the "Old" and "New" columns in
the table.
index.html
<table>
<caption>Product Prices</caption>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>Product 1</td>
<td>$10.00</td>
</tr>
<tr>
<td>Product 2</td>
<td>$15.00</td>
</tr>
</table>
By using the <caption> element, you can provide a brief summary or description of the
table's contents to your users, making it easier for them to understand and interpret the data
presented in the table.
In this course, we'll check out both ways to help you make tables that work well and look good.
But for now, we're going to focus on playing with the attributes of the <table> tag. We'll save
CSS for the CSS Essentials course, which is part 2 of the series.
The <table> tag in HTML has some attributes you can use to change how tables appear. You
can add these attributes to the opening <table> tag, and they let you control things like the size
and layout of the table, as well as the color and border style of the cells.
index.html
<table border="1" cellspacing="10" cellpadding="5" width="80%"
height="200" align="center" bgcolor="#f2f2f2">
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>Product 1</td>
<td>$10.00</td>
</tr>
<tr>
<td>Product 2</td>
<td>$15.00</td>
</tr>
</table>
Feel free to experiment with the different attributes and their values to create tables that suit your
specific needs and preferences. Don't be afraid to play around with different settings to see how
they affect the appearance and functionality of your table.
Customizing tables with attributes allows you to tailor them to your website's design and layout.
However, keep in mind that this may result in complex HTML code, which can make
maintenance difficult for larger and more complex tables. In these scenarios, using CSS to style
your tables may be a better option. Don’t worry, we'll soon explore CSS styling in the next part
of the course.
Here is an example:
index.html
<table>
<caption>Monthly Sales</caption>
<thead>
<tr>
<th>Month</th>
<th>Sales</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$10,000</td>
</tr>
<tr>
<td>February</td>
<td>$12,000</td>
</tr>
<tr>
<td>March</td>
<td>$15,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$37,000</td>
</tr>
</tfoot>
<summary>This table shows the monthly sales figures for the
first quarter of the year.</summary>
</table>
It's important to note that some older attributes like border, cellpadding,
and cellspacing are now deprecated in HTML5, so it's recommended to use CSS instead.
Using the summary attribute can help make your tables more accessible and easier to understand
for all users.
Your journey through learning continues with great success. In this module, you've expanded
your HTML knowledge to include formatting text, organizing data with lists and tables, and
understanding the common properties and values used in web development. Ready for the next
step?
Your mission is to design a captivating webpage that not only tantalizes taste buds but
also inspires wanderlust through immersive storytelling and visually stunning
presentations of recipes from around the world.
Instructions
2. Head Section
• Create the <head> section of your HTML document. Inside the <head> section,
set the title of your page to "Taste of Travel" using the <title> tag.
• Add meta descriptions for your page using <meta> tags. Include the following:
o Name: Set the name attribute to "description".
o Content: Set the content attribute to the following description of the
webpage: "Embark on a culinary adventure with Taste of Travel, exploring
global flavors and recipes."
• Set the character encoding for your webpage to UTF-8 using the <meta> tag.
This ensures proper display of special characters.
• Review your webpage to ensure all elements are properly structured and
displayed.
• Experiment and Customize – Feel free to experiment by adding additional
information or elements to enhance the webpage if you wish.
Sample Solution
If you're finding the tasks challenging or need some assistance, you can check out the
sample solution provided below.
However, we encourage you to try tackling the project independently first. Doing so will
help you strengthen your HTML skills and deepen your understanding. Remember,
facing obstacles is a natural part of learning. Stay persistent, keep practicing, and you'll
see improvement over time. Best of luck!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="Embark on a culinary
adventure with Taste of Travel, exploring global flavors and
recipes.">
<title>Taste of Travel</title>
</head>
<body>
<h1>Embark on a Culinary Adventure</h1>
<blockquote>
<p><q>The key to a delicious Tom Yum Goong lies in the
balance of flavors – sweet, sour, salty, and spicy.</q></p>
<footer>- Chef Somchai, Thai Cuisine Expert</footer>
</blockquote>
<h3>Ingredients:</h3>
<ul>
<li><strong>Lemongrass:</strong> 2 stalks</li>
<li><strong>Thai Basil:</strong> 1 cup</li>
<li><strong>Kaffir Lime Leaves:</strong> 3 leaves</li>
<li><strong>Shrimp:</strong> 500g</li>
</ul>
<h3>Preparation:</h3>
<ol>
<li><em>Simmer the broth for 10 minutes.</em></li>
<li><em>Add lemongrass, galangal, and kaffir lime
leaves.</em></li>
<li><em>Stir in shrimp and cook until pink.</em></li>
<li><em>Season with fish sauce, lime juice, and chili
paste.</em></li>
<li><em>Garnish with Thai basil and serve hot.</em></li>
</ol>
<h3>Cooking Tips:</h3>
<ul>
<li><sup>1/4</sup> cup of fish sauce adds authentic Thai
flavor.</li>
<li><sub>1</sub> tablespoon of chili paste gives the
soup its signature heat.</li>
</ul>
<img
src="https://edube.org/uploads/media/default/0001/04/thai-
soup.jpg" alt="Tom Yum Goong">
<br><br>
<table>
<caption>Recipe Details</caption>
<tr>
<th>Ingredient</th>
<th>Quantity</th>
</tr>
<tr>
<td>Lemongrass</td>
<td>2 stalks</td>
</tr>
<tr>
<td>Thai Basil</td>
<td>1 cup</td>
</tr>
<tr>
<td>Kaffir Lime Leaves</td>
<td>3 leaves</td>
</tr>
<tr>
<td>Shrimp</td>
<td>500g</td>
</tr>
<tr>
<td colspan="2"><strong>Preparation Time:</strong>
20 minutes</td>
</tr>
<tr>
<td colspan="2"><strong>Serving
Suggestions:</strong> Serve with steamed rice or jasmine
tea.</td>
</tr>
</table>
</body>
</html>
<h3> is the largest and should be used for the main title, while <h2> and <h1> are for
subsections and minor points, respectively.
HTML headings do not influence the hierarchy of content; CSS is solely responsible for defining
such relationships.
done
<h1> has the largest default font size, suitable for the main title of a page. <h2> is used for major
section headings with a smaller font size than <h1>, and <h3> is for sub-sections, with a font
size smaller than <h2>, reflecting a hierarchical document structure.
signal_cellular_4_bar
The font sizes for <h1>, <h2>, and <h3> are the same, with differences only in semantic
importance.
Question 2
Which of the following accurately describes the function of the <p> tag in HTML?
done
The <p> tag defines a paragraph, automatically adding a blank line above and below the
enclosed text and taking up the full width of its container.
signal_cellular_4_bar
The <p> tag is used to create a new line within a paragraph without adding any space above or
below.
The <p> tag defines a paragraph, without adding any space above or below.
The <p> tag is an inline element that formats text without affecting its block-level structure.
Question 3
What is the purpose of the <mark> tag in HTML?
index.html
<p>The meeting is scheduled for <mark>Wednesday</mark> at 10
AM.</p>
The <mark> tag underlines and highlights the word "Wednesday", drawing attention to it with a
font color.
The <mark> tag underlines the word "Wednesday" to indicate hyperlinks without creating an
actual link.
The <mark> tag makes the word "Wednesday" italic to emphasize a specific part of the
paragraph.
done
The <mark> tag highlights the word "Wednesday", drawing attention to it with a background
color.
signal_cellular_4_bar
Question 4
How does the <blockquote> tag differ from the <q> tag in HTML?
done
The cite attribute should be used within the <blockquote> tag to specify the URL of the
quotation's source.
signal_cellular_4_bar
Citation sources are typically not included in the HTML but rather in the accompanying CSS.
The <cite> tag should be used as a container for the entire quotation and its source URL.
The source URL should be included inside the <q> tag for all quotations.
Question 6
Which statement is true about using quotation marks with the <q> and <blockquote> tags?
Quotation marks must be manually added when using both <q> and <blockquote> tags for
proper formatting.
done
The <q> tag automatically adds quotation marks around the enclosed text, while the
<blockquote> tag does not.
signal_cellular_4_bar
Both <q> and <blockquote> tags automatically add double quotation marks around the text.
The <blockquote> tag requires manual addition of quotation marks, but the <q> tag does not.
Question 7
Which of the following statements accurately describes the use of the <br> and <hr> tags in
HTML?
<hr> is used to create a line break in text, and <br> is for drawing a horizontal line.
Both <br> and <hr> tags are used for creating new paragraphs.
done
The <br> tag is used for adding a new line within a paragraph, while the <hr> tag is used to
insert a visual horizontal line to separate content.
signal_cellular_4_bar
Both tags require closing tags to function correctly in HTML documents.
Question 8
What is the primary purpose of the <code> tag in HTML?
The <code> tag provides semantic meaning to text, indicating technical terms or identifiers
outside of code contexts.
The <code> tag is used to indicate text that should be interpreted as programming variables.
done
The <code> tag is used to display a snippet of computer code inline with other text, highlighting
it in a monospaced font to distinguish it from the surrounding text.
signal_cellular_4_bar
The <code> tag serves as a container for embedding executable code within HTML.
Question 9
How does the <pre> tag affect the display of text in an HTML document?
The <pre> tag organizes text into pre-defined sections for improved document structure.
The <pre> tag prioritizes text for search engines, enhancing SEO for preformatted content.
The <pre> tag is used to pre-process text, applying automatic formatting rules.
done
The <pre> tag preserves the text's white space and line breaks, displaying it exactly as written
within the tag, which is useful for showing code or poetry.
signal_cellular_4_bar
Question 10
Considering accessibility and HTML semantics, what is the significance of nesting <ol> within
<ul> or vice versa?
Nesting provides semantic clarity, enabling search engines to better understand and index the
content structure, potentially improving SEO performance.
By utilizing nested lists, developers can implement complex web designs more efficiently, as it
simplifies the CSS needed for list customization.
done
Nesting lists, such as incorporating <ol> within <ul> or vice versa, organizes information
hierarchically. This enhances document structure and accessibility by delineating subcategories
or sequential steps within broader categories.
signal_cellular_4_bar
Nesting lists facilitates the automatic adaptation of content to various screen sizes, improving the
responsive design of web pages without additional CSS.
Question 11
Which HTML tag pair is specifically used for creating a list of terms and their respective
definitions?
close
<ul> for the list, with <dt> and <dd> tags for terms and definitions.
signal_cellular_4_bar
<dl> for the list, followed by <li> for each term and definition.
<dl> for the list, <dt> for each term, and <dd> for each definition.
<ul> for the list, with <dt> tags marking each term and definition pair.
Question 12
Which attribute would you use to merge two cells horizontally within a table row?
cellspan
colspan
rowspan
close
merge
signal_cellular_4_bar
Question 13
What is the correct way to add a caption to an HTML table?
The <header> element should be used at the beginning of a table to add a caption.
Use the <title> element within a table for captions.
Captions are added using the alt attribute on the <table> tag.
done
The <caption> element, placed immediately after the opening <table> tag, is used to provide a
title or caption for the table.
signal_cellular_4_bar
Question 14
Considering HTML5 standards, which table attributes are recommended to control the
appearance and layout of a table?
The border and bgcolor attributes are preferred for styling tables.
Use the border and cellspacing attributes for appearance and layout control.
CSS styles are recommended for controlling the appearance and layout of tables in HTML5.
close
The border, the cellpadding, and the cellspacing attributes are the HTML5 recommended
method.
signal_cellular_4_bar
Question 15
What role does the summary attribute play in HTML tables, and why is it important?
done
It is used to describe the table's content and purpose for assistive technologies, enhances
accessibility by providing context.
signal_cellular_4_bar
It summarizes the table data in a tooltip.
It is a visual summary displayed at the top of the table.
It is primarily designed for enhancing table accessibility, not directly influencing SEO or
providing visible content to all users.
3.1 Images
The <img> tag is an empty element, which means that it does not have a closing tag. Instead,
all the attributes are included in the opening tag.
The most important attributes of the <img> tag are <src>, <alt>, <width>, and <height>.
The src attribute specifies the source URL of the image that should be displayed.
For
example: src="https://edube.org/uploads/media/default/0001/03/mountain
_landscape.jpg".
The alt attribute provides alternative text that will be displayed if the image cannot be loaded.
It is also used by screen readers for visually impaired users.
The width attribute specifies the width of the image. It can be defined in pixels
(e.g., width="340") or as a percentage of the containing element's width
(e.g., width="50%").
The height Attribute
Similarly to width, the height specifies the height of the image in pixels or as a percentage of
its parent container.
Here’s an example of the <img> tag with all the four attributes in action:
index.html
<img
src="https://edube.org/uploads/media/default/0001/03/mountain_la
ndscape.jpg" alt="Mountain landscape" width="340" height="250">
When the browser encounters the <img> tag, it loads the image from the specified source URL,
displays the alternative text if necessary, and adjusts the image's width and height according to
the provided attributes. This results in the image being rendered on the web page with the
specified dimensions and description.
• JPEG,
• PNG, and
• GIF.
JPEG is used for photographs, while PNG is best suited for graphics and images with transparent
backgrounds. GIF is commonly used for simple animations and graphics.
Consider the characteristics of your image, its complexity, and the intended use when selecting
an image format. Using the wrong format may result in larger file sizes, longer loading times,
and poorer image quality.
Although JPEG, PNG, and GIF are the most commonly used image formats, keep in mind that
there are other image formats available, such as SVG (Scalable Vector Graphics) and WebP.
SVG is a vector-based format that is ideal for images that need to be scaled without losing
quality, while WebP is a relatively new format that offers better compression and smaller file
sizes than JPEG and PNG. However, not all web browsers support these formats, so it's
important to check compatibility before using them on your website.
To check compatibility for different image formats, you can refer to the documentation of the
web browsers you are targeting. Most popular web browsers such as Chrome, Firefox, Safari,
and Edge have official documentation that lists the supported file formats and their versions.
You can also use online tools such as CanIUse.com, which provides a comprehensive database
of browser compatibility information for different web technologies, including image formats.
3.1.3 Image Location
When adding images to your website, it's important to consider the location of the image file. If
the image is stored on your computer, you will need to upload it to your website's server. If the
image file is not in the same directory as the HTML file, you'll need to provide a relative or
absolute path to the image file.
Once the image is in the right location, you can use the <img> tag and the src attribute to insert
it into your web page.
Relative Path
A relative path is a path that starts from the directory of the HTML file. For example:
index.html
<img src="images/picture.jpg" alt="A picture">
In this example, the relative path points to an image file (picture.jpg) in a subdirectory
called images that is located in the same directory as the HTML file.
Absolute Path
An absolute path is a path that starts from the root directory of the website. For example:
index.html
<img src="https://example.com/images/picture.jpg" alt="A
picture">
In this example, the absolute path points to an image file (picture.jpg) hosted on the web server
at the URL "https://example.com/images/pic.jpg".
In addition to these methods, there are also several third-party image hosting services such as
Imgur, Flickr, Photobucket, Google Photos, Dropbox, or Amazon S3, that allow you to store and
manage your images online. These services can provide additional features such as automatic
image resizing, optimization, and compression.
However, keep in mind that using third-party services may require an additional cost or
subscription, and you may have limited control over the hosting and availability of your images.
To create responsive images in HTML, you can use the srcset and sizes attributes.
The srcset attribute allows you to specify a list of image files with different resolutions,
sizes, and formats. When the browser loads the image, it will select the most appropriate image
from the list based on the screen size and the device's capabilities.
The sizes attribute specifies the size of the image container in which the image will be
displayed. In other words, it tells the browser how much screen space the image will occupy
on different devices.
By using srcset and sizes together, you can create images that are optimized for different
devices and screen sizes.
For example:
index.html
<img src=sunflowers.jpg"
alt="Sunflowers in the sunset"
srcset="sunflowers-small.jpg 480w,
sunflowers-medium.jpg 800w,
sunflowers-large.jpg 1200w"
sizes="(max-width: 480px) 95vw,
(max-width: 800px) 45vw,
30vw">
When the page is loaded, the browser will choose the most appropriate image from
the srcset attribute based on the screen size and device capabilities.
It's important to note that while HTML can provide a basic level of responsiveness for images,
more advanced techniques can be achieved through CSS, which we’ll cover in the second part of
the HTML & CSS Essentials series.
In this section, we will briefly explore these traditional attributes, acknowledging their role in the
evolution of HTML while also emphasizing the shift towards CSS for achieving similar results.
The border attribute specifies the width of the border around the image. For example:
index.html
<img src="example.jpg" alt="Example image" border="2">
The hspace and vspace Attributes
The hspace and vspace attributes specify the horizontal and vertical space around the image,
respectively. For example:
index.html
<img src="example.jpg" alt="Example image" hspace="10"
vspace="10">
The align Attribute
The align attribute allows for specifying the alignment of an image relative to surrounding
content, with values like left, right, and center. For example:
index.html
<img src="example.jpg" alt="Example image" align="left">
While these attributes provide straightforward ways to adjust image presentation, modern HTML
practices use CSS to achieve these effects. This approach enhances the flexibility of styling,
keeps the HTML cleaner, and separates presentation from content. Later in the course, as well as
in the Web Dev Essentials: CSS part, you'll learn how to use CSS effectively to replace these
deprecated attributes and apply best practices for web design.
• Name your image files descriptively and include relevant keywords. This can help with
search engine optimization and make it easier to find images in your image library. Avoid
using generic names like "image1.jpg" or "photo.png".
• Use appropriate image formats for the type of image to ensure the best image quality and
fast loading time.
• Store images in an appropriate location. Ensure that the image file is either in the same
directory as your HTML file (relative path) or provide the full path to the image file in
the src attribute (absolute path).
• Consider the file size of the image as large images can slow down your website's load
time. It's a good idea to optimize images for the web before uploading them to your site
(i.e. compress them to reduce file size without sacrificing image quality).
• Always provide descriptive and meaningful alt text for your images to improve
accessibility and user experience.
• Last but not least, consider the placement of your images to complement your content
and enhance the user experience. Avoid placing images in distracting locations that may
interfere with the readability of your text.
3.2 Hyperlinks
The <a> tag primarily relies on the href attribute, which specifies the destination of the link.
This destination can be an absolute URL (such as https://www.example.com/) or a
relative URL (like about.html if the target page resides in the same directory as the current
page).
To add a visible, clickable link text in HTML, you need to place it between the opening <a> tag
and the closing </a> tag. This text is what is displayed on the web page.
For example, the following code will create a hyperlink with the text "Visit our website" that
points to the URL "https://www.example.com":
index.html
<a href="https://www.example.com/">Visit our website</a>
Hyperlinks are typically underlined and displayed in a different color than the surrounding
text, to indicate to the user that they can be clicked.
By default, web browsers style hyperlinks to indicate their state, enhancing user navigation.
Unvisited links are underlined in blue, signaling new paths. Visited links change to underlined
purple, differentiating them from new ones. Active links, when clicked, turn underlined red,
providing immediate feedback on the interaction. These standard styles help users intuitively
navigate the web.
To create an internal link, you can use either an absolute or a relative URL to specify the URL of
the page or section of the same website that you want to link to. For example:
To create a link like this, you’re going to need the id attribute and the # symbol. Here’s how to
do it:
1. Add the id attribute to an HTML element on the page that you want to link to. For
example, if you want to link to an <h2> element with the content “Section 1”, you can do
the following: <h2 id="section-1">Section 1</h2>.
2. Then, create a link that points to this anchor by adding the # symbol followed by
the id to the href attribute of an <a> tag, like this: <a href="#section-
1">Go to Section 1</a>.
When a user clicks on this link, they will be taken to the section of the page with
the id="section-1". It's important to note that the id value must be unique within the page,
and it's a good practice to use descriptive names that indicate the section's content.
index.html
<a href="https://example.com">Visit Example.com</a>
It's important to note that because external links take users away from your website, you should
ensure that they open in a new window or tab using the target attribute. For example:
index.html
<a href="https://www.example.com" target="_blank">Visit Example
Website</a>
The target="_blank" attribute will open the linked page in a new tab or window,
allowing users to easily return to your website. The target="_self" attribute will open the
link in the same window.
It's important to note that external links can have security implications for your website. You
should be cautious when linking to external sites and make sure they are reputable sources.
Additionally, it's a good practice to inform your users when a link is external by using a small
icon or text label next to the link.
Email links
To create an email link, you can use the mailto protocol followed by the email address that you
want to link to. Here's an example:
index.html
<a href="mailto:[email protected]">Email Us</a>
When a user clicks on this link, their default email client will open with the "To" field pre-filled
with the email address specified in the link.
Telephone links
Similarly, to create a telephone link, you can use the tel protocol followed by the telephone
number that you want to link to. Here's an example:
index.html
<a href="tel:123-456-7890">Call us at 123-456-7890</a>
When a user clicks on this link on a mobile device, it will open their default phone app and
automatically dial the number. On a desktop device, clicking the link will typically do nothing,
as desktop devices typically don't have phone capabilities.
The download attribute specifies that the target of the link should be downloaded rather than
navigated to. The attribute value can be used as the default filename that the downloaded file will
be saved as.
For example:
index.html
<a href="https://example.com/document.pdf" download="my-
document.pdf">Download my document</a>
The rel Attribute
The rel attribute specifies the relationship between the current document and the target
document. It can be used to indicate that the target document is a stylesheet, a parent document,
or a part of a series, among other things.
For example:
index.html
<a href="https://example.com/stylesheet.css"
rel="stylesheet">Link to stylesheet</a>
The title Attribute
The title attribute provides additional information about an element, enhancing the user's
understanding and interaction with web content.
The attribute offers supplementary details about the hyperlink's destination or purpose. This
information typically appears as a tooltip, a small pop-up box, when the user hovers their mouse
over the link, giving users a preview of what to expect before clicking.
For example:
index.html
<p>Go to <a href="https://example.com/about" title="Visit our
About section.">our website</a> for more information.</p>
By using these additional link-specific attributes, you can provide more information and
functionality to your hyperlinks and improve the user experience of your website.
This method works with a wide range of elements, including images, blocks of text, and even
complex HTML structures like divs or sections.
Here's a simple example that illustrates how you can turn an image into a clickable link:
index.html
<a href="https://www.example.com">
<img
src="/uploads/media/default/0001/03/mountain_landscape.jpg"
alt="Mountain landscape" width="340" height="250">
</a>
In this example, the image becomes part of the clickable link. This is particularly useful for
creating visually appealing call-to-action (CTA) buttons or linking card elements that contain a
combination of text, images, and other media.
3.3 Media
For example, the following code embeds a video with built-in media controls and automatic
playback when the page loads:
index.html
<video src="myvideo.mp4" controls autoplay>
Your browser does not support the video tag.
</video>
For example:
index.html
<!-- Video Example -->
<video controls>
<source src="myvideo.mp4" type="video/mp4">
<source src="myvideo.webm" type="video/webm">
<p>Your browser does not support the video tag.</p>
</video>
Remember to test your video and audio elements on different browsers and devices to ensure
compatibility. Some browsers may not support certain codecs or may require additional plugins
for playback.
For example, you can test your video and audio elements on popular web browsers such as
Google Chrome, Firefox, Safari, and Microsoft Edge. You can also test on different devices with
varying screen sizes, resolutions, and operating systems, including desktops, laptops, tablets, and
smartphones. This can help you identify any compatibility issues and ensure that your media
content is accessible and engaging for all users.
Video and audio codecs are algorithms used to compress and decompress media files,
enabling them to be played on different devices and platforms. In other words, they are programs
that encode and decode digital media content for transmission or storage.
There are several video codecs available, including H.264, VP8, and VP9. H.264 is widely used
and is compatible with most devices, while VP8 and VP9 are free, open-source codecs.
Similarly, there are several audio codecs available, including MP3, AAC, and Ogg Vorbis. MP3
is widely used and is compatible with most devices, while AAC is a more efficient codec and is
commonly used for streaming services. Ogg Vorbis is a free, open-source codec.
MP4 files typically use the H.264 codec for video and the AAC codec for audio.
As we talked about before, different web browsers handle video and audio files in different
ways. This can make it tricky for your media to work on all devices. To make sure your media
works well everywhere, it's a good idea to offer it in different formats, like MP4 and WebM for
videos, and MP3 and Ogg for audio.
Having at least some basic understanding of codecs can be helpful when working with video and
audio elements in HTML. It can help ensure that your media content is accessible and
compatible with various devices and browsers.
To create a responsive video using HTML, you can use the <video> element with
the poster and controls attributes, and the <source> element with the media atribute.
The poster attribute specifies an image that will be displayed when the video is not playing,
while the media attribute located within the <source> element specifies a maximum
width for the video to be displayed. This allows the video to adapt to different screen sizes.
index.html
<video poster="web-dev-picture.jpg" controls>
<source src="web-dev-video.mp4" type="video/mp4" media="(max-
width: 600px)">
<source src="web-dev-video.webm" type="video/webm">
</video>
The code creates a video player that shows the poster image while the video is not playing, and
the built-in media controls will be available for use. The first <source> element limits the
video to play only the .mp4 version on devices with a maximum width of 600 pixels. The
second <source> element provides the .webm version of the video for other devices, making it
adaptable to various screen sizes and thus responsive.
We'll cover more advanced techniques for video responsiveness in the CSS Essentials course.
For now, focusing on the HTML basics for responsive video will give you a strong foundation to
build upon.
It's commonly used for various purposes, including collecting user information, conducting
surveys, and enabling users to log in or sign up for accounts.
For example, a login page typically features a form where users enter their credentials
(username and password) to access restricted areas of a website. Similarly, a sign-up
page includes a form where new users can register by providing their information, such as
username, email address, and password.
Forms are also used for newsletter sign-up, where visitors can subscribe by entering their email
addresses. Payment forms enable users to input their payment details, such as credit card
information, to complete online transactions securely.
In addition, forms can be utilized for interactive tools like calculators, such as a BMI
calculator, where users input their weight and height to calculate their body mass index directly
on the webpage without server interaction.
Contact forms allow visitors to send messages or inquiries to website owners. Surveys often
consist of forms with multiple-choice questions or text fields, enabling users to provide feedback
or answer specific questions.
Forms can be also designed to generate PDF documents with user-entered data. These forms
allow users to input information, such as personal details or responses to questions, which can
then be saved as PDF files for offline use or record-keeping.
As you can see, HTML forms are versatile tools used for collecting user information, facilitating
user interactions, conducting surveys, and providing various interactive functionalities on web
pages. We've showed you just a few examples, but the possibilities for using forms are limitless,
and they can be customized to suit a wide range of purposes and requirements.
In this section, we'll cover the basics of HTML forms, including form elements, common input
types, and most popular attributes.
• the action attribute, which specifies the URL of the server-side script or endpoint
that will process the form data. The action attribute is added to the <form> element.
When the form is submitted, the browser will send the form data to the specified URL.
• the method attribute, which specifies the HTTP method (GET or POST) used when
sending form data to the server. The method attribute is added to the <form> element
and its value is set to either "GET" or "POST".
For example:
index.html
<form action="submit-form.php" method="POST">
<!-- Form elements/fields go here -->
</form>
Let’s see what happens here.
The code creates an HTML form element that uses the POST method to submit data to the
"submit-form.php" file on the server, which is likely a server-side script that will receive and
handle the form data submitted by the user.
After the user submits the form, the data entered into the form fields is sent to the server-side
script for processing. The script can then perform actions such as saving the data to a database,
sending an email, or displaying a confirmation message to the user.
The HTTP method, also known as the HTTP request method, is a verb that indicates the
desired action to be performed on a resource identified by a URL. It's like a type of action
word that says what to do with the information.
HTTP defines several methods, each with a specific purpose. The two most common methods for
submitting form data are GET and POST.
The GET method sends the form data in the URL query string. This means that the form data
is visible in the browser's address bar and can be bookmarked or shared with others.
It's commonly used for simple forms that don't require a lot of security (the data is visible in the
URL, so it’s not the best method for sending sensitive data).
For example, if a user submits a form with the name "John" and the email "[email protected]",
the URL will look like
this: https://example.com/form.php?name=John&email=john%40example.com.
The POST method sends the form data in the body of the HTTP request. This means that the
form data is not visible in the URL or the browser's address bar.
It's commonly used for more complex forms that require higher security, such as login forms or
forms that contain sensitive information. However, the form data cannot be bookmarked, shared,
or cached by the browser as in the case of the GET method.
Note
In this course, we'll focus exclusively on HTML and won't cover the intricacies of form
submission, such as POST and GET methods, or actual sending the form and its data. These
tasks typically require server-side languages like PHP or web development frameworks like
Node.js, Ruby on Rails, or Django.
However, don't worry because you’ll have a chance to learn more about form submission and
processing in the third course of the Web Development Essentials series, Web Development
Essentials: JavaScript, which covers the fundamentals of server-side programming and form
submission using AJAX and Node.js, among other topics.
The type attribute defines the functionality and input control displayed to the user, enabling
specific data formats and validations for each field. In other words, it determines the type of
input field and provides built-in validation functionality to ensure the input matches the desired
format criteria.
• text – a single-line text input field, used for short text inputs such as names, email
addresses, etc.
• email – a single-line text input field used specifically for entering and validating email
addresses (the browser applies built-in validation to ensure that the user’s input is in the
proper email format)
• url – a single-line text input field used specifically for entering, validating, and
accepting only properly-formatted URLs;
• number – a single-line input field used specifically to validate and accept only numbers;
• password – a single-line text input field that masks the entered characters to maintain
the confidentiality of the password;
• checkbox – a checkbox that can be toggled on or off, allows users to select one or more
options from a list;
• radio – a radio button that belongs to a group of radio buttons (only one can be selected
at a time)
• submit – a button that submits the form data and sends it to the server as specified by
the action and method attributes;
• reset – a button that clears the form data and resets it to the initial values.
For example, setting type="text" creates a field for textual input,
while type="email" expects an email address, including built-in validation to ensure the input
matches email format criteria.
The name attribute is essential for identifying each piece of data submitted. It acts as a key for
the form data, allowing the server-side script to access and process user inputs based on these
names.
Adding the required attribute to an input field makes it mandatory for users to fill out that
field before submitting the form. It's a simple way to ensure that critical information is not
omitted.
By associating a label with a specific input field using the for attribute (which should match
the input's id attribute), users can click on the label to focus on the corresponding input, a
feature particularly beneficial for those using assistive technologies.
Here's a basic example of a labeled <input> element with required email input field in an
HTML form:
index.html
<label for="email">Email:</label>
<input type="email" id="email" name="useremail" required>
In the sections ahead, we will delve further into elements and attributes unique to HTML forms.
Additionally, we'll provide hands-on examples to illustrate the practical application of HTML
forms in real-world scenarios.
The <textarea> element creates a multi-line text input field, which allows users to enter larger
amounts of text. You can set the rows and cols attributes to control the visible size of the
textarea.
For example:
index.html
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4"
cols="50"></textarea>
The Select Element
The <select> element creates a dropdown list, used with <option> elements to define the
available options. You can use the multiple attribute to allow multiple selections, and
the size attribute to control the number of visible options.
For example:
index.html
<label for="pasta">Pasta:</label>
<select id="pasta" name="pasta">
<option value="spaghetti">Spaghetti</option>
<option value="penne">Penne</option>
<option value="lasagna">Lasagna</option>
<option value="farfalle">Farfalle</option>
</select>
The Button Element
The <button> button element creates a clickable button that can be customized with JavaScript
or used to submit or reset a form, depending on its type attribute (e.g., submit, reset,
or button). If the type attribute is omitted or set to "button", it does not have any default
behavior and can be controlled with JavaScript.
For example:
index.html
<button type="button" onclick="alert('Hello, World!')">Click
me!</button>
The code we've provided is an HTML button element that, when clicked, triggers an alert pop-up
displaying the message "Hello, World!".
The onclick attribute is a JavaScript event handler that specifies the action to be performed
when the button is clicked. In this case, the action is an alert() function call, which displays
the pop-up dialog message we've mentioned above.
The <fieldset> element creates a container used to group together related form elements. It
can be helpful in organizing complex forms with multiple sections. The <legend> element can
be used within a <fieldset> to provide a caption or title for the group.
For example:
index.html
<fieldset>
<legend>Shipping Address</legend>
<label for="address">Address:</label>
<input type="text" id="address" name="address">
<br>
<label for="city">City:</label>
<input type="text" id="city" name="city">
<br>
<label for="zip-code">ZIP Code:</label>
<input type="text" id="zip-code" name="zip-code">
</fieldset>
These additional elements can help you create more structured and organized forms, improving
both the appearance and usability of your forms.
You’ve already been introduced to the name attribute, which specifies the name of the input
field, and works as an identifier for the form element when the data is sent to the server. You’ve
also learned about the required attribute, which indicates that the input field must be filled out
before submitting the form.
As you might suspect, the list is longer, and some other commonly used <form> attributes
include value, placeholder, disabled, and readonly.
The Value Attribute
The value attribute specifies the initial value of the input field. When the form is loaded, this
value will be pre-filled in the input field.
For example:
index.html
<label for="first-name">First Name:</label>
<input type="text" id="first-name" name="first-name"
value="John">
The placeholder attribute specifies a hint that describes the expected value of the input
field. It does not specify the initial value itself, as in the case of the value attribute. The
placeholder text is displayed in the input field when it is empty and disappears when the user
starts typing.
For example:
index.html
<label for="email">Email:</label>
<input type="email" id="email" name="email"
placeholder="[email protected]">
The Disabled Attribute
The disabled attribute disables the input field, making it uneditable and unselectable.
Users cannot interact with disabled fields, and the fields appear grayed out or visually distinct
from other fields.
When a form is submitted, disabled fields do not send their values to the server. This attribute is
useful when you want to show information to users without allowing them to edit or submit the
content.
For example, in multi-step forms or wizards, you might want to disable certain fields until
previous steps are completed. Or, when displaying a form to edit user profile information, you
might want to show default or system-generated values that users should not change, such as
their usernames.
index.html
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="JohnDoe"
disabled>
The readonly attribute makes the input field read-only, allowing users to view the content
but not edit it. Unlike disabled fields, read-only fields are still selectable and send their
values when the form is submitted. This attribute is useful when you want to display information
to users that they should not edit but still include when submitting the form data.
For example:
These attributes help ensure that the user provides the necessary information in the correct
format while also enhancing the user experience by providing helpful hints and feedback.
By combining these elements and attributes, you can create a wide variety of forms to meet the
needs of your website or application.
min and max set the minimum and maximum values that can be entered into number, range,
date, and time input fields. For example, the following line will limit the "age" input to a number
between 18 and 100:
index.html
<input type="number" name="age" min="18" max="100">
The Autocomplete Attribute
autocomplete – controls whether the browser should automatically complete input fields with
previously entered data. This attribute can have values of "on" (default), "off", or "new-
password" (to disable autocomplete for password fields). For example, the following line will
disable autocomplete for the "address" input:
index.html
<input type="text" name="address" autocomplete="off">
The Pattern Attribute
pattern specifies a regular expression that the input value must match in order to be valid.
This attribute is useful for enforcing specific formatting or data validation rules. For example, the
following line will require the "phone" input to be formatted as a 10-digit phone number with
hyphens:
index.html
<input type="text" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-
9]{4}">
By using these form-specific attributes, you can create input fields that are tailored to your
specific needs and help ensure that users provide valid data in the correct format.
With the knowledge you've gained about HTML forms and their attributes, you're now well-
equipped to create various types of forms to cater to the needs of your website or application.
Remember that these attributes play a crucial role in enhancing user experience and ensuring
users provide the necessary information in the correct format. As you continue to explore and
experiment with form elements and attributes, you'll discover even more ways to customize and
optimize your forms.
Let's walk through the sample process of creating a simple HTML form, step by step.
Start with the <form> element. This element wraps all the contents of your form, including
input fields, labels, and buttons. The action attribute specifies where to send the form data
when submitted, and the method attribute defines how to send it (usually POST or GET).
Step 2: Add Input Fields
Input fields are where users enter data. Use the <input> tag to create these fields.
The type attribute specifies the kind of data you expect (e.g., text, number, email).
The name attribute is crucial for identifying the data on the server side.
The <label> element enhances the usability of your form by providing descriptive text for each
input field. Link each label to its corresponding input by matching the for attribute in
the <label> tag with the id attribute of the <input> tag.
First, let's build a simple HTML form for user login with two input fields
(username and password) and two buttons (submit and reset).
index.html
<form action="/submit" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
The required attribute indicates that the user must fill out this field before
submitting the form. (When an input field has the required attribute, the browser will
prevent the form from being submitted if the field is left empty or, in some cases, if it
does not meet the specified validation criteria, such as a valid email address for an email
input field.)
4. <br> creates a new line between the input fields, but you already know this, don’t you?
5. <label for="password">Password:</label> creates a label element
associated with the "password" input field.
6. <input type="password" id="password" name="password"
required> creates a password input field for the user to enter their password. The
entered characters will be masked for security purposes. Again, the required attribute
indicates that the user must fill out this field before submitting the form.
7. <input type="submit" value="Login"> creates a submit button for the form.
When the user clicks this button, the form data will be submitted to the specified URL
using the specified method. The value attribute sets the text displayed on the button, in
this case, "Login."
8. <input type="reset" value="Reset"> creates a reset button for the form.
When the user clicks this button, the form fields will be reset to their initial values or
cleared if they don't have initial values.
9. </form> marks the end of the form element.
When a user fills out the username and password fields and clicks the "Login" button, the form
data will be submitted to the /submit URL using the POST method. If the user clicks the "Reset"
button, the form will be cleared, and the user can enter new data.
Now, let's create a simple contact form that collects basic information like name, email, and a
message.
index.html
<form action="/submit-contact" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<br>
<button type="submit">Send</button>
</form>
1. This form includes text and email inputs for name and email, with a textarea for a
more extended message.
2. The required attribute ensures all fields must be filled out.
3. The form data is sent to a server endpoint defined in the action attribute upon
submission.
Okay. Now, let's build a simple form for calculating Body Mass Index (BMI) using weight and
height inputs.
index.html
<form action="/submit-bmi" method="post">
<label for="weight">Weight (kg):</label>
<input type="number" id="weight" name="weight" required>
<br>
1. The form uses number inputs for weight and height, ensuring users enter numerical
values.
2. The required attribute ensures the form cannot be submitted without these values.
3. When the user submits the form, the data is sent to the server endpoint specified in
the action attribute for BMI calculation (the calculation part is handled server-side).
index.html
<form action="/submit" method="POST">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
When a user fills out the form and clicks the "Register" button, the form data will be submitted
to the "/submit" URL using the POST method.
In our examples, we used line breaks (<br>) to make the spaces between input fields and groups
look nice and clear. But, it's just a simple way to make things look better for now. Normally,
when you make websites, you should use CSS to arrange and style everything, like where things
go and how much space is between them. We're going to learn all about how to do this with CSS
in our second course in the Web Development Essentials series.
You're making impressive progress on your learning journey. This module has taken your
HTML skills further by introducing you to visual and interactive elements. You've learned how
to enrich web pages with images, hyperlinks, and media, as well as how to construct HTML
forms. Eager to apply these new skills?
You've been approached by "Harmony Heights," an emerging band known for their
eclectic mix of genres and compelling live performances. As they prepare to broaden
their audience and establish a stronger online presence, they need a dynamic and
engaging official webpage. This page will serve as a central hub for fans to explore the
band's music, learn about band members, view upcoming show dates, and connect with
the band.
Your task is to craft a webpage that reflects the band's vibrant personality and musical
diversity, incorporating multimedia elements such as images, music samples, videos of
performances, and a contact form for booking inquiries or fan messages.
Instructions
1. Initial Setup
• Introduce the band with an <h1> tag ("Welcome to Harmony Heights"), followed
by a captivating paragraph about their musical journey: "We are Harmony
Heights, a band that blends genres to create unique sounds. Our journey through
music has been incredible, and we're excited to share it with you."
• Include professional photos of the band and individual members using the <img>
tag, emphasizing the importance of the alt attribute for accessibility:
o The first photo – source:
"https://edube.org/uploads/media/default/0001/04/band-
photo.jpg", alt text: "Harmony Heights Band Photo".
o The second photo – source:
"https://edube.org/uploads/media/default/0001/04/member1-
amy.jpg", alt text: "Harmony Heights Vocals/Sampling: Amy Duncan".
o The third photo – source:
"https://edube.org/uploads/media/default/0001/04/member2-
john.jpg", alt text: "Harmony Heights Bass/Guitars: John Smith".
o The fourth photo – source:
"https://edube.org/uploads/media/default/0001/04/member3-
trevor.jpg", alt text "Harmony Heights Drums: Trevor G.".
• Audio
o Add an <h2> element with the following content: "Listen to Our Latest
Tracks". Feature a selection of the band's latest tracks using the <audio>
tag, allowing fans to listen directly from the site. Include
the controls attribute.
o Set the src attribute of the <source> tag to the path of the audio file:
"https://edube.org/uploads/media/default/0001/04/track1.m
p3". Then, set the type attribute to "audio/mpeg". If the browser does not
support the <audio> tag, the following text should be displayed: "Your
browser does not support the audio element."
• Video
o Add an <h2> element with the following content: "Watch Our
Performances". Embed a video of live performances or music videos using
the <video> tag, showcasing the band's stage presence and engagement
with their audience. Include the controls attribute.
o Set the src attribute of the <source> tag to the path of the audio file:
"https://edube.org/uploads/media/default/0001/04/performa
nce1.mp4". Then, set the type attribute to "video/mp4". If the browser
does not support the <video> tag, the following text should be displayed:
"Your browser does not support the video element."
• Add an <h2> element with the following content: "Upcoming Tour Dates". Then,
create an unordered list to display upcoming tour dates and locations:
o The first listed item – "March 12, 2029, Orlando, FL", with the URL of the
ticket purchasing website "https://example.com/purchase-tickets-harmony-
heights-orlando", and the link text "Get Tickets".
o The second listed item – "March 14, 2029, Salt Lake City, UT", with the
URL of the ticket purchasing website "https://example.com/purchase-
tickets-harmony-heights-slc", and the link text "Get Tickets".
• Include the target attribute within the <a> tag, and assign the appropriate value to
it, which instructs the browser to open the link in a new tab or window.
• Add an <h2> element with the following content: "Follow Us". Underneath, create
a paragraph to provide a short message: "Stay updated with our latest news and
releases:".
• Insert Social Media Links – create a section for fans to follow the band on
social media, using hyperlinks to direct users to the band's official social media
pages:
o Link to the band's Faceblock profile
("https://www.example.com/faceblock/hh"). Between the opening and
closing <a> tags, place the text "Faceblock". After the Faceblock link, add
a line break to ensure the next link appears on a new line.
o Repeat this process for the band's Instagrump and Twotter profiles,
adjusting the URLs and link texts accordingly. For Instagrump, use and for
Twotter use
• Implement a simple contact form at the bottom of the page for fans to send
messages to the band or inquire about booking. The form should include fields
for the user's name, email, subject, and message, along with a submit button.
Begin by introducing the contact section – use an <h2> tag to create a heading,
and inside the <h2> tags, insert the text "Contact Us".
• Directly below the heading, initiate a form by adding the <form> tag, and create
input fields for user information:
o Name Field – begin with a <label> tag for the user's name. Use
the for attribute with a value of "name" to associate the label with the input
field. Inside the <label> tags, type "Name:". Insert a line break to ensure
the input field appears on a new line. Then, add an <input> tag for the
name input field. Set the type attribute to "text", the id to "name", and the
name to "name" as well. Follow the input field with another line break.
o Email Field – repeat the label and input field process for the email
address. Use a <label> with for="email" and type "Email:" inside. Use an
<input> tag for the email input field, setting type to "email", id to "email",
and name to "email". Add line breaks for spacing.
o Subject Field – for the subject of the message, again use a <label> tag
with for="subject" and include "Subject:" as the label text. Create an
<input> field for the subject, setting type to "text", id to "subject",
and name to "subject". Add line braks for spacing.
• Add a Textarea for the Message – use a <label> tag for the message area,
with for="message", and type "Message:" as the label text. After the label, insert
a line break. Introduce a <textarea> tag for the message input, assigning id to
"message" and name to "message". Place another line break tag for spacing.
• Include a Submit Button – add an <input> tag and set type to "submit"
and value to "Send". Close the <form> tag.
• Review your webpage to ensure that all multimedia content is properly displayed
and functional.
• Experiment and Customize – Feel free to explore further by integrating more
content or features to enrich your webpage according to your preferences.
Sample Solution
If you're finding the tasks challenging or need some assistance, you can check out the
sample solution provided below.
However, we encourage you to try tackling the project independently first. Doing so will
help you strengthen your HTML skills and deepen your understanding. Remember,
facing obstacles is a natural part of learning. Stay persistent, keep practicing, and you'll
see improvement over time. Best of luck!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="Official webpage of
Harmony Heights, featuring our latest music, tour dates, and
exclusive content for our fans.">
<title>Harmony Heights: Feel the Music</title>
</head>
<body>
<h2>Follow Us</h2>
<p>Stay updated with our latest news and releases:</p>
<a href="https://www.example.com/faceblock/hh">Faceblock</a><br>
<a
href="https://www.example.com/instagrump/hh">Instagrump</a><br>
<a href="https://www.example.com/twotter/hh">Twotter</a>
<h2>Contact Us</h2>
<form>
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<label for="subject">Subject:</label><br>
<input type="text" id="subject" name="subject"><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message"></textarea><br>
<input type="submit" value="Send">
</form>
</body>
</html>
Skills you'll gain: Styling and layout fundamentals, using global and event attributes,
and enhancing user interaction.
At the end of this module, you'll complete a project that showcases your understanding
of HTML styling and layout, followed by a test to wrap up the module.
• using the style attribute right in the HTML tags (inline styling), and
• putting styles inside the HTML document with a style section (internal
stylesheet and the <style> element).
While the best practice for styling web pages in most cases involves using external
stylesheets and CSS for greater flexibility and maintainability, in this section, we're
focusing on adding styles within an HTML document.
This approach not only helps build a strong foundation in styling basics but also
prepares you for the CSS techniques we'll discuss in the second course of the Web Dev
Essentials series, "CSS Essentials."
In the "CSS Essentials" course, the next installment of the Web Dev Essentials series,
we will shift our focus strictly to CSS, delving into more advanced styling methods to
enhance the visual appeal of web designs. This ensures a smooth transition and a solid
understanding as you progress from HTML styling to comprehensive CSS application.
It allows you to define the appearance and layout of the element without having to create a
separate CSS file or style block.
The syntax for inline styling involves using the style attribute directly within an HTML
element tag, followed by a property-value pair that defines the style. Here's how it is structured:
index.html
<element style="property: value;">
This means you add the style attribute to any HTML element, and then specify the CSS
property and its value you wish to apply to that element, formatted as "property: value;".
Here's an example showing how to use the style attribute for adding styles directly inside
a <p> (paragraph) element:
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Here is a normal paragraph.</p>
<p style="background-color: blue; color: white; font-weight:
bold;">
This paragraph has inline styling applied to it.
</p>
<p>Another normal paragraph.</p>
</body>
</html>
An internal stylesheet consists of CSS rules that you put inside a <style> element in the
HTML document. This method lets you style several HTML elements at once, avoiding the
need to repeat styling for each individual element.
You should place the <style> element in the <head> section of your HTML document. The
CSS rules inside this <style> element will then apply to matching elements in the <body> of
your document based on the selectors you use.
Selectors are the part of CSS rules that identify which HTML elements to apply the styling to.
Selectors can identify elements based on their tag name, class, ID, attributes, and more. For
example, if you want to apply a certain color to all the paragraphs on your page, you can use
the p selector to target all <p> elements.
index.html
<style>
/* CSS rules */
selector {
property: value;
/* more properties and values */
}
</style>
Each CSS rule includes a selector and one or more declarations (property-value pairs) inside
curly braces ({ and }).
index.html
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: orange;
}
p {
font-size: 18px;
color: blue;
}
</style>
</head>
<body>
<h1>This is Heading 1</h1>
<p>This is an example of using an internal stylesheet with
the style element. By defining CSS rules in the style element,
we can apply consistent styling across the entire page without
repeating the code for each element.</p>
</body>
</html>
While internal stylesheets are a fantastic way for smaller projects or for quick styling across your
HTML document, they might not be the most efficient for larger projects, where external
stylesheets are preferred. However, understanding and using internal stylesheets can give you a
solid foundation in CSS, preparing you for more complex styling techniques. This approach
mirrors how styles are managed in external stylesheets, providing a cohesive learning experience
as you progress in your web development journey.
If you're eager to learn more about CSS right away, you can jump ahead to Mozilla's CSS basics
guide to grasp some basics. However, in the second part of our course, we'll dive deeper into
CSS and cover some more advanced topics, including CSS syntax, the Box Model, CSS layout
techniques, and much more. So keep on learning!
In the next section, we'll delve into the essentials of using colors and font properties in HTML.
Understanding how to manipulate colors will allow you to design your webpages with the
desired aesthetic and mood, while mastering font properties will enable you to control the
readability and style of your text. These are key components in crafting an attractive and user-
friendly website, setting the foundation for more advanced design techniques.
Colors play a vital role in web design, as they evoke emotions and establish visual hierarchy.
Font properties, on the other hand, allow you to define the typeface, size, weight, and other
characteristics of the text on your web pages.
By combining the two, you'll learn how to enhance the overal aesthetic, readability, and
emphasis of your websites.
• by name – there are 147 color names that can be used, such as "red", "green", "blue",
"yellow", "purple", and "black".
• by hexadecimal value – a six-digit code preceded by a pound sign (#) that represents a
combination of red, green, and blue values. For example, #FF0000 represents the color
red.
• by RGB value – a set of three values representing the amount of red, green, and blue,
respectively. Each value ranges from 0 to 255. For example, RGB(255, 0,
0) represents the color red.
For example:
index.html
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: #FFFFFF;
background-color: green;
}
p {
color: RGB(0, 0, 255);
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
In the code, we've defined the colors using the following CSS rules within
the <style> element:
When the code is rendered in a web browser, the heading <h1> element will have white text
color and a green background color. The paragraph <p> element will have blue text color.
Here are some of the most popular colors and their codes used in HTML:
• Red: #FF0000
• Green: #00FF00
• Blue: #0000FF
• Black: #000000
• White #FFFFFF
Tip
There are many tools available online for generating hexadecimal values for colors, such as
the HTML CSS Color Picker. Experimenting with colors can be a fun and creative way to add
style to your HTML pages!
• The font-family property specifies the font to be used for the text. It can be set to a
specific font name, such as Arial, Times New Roman, or Helvetica, or a generic font
family such as serif, sans-serif, or monospace. The default value depends on the browser.
• The font-size property defines the size of the font. It can be set using an absolute
value such as pixels (px) or points, or a relative value such as percentages (%)or em units
(ems). The default value is normal.
• The font-weight property sets the weight, or thickness (boldness), of the font. It can
be set to a specific value name such as bold, bolder, or lighter, or to a numeric value
between 100 and 900, with 400 being the default value (normal).
• The font-style property defines the style of the font, such as normal (default
value), italic, or oblique.
Here's an example of inline styling where all four font properties are used:
index.html
<p style="font-family: monospace; font-size: 20px; font-weight:
900; font-style: normal;">
This is a paragraph of text.</p>
And here's an example of using internal CSS stylesheet to set the same four font properties:
index.html
<!DOCTYPE html>
<html>
<head>
<style>
p {
font-family: monospace;
font-size: 20px;
font-weight: 900;
font-style: normal;
}
</style>
</head>
<body>
<p>This is a paragraph of text.</p>
</body>
</html>
4.3 HTML Styling and Layout – Part 3
For example, you might use the <span> element to style a single word in a sentence with a
different color, font size or font style:
index.html
<p>This is a <span style="color: green;">sample text</span> with
some inline styling.</p>
In this example, the <span> element is used to style the phrase "sample text" with the color
green.
For example, you might use a <div> element to group together a set of images and apply a
border or padding to the entire group:
index.html
<div style="border: 1px solid black; padding: 10px;">
<img src="/uploads/media/default/0001/04/rect1.png" alt="Image
1">
<img src="/uploads/media/default/0001/04/rect2.png" alt="Image
2">
<img src="/uploads/media/default/0001/04/rect3.png" alt="Image
3">
</div>
4.3.4 When to Use <span> and <div>
While the <span> and <div> elements are non-semantic and should not be used to convey any
meaning on their own, they can be useful in certain situations:
1. Use <span> when you want to apply styles to a specific portion of text or a small group of
inline elements. For example:
index.html
<p>This is a <span style="color: blue;">blue</span> text.</p>
2. Use <div> when you want to group together a set of elements and apply styles to them as a
whole. For example:
index.html
<div>
<button>Button 1</button>
<button>Button 2</button>
</div>
Keep in mind that <span> and <div> elements have their use for providing layout and styling
to a web page, but they should not be used to replace semantic elements when a more appropriate
option exists.
In the later section of the course entitled Semantic Markup, you will learn about such options and
the benefits of using semantic elements to convey the meaning and structure of your content. So,
stay tuned and make informed choices to enhance the accessibility, usability, and SEO of your
web pages.
4.4 Global Attributes
We've already talked about the style attribute, but there are several more that are widely used,
such as: id, class, title, accesskey, lang, hidden, dir, translate, and onclick.
• unique identification, which lets you distinguish HTML elements from each other on
the page.
• styling, which allows you to apply specific CSS styles to a single element. (By targeting
the element's unique id, you can create custom styles that only affect that particular
element. You're going to learn about it in the second part of the course.)
• JavaScript manipulation, which lets you select and manipulate specific elements in the
DOM. (It makes it easy to access, modify, or perform actions on a particular element
without affecting others. Again, you're going to learn more about it in the Web
Development Essentials: JavaScript course.)
• anchors, which you can use to create internal (anchor) links within a webpage. (You
learned about them in the Links section of this course.)
index.html
<!DOCTYPE html>
<html>
<head>
<style>
#greeting {
font-size: 24px;
color: blue;
}
</style>
</head>
<body>
<p>Hello, World!</p>
<p id="greeting">Hello, world!</p>
<p>Hello, World!</p>
</body>
</html>
Remember that the id attribute should be unique within a page, meaning no two elements should
share the same id value. If you need to target multiple elements that share the same
characteristics, consider using the class attribute instead.
• grouping elements – the class attribute allows you to group multiple HTML elements
that share similar characteristics or purposes. Unlike the id attribute, class can be
assigned to multiple elements on a page.
• styling – by using the class attribute, you can apply consistent CSS styles to a group of
elements. This helps maintain a uniform appearance and promotes reusability of styles
across your webpage or even an entire website.
• JavaScript manipulation – when working with JavaScript, the class attribute can be
used to select and manipulate groups of elements with the same class. You can perform
actions or apply changes to all elements with the specified class at once, making it an
efficient way to manage similar elements.
• readability and maintainability – using class attributes can help improve the
readability and maintainability of your HTML and CSS code. By assigning meaningful
class names, you can easily understand the purpose or functionality of specific elements,
making it easier to update or modify your code in the future.
index.html
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: blue;
color: white;
font-weight: bold;
}
</style>
</head>
<body>
<p>Here is a normal paragraph.</p>
<p class="highlight">This paragraph has the 'highlight'
class applied to it.</p>
<p>Another normal paragraph.</p>
<p class="highlight">Another paragraph with the 'highlight'
class.</p>
</body>
</html>
As you can see, the class attribute acts like a label that you can attach to elements, allowing
you to target and style them using CSS. Let's see what happens in the code:
1. We start by defining a CSS rule (a class) in the <style> block. The rule is
named .highlight, and it includes properties like background-color, color,
and font-weight that determine how elements with this class will look.
2. As we move to the <body> section, you'll notice four <p> elements. Two of these
paragraphs have the class attribute set to "highlight". This means that we're
applying the styles defined in the .highlight class to these specific paragraphs.
3. When the browser renders the page, it sees the class="highlight" attribute on the
second and fourth paragraphs. It understands that these paragraphs should inherit the
styles defined in the .highlight class.
4. As a result, the background color of these two paragraphs becomes blue, the text color
turns white, and the text itself becomes bold. All of this is thanks to the CSS properties
we defined earlier.
In a nutshell, the class attribute acts like a bridge between the HTML and CSS worlds. It
allows you to apply a set of styles to one or more elements without duplicating the styles across
the document.
This approach keeps your HTML clean and separates content from presentation, making it easier
to manage and maintain consistent styles throughout your web pages. So, the next time you see
the class attribute, remember that you're harnessing its power to bring styling magic to your
HTML elements!
For example:
index.html
<button type="button" title="Click me for more information">
Learn More</button>
The title attribute is commonly used on HTML elements such as links, images, form controls,
and table elements.
To spark your curiosity, here are a few more global attributes that can be really handy. Try
playing around with them in your projects:
If you want to dive deeper into global attributes in HTML, the Mozilla Developer Network
(MDN) has a wealth of information.
The more you learn and work on different projects, the more you'll come across various
attributes and figure out creative ways to use them. So, keep exploring and adding to your
HTML toolkit.
Event attributes let HTML elements react to things users do, like clicking or hovering over
them. Data attributes let you keep extra info inside HTML tags without changing how things
look or act.
We'll give you a peek at these attributes and show some simple uses. To dive deeper into making
them work with JavaScript, check out our Web Development Essentials: JavaScript course.
For instance, using onclick, you can make a button show a message when clicked:
index.html
<button onclick="alert('Hello, World!')">Click Me</button>
In this example, clicking the button triggers an alert box with "Hello, World!" This simple
interaction is achieved without needing in-depth JavaScript knowledge.
This information can be used for scripting or styling purposes (you can store information such as
IDs, values, or other data that may be useful in web development), and can be accessed and
manipulated via JavaScript or CSS.
You start these attributes with data- and add a name that makes sense for what you're storing,
like data-recipe-id for a unique recipe number.
Imagine a cooking website where users can save recipes. You can use data attributes to keep
each recipe's unique ID right in the HTML:
index.html
<ul>
<li data-recipe-id="001">
<h2>Spaghetti with Meatballs</h2>
<p>A classic Italian dish that's perfect for a cozy
night in.</p>
<button class="save-recipe">Save Recipe</button>
</li>
<li data-recipe-id="002">
<h2>Chicken Tikka Masala</h2>
<p>A flavorful Indian curry that's sure to please.</p>
<button class="save-recipe">Save Recipe</button>
</li>
<li data-recipe-id="003">
<h2>Beef and Broccoli Stir Fry</h2>
<p>A quick and easy weeknight dinner that's packed with
flavor.</p>
<button class="save-recipe">Save Recipe</button>
</li>
</ul>
The possibilities are endless, and data attributes can be used in many different ways to add
functionality and customization to your website.
You're steadily advancing in your learning. In this module, you've learned how to make your
web pages look better and work better using styling and layout techniques. Ready to put these
skills to use?
Sunnydale School has a basic webpage that serves as an information hub for students,
parents, and staff. The current page features general information about the school,
including its mission, upcoming events, and contact details. While functional, the
webpage lacks the interactive and visual appeal necessary to engage its audience fully.
As a budding web developer, you have been approached by the school to revamp this
webpage.
Your task is to apply your HTML knowledge to enhance the page's aesthetics, usability,
and interactivity, making it a more inviting and informative resource for the Sunnydale
community.
Instructions
• In the same <style> element, set the body font to a friendly and readable
option, such as font-family: 'Arial', sans-serif;.
• Assign unique colors to each <h2> heading to differentiate the sections. Use
CSS rules like color: #32CD32; for the Mission Statement, color:
#FFA07A; for Upcoming Events, and color: #20B2AA; for Contact Us.
• For the "Contact Us" section, add a title attribute to the email and phone
number, offering a tooltip when hovered: "Click to copy email".
• While actual onclick behavior requires JavaScript, describe how it would work
by adding a comment at the end of the "Contact Us" section: "Imagine clicking
here shows a message: 'Thanks for reaching out!'".
• Group all the "Contact Us" info by wrapping it in a <div> tag. This makes
everything inside it, like the email and phone number, sit together in one area on
the page.
• Add the section class to the <div> element, and style this class in your internal
stylesheet by changing the background color and adding some space around the
text: background-color: #f8f3f3; and padding: 10px;.
• Review your webpage to ensure that all content is properly displayed and
functional.
• Suggest Changes – After creating the Sunnydale School webpage according to
initial specifications, you realize that the result might be excessively colorful,
potentially overshadowing the essential information. To address this, you
propose suggestions to moderate the color scheme, aiming to cultivate a more
professional and visually coherent presentation. For example:
o Refine the Color Palette – Choose a more restrained color palette that still
reflects the school's spirit but in a subtler way. Opt for complementary
colors or different shades of the same color for a harmonious appearance.
o Background and Font Colors – If you've used bright colors for the
background or fonts, try softer shades that are easier on the eyes. This
can help make the text more readable and the overall design more
appealing.
o Consistency in Headings – Instead of using different colors for each
heading (<h2>), consider using the same color for all headings but vary
the font weight or style (font-weight, font-style) to distinguish between
sections.
• Experiment and Customize – Experiment with these design adjustments on your
webpage. The goal is to balance creativity with clarity and cohesion, enhancing
the user experience while staying true to Sunnydale School's identity. After
making changes, revisit your testing and review process to assess the impact of
your design modifications.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sunnydale School</title>
</head>
<body>
<h1>Sunnydale School</h1>
<p>Welcome to Sunnydale School, dedicated to fostering a love of learning in every
student.</p>
<h2>Mission Statement</h2>
<p>Our mission is to provide a quality education that prepares all children for a successful
future.</p>
<h2>Upcoming Events</h2>
<ul>
<li>Science Fair - June 10</li>
<li>Art Exhibition - June 15</li>
<li>Sports Day - June 20</li>
</ul>
<h2>Contact Us</h2>
<p>Email: [email protected]</p>
<p>Phone: 555-1234</p>
</body>
</html>
SIMPLE SOLUTION
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sunnydale School</title>
<style>
body {
font-family: 'Arial', sans-serif;
}
h1 {
font-size: 24px;
font-weight: bold;
color: #1E90FF;
}
h2 {
margin-top: 20px;
}
#mission-statement {
color: #32CD32;
}
#upcoming-events {
color: #FFA07A;
background-color: #FFFFE0;
}
#contact {
color: #20B2AA;
}
.outdoor {
background-color: #AFEEEE;
padding: 5px;
}
.date {
font-weight: bold;
color: red;
}
.section {
background-color: #f8f3f3;
padding: 10px;
}
</style>
</head>
<body>
<h1>Sunnydale School</h1>
<p>Welcome to Sunnydale School, dedicated to fostering a love of
learning in every student.</p>
<div class="section">
<h2 id="contact">Contact Us</h2>
<p title="Email us at [email protected]">Email:
[email protected]</p>
<p title="Call us at 555-1234">Phone: 555-1234</p>
<!-- Imagine clicking here shows a message: 'Thanks for reaching
out!' -->
</div>
</body>
</html>
Unlike non-semantic elements such as <div> and <span>, which do not provide any
contextual information about the content they contain, semantic HTML elements provide
an easy, clear and concise way to describe the structure and meaning of web pages.
This helps create websites that are more accessible, searchable, and easily understood
by both humans and machines.
Semantic HTML is important for creating more efficient, flexible, and accessible web
content. This includes:
• Accessibility – by using semantic markup, you can make sure that your content
is accessible to everyone, including people with disabilities who use screen
readers and other assistive technologies to navigate the web. Semantic markup
helps these technologies to understand the content and present it in a
meaningful way.
• Search Engine Optimization (SEO) – search engines use semantic markup to
understand the content of a web page and rank it accordingly. By using semantic
markup, you can make sure that your content is properly indexed and easily
discoverable by search engines.
• Maintainability – semantic markup helps to create cleaner, more organized
code that is easier to read and maintain. By using descriptive tags, you can make
your code more self-explanatory, which makes it easier for other developers to
understand and update.
• Future-proofing – semantic markup is designed to be forward-compatible, which
means that it will continue to be relevant and useful as new technologies and
standards emerge. By using semantic markup, you can ensure that your code
will continue to be relevant and functional for years to come.
These elements typically start on a new line and stretch out as wide as their container,
creating significant sections within a webpage. Here are some examples:
• <header> – represents the introductory content for a page or section (it often
contains a logo, navigation menu, or other identifying information for the site)
• <nav> – represents a section of a page that contains links to other pages or
sections on the site. Use this for navigation links to help users find their way
around your site or page.
• <main> – represents the primary content of a page (it should not include any
content that is repeated across multiple pages, such as navigation menus,
footers, or sidebars)
• <article> – represents a self-contained unit of content or story that can be
independently distributed or reused, e.g. blog posts, news articles, or product
reviews.
• <section> – represents a section of a page that groups together related content
within a page or article (it can be used to divide a page into multiple sections or
to group together content within a larger section)
• <aside> – represents content that is not directly related to the main content of a
page, but rather provides additional information, context, or related resources,
e.g. sidebars, callouts, or related links;
• <footer> – represents the closing content for a page or section/the bottom part
of a page or section (it often contains copyright information, contact details, or
other supplemental information)
• <figcaption> – represents a caption or legend for a figure or image;
• <figure> – represents self-contained content, such as an image, diagram, or
code snippet, that is referenced in the main content of a page;
• <summary> – represents a summary or caption for a <details> element;
• <details> – represents a disclosure widget that can be used to show or hide
additional information;
• Heading tags (<h1> to <h6>) – outline the structure of content on the web page
and define a hierarchy.
Here's an easy example showing how you might use some of these elements together:
<!DOCTYPE html>
<html>
<head>
<title>WebDev Solutions</title>
</head>
<body>
<header>
<h1>Welcome to WebDev Solutions</h1>
<nav>
<ul>
<li><a href="\home">Home</a></li>
<li><a href="\about">About</a></li>
<li><a href="\services">Services</a></li>
<li><a href="\contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<article>
<h2>Our Services</h2>
<p>We offer a variety of services including web design,
development, and digital marketing.
Contact us to learn more!</p>
</article>
<article>
<h2>Our Customers</h2>
<p>Our customers are at the heart of everything we do.
We pride ourselves on delivering exceptional service
and building strong relationships with each and every
one of our clients.</p>
</article>
</main>
<footer>
<p>© 2023 WebDev Solutions. All Rights Reserved.</p>
</footer>
</body>
</html>
Let's break down the roles of each semantic element present in the code:
• The <header> element contains the website's name, "Welcome to WebDev Solutions,"
and a navigation bar (<nav>) with links to different sections of the site (Home, About,
Services, Contact).
• The <nav> element defines a set clickable links (<a>) that allow users to easily navigate
to the main sections of the website.
• The <main> element highlights the central, most important information, which includes
details about the services offered and the company's focus on its customers.
• The <article> element represents a self-contained composition that could stand
independently from the rest of the page content. It's ideally suited for blog posts, news
articles, and in this case, specific sections within the page that detail "Our Services" and
"Our Customers." Each <article> is meant to be independently distributable or
reusable.
• The <footer> element denotes the closing or end section of a page or section, and in
this case it includes copyright notice for WebDev Solutions, marking the end of the page
content.
Inline elements do not start on a new line and are typically used to change the meaning of a part
of the text, without creating a new block or section. Examples include:
• <em> – emphasizes text, usually displayed in italics, indicating a subtle shift in tone or
added stress on a word or phrase.
• <strong> – indicates strong importance or urgency of the text, commonly displayed in
bold.
• <mark> – highlights parts of text for reference or emphasis, often with a background
color.
• <cite> – used for referencing a title of a work, providing a semantic way to indicate
sources or references.
• <q> – defines a short inline quotation.
• <dfn> – represents the defining instance of a term.
• <abbr> – denotes an abbreviation or acronym; the full definition can be provided in
the title attribute.
• <data> – links the given content with a machine-readable translation (e.g., a product ID)
• <time> – represents a specific period or date, adding semantic meaning to times or dates
within text.
Here's one more straightforward example that demonstrates the application of semantic markup:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<article>
<h1>The Importance of Web Standards</h1>
<p>The web is built on <strong>standards</strong> to
ensure <em>consistency</em> and <mark>accessibility</mark> for
all users. Standards like HTML5 and CSS3 provide a foundation
for building <abbr title="Accessible Rich Internet
Applications">ARIA</abbr>-compliant sites that are accessible to
individuals with disabilities.</p>
<p>According to <cite>World Wide Web Consortium
(W3C)</cite>, adhering to web standards <q>ensures the long-term
growth of the Web</q>. To create semantic markup, developers
should use elements like <code><article></code>,
<code><section></code>, and <code><nav></code>
appropriately.</p>
<p>Learning web standards is crucial for <del>just
developers</del> <ins>everyone involved in web
development</ins>, from designers to content creators. Embrace
these standards to make the web a better place for <a
href="#">everyone</a>.</p>
<p>For more details, visit <a
href="https://www.w3.org/standards/">W3C Standards</a>.</p>
</article>
</body>
</html>
This example showcases how block-level and inline semantic elements can be combined to
create meaningful, well-structured content that is both accessible and semantically rich.
Each of these semantic elements plays a crucial role in structuring the web page in a meaningful
way.
By choosing these specific elements over generic ones like <div> or <span>, you make your
web page easier to understand and navigate, not just for people but also for search engines. This
helps with both accessibility and SEO.
Microdata and microformats are two ways of adding extra information to your website in a
structured way so that search engines can easily understand it.
For example, let's say we have a recipe website. We can use microdata or microformats to add
structured data to our recipe pages such as the name of the recipe, the ingredients, and the
cooking time. This makes it easier for search engines to recognize that the page is about a recipe
and show it to people who are searching for that recipe.
5.2.2 Microformats
Microformats use a specific class naming convention to define data within HTML elements.
For example, hCard is a microformat used to describe a person or organization and their contact
information. It is based on the vCard format, which is a standardized format for electronic
business cards that is used for exchanging contact information between different applications and
platforms.
To implement hCard, you would add class names to specific HTML elements to indicate what
information is contained within them. Search engines can then extract this information and
display it in search results.
Here's an example of how to use the hCard microformat to describe a person or organization and
their contact information:
index.html
<div class="vcard">
<p class="fn">John Smith</p>
<p class="title">Web Developer</p>
<p class="org">Smith Web Solutions</p>
<p class="tel">555-555-5555</p>
<a class="email"
href="mailto:[email protected]">john@smithwebsolutions.
com</a>
<p class="adr">
<span class="street-address">123 Main St.</span><br>
<span class="locality">Anytown</span>, <span
class="region">CA</span> <span class="postal-code">12345</span>
</p>
</div>
The code example we’ve provided uses the class name vcard to indicate that the information
contained within is structured according to hCard(vCard) specifications.
Within the vCard element, different contact information is defined using specific class names
on HTML elements. For example, the name of the person or organization is defined using
the fn class on a paragraph element. The job title and organization are defined using
the title and org classes, respectively. The contact phone number is defined using
the tel class on a paragraph element, while the email address is defined using the email class
on an anchor element. Finally, the address is defined using the adr class on a paragraph element,
with each component of the address (street address, locality, region, and postal code) defined
using their respective class names.
This structured data can then be extracted by search engines and displayed in a more organized
and informative way in search results.
5.2.3 Microdata and Schema.org
Microdata, on the other hand, uses HTML attributes to associate data with specific elements.
The most commonly used attribute for microdata is the itemprop attribute, which defines the
type of data contained within an HTML element. For example, if you have a page with a review
of a product, you could use the itemprop attribute to indicate the name of the product, the
author of the review, and the rating given.
Here's an example of using microdata to add schema.org structured data to a web page:
index.html
<div itemscope itemtype="http://schema.org/Person">
<h2 itemprop="name">John Smith</h2>
<p itemprop="jobTitle">Web Developer</p>
<p>
Contact me at:
<a href="mailto:[email protected]"
itemprop="email">[email protected]
</a>
</p>
</div>
5.3 Accessibility – Part 1
Web accessibility ensures that people with disabilities can perceive, understand, navigate,
and interact with your website just like anyone else. Disabilities can range from visual
impairments, like blindness or color blindness, to auditory impairments, motor disabilities that
affect the use of hands or limbs, and cognitive impairments that impact memory or processing
information. Making your website accessible means creating an online space where everyone
feels welcome and empowered.
By making your websites accessible, you're not only following ethical guidelines but also
expanding your audience and making the web a more inclusive place.
• Inclusivity – one of the main reasons for web accessibility is to ensure that your website
is inclusive and caters to a diverse range of users. When you create an accessible website,
you're making it possible for everyone, regardless of their abilities, to access and enjoy
your content.
• Legal and ethical responsibility – many countries have laws and regulations that require
websites to be accessible. By adhering to these guidelines, you're not only fulfilling your
legal obligations but also demonstrating a commitment to ethical principles and social
responsibility. Examples of such laws are the ADA – the Americans with Disabilities Act
in the USA, and the EAA – the European Accessibility Act in Europe.
• Expanded audience – designing with accessibility in mind means reaching a wider
audience. People with disabilities are a significant portion of the population, and by
accommodating their needs, you're tapping into a valuable demographic.
• Improved SEO – many accessibility practices align with search engine optimization
(SEO) best practices. Properly structured content, descriptive headings, and meaningful
image alt text can boost your website's search engine ranking.
The WCAG guidelines are organized into three levels of conformance: A, AA, and AAA. Each
level has specific success criteria that your website should meet to ensure accessibility (i.e. it
indicates the degree to which your website meets accessibility standards).
WCAG 2.1/WCAG 2.2 is the latest web standard published by W3C, but the works on the
WCAG 3.0 have already started.
Applying WCAG
Applying WCAG is a step-by-step process that involves understanding the guidelines, assessing
your website's accessibility, and implementing necessary changes. Let’s break down the process
into simple steps:
Remember, achieving full accessibility might not happen overnight. It's an ongoing process of
improvement and learning. By taking small steps and consistently applying WCAG guidelines,
you'll create a more inclusive online experience for all users.
ARIA enhances the accessibility of dynamic and interactive content by providing additional
information to assistive technologies, like screen readers. It ensures that users with disabilities
can effectively navigate and interact with your web applications.
For example:
index.html
<button role="button">Click me</button>
<a href="#" role="link">Read more</a>
<h2 role="heading">Important Information</h2>
In this example, the <button>, <a>, and <h2> elements have ARIA roles applied to them
using the roleattribute. The <button>element is given the role of "button",
the <a> element is given the role of "link", and the <h2> element is given the role
of "heading". These roles help assistive technologies understand the intended purpose of each
element, enhancing the accessibility of the content.
For example, you can use ARIA attributes like aria-expanded, aria-checked, and aria-
hidden to communicate whether a menu is open or closed, a checkbox is checked or
unchecked, or an element is hidden from screen readers, respectively:
index.html
<button aria-expanded="true">Toggle menu</button>
<input type="checkbox" aria-checked="false">
<div aria-hidden="true">This content is hidden from screen
readers.</div>
In this example, the <button> element uses aria-expanded to indicate that the menu is
currently open, the <input> element uses aria-checked to indicate that the checkbox is
unchecked, and the <div> element uses aria-hidden to hide its content from screen readers.
These ARIA attributes enhance the accessibility and understanding of the elements for users of
assistive technologies.
Again, to ensure your ARIA implementations are effective, it's important to test your web
application with screen readers and other assistive technologies. This will help you verify that
the added ARIA roles, states, and properties are accurately conveyed to users with disabilities.
5.4.4 Testing Accessibility
Testing your website for accessibility helps you identify potential issues and make necessary
improvements. Here's what you can do:
1. Use built-in accessibility tools to identify potential accessibility issues. Most modern
web browsers have built-in accessibility tool kits, for example:
o Chrome Accessibility DevTools: In Google Chrome, open your website, right-
click on an element, and select "Inspect." Go to the "Accessibility" tab in the
DevTools panel to see a list of accessibility issues.
o Firefox Accessibility Inspector: In Mozilla Firefox, right-click on an element and
select "Inspect Element." Go to the "Accessibility" tab in the Inspector panel to
view accessibility information and issues.
2. Validate HTML with W3C Validator – use the W3C HTML Validator to check your
HTML code for any syntax errors or structural issues that might affect accessibility.
Valid HTML ensures that your website is well-structured and follows best practices.
3. Test with screen readers – this can help you understand how users with disabilities
experience your content. You can use a free reader:
o NVDA (NonVisual Desktop Access) – a free screen reader for Windows
(download here: https://www.nvaccess.org/.)
o VoiceOver – a built-in screen reader on macOS and iOS devices. Enable
VoiceOver in the Accessibility settings and use it to navigate your website.
4. Check keyboard navigation to ensure that your website can be navigated using only a
keyboard. Use the "Tab" key to navigate through interactive elements, links, and forms.
Ensure focus indicators are visible and elements can be activated using the "Enter" key.
5. Use color contrast checkers, such as the one provided by WebAIM, to ensure that text
and background colors meet accessibility standards.
6. Finally, test with real users – conduct usability testing1 with real users, including those
with disabilities, to get feedback on the accessibility of your website. This can provide
valuable insights into real-world usage and identify any remaining issues. It also ensures
that your website is designed with the needs and preferences of your users in mind – it
adopts the user-centered design2 approach.
By following these simple steps and using the tools we’ve mentioned, you can identify and
address many accessibility issues on your website, making it more inclusive and user-friendly for
everyone.
A user-friendly website design and responsive layout reduce the likelihood of users leaving your
site due to a poor experience, and reflect positively on your brand, which helps you build trust
with your audience.
1
A method used to evaluate the ease of use and effectiveness of a website by observing real users as they interact with it.
2
User-centered design focuses on designing websites with the needs and preferences of users in mind. It involves understanding
your target audience, conducting user research, creating personas, and considering user feedback throughout the design process.
Let's explore some HTML best practices to help you become a proficient web developer:
1. Use semantic HTML – choose the appropriate HTML tags that accurately describe the
content they enclose. For example, use <header> for the page header, <nav> for
navigation menus, <main> for the main content, <article> for standalone
content, <section> for grouped content, and <footer> for the page footer. Semantic
tags enhance accessibility and make your code more meaningful.
2. Maintain consistent indentation and formatting throughout your code. Properly
indented code enhances readability (great minds say that code is read more often than
written – do you agree?) and makes it easier to identify the structure of your HTML
elements.
3. Whenever possible, avoid deprecated tags like <center>, <font>, and <strike>.
Instead, use CSS for styling and layout, and use appropriate HTML tags. Similarly, avoid
deprecated attributes such as frame.
4. Use lowercase tags and attributes – although HTML is case-insensitive, using
lowercase consistently improves code consistency and readability.
5. Use descriptive comments in your HTML code to explain complex sections, structures,
or special considerations. Comments are helpful for other developers (and your future
self) to understand the code's purpose and functionality.
6. Optimize Images – provide descriptive alternative text using the alt attribute for better
accessibility. Additionally, optimize image file sizes to improve page loading times.
7. Keep styles separate – avoid inline styles within your HTML elements. Instead, use
internal CSS styles or external CSS files (recommended – we’ll learn more about this in
the second course from this series) to keep the styling separate from your HTML content.
This approach promotes maintainability and allows for consistent design across multiple
pages.
8. Minimize use of <br> tags – use CSS for controlling line spacing and layout, instead of
relying heavily on the <br> tag for line breaks. Overusing <br> tags can lead to poor
code structure and hinder maintainability.
9. Ensure your HTML code is valid by adhering to the HTML specifications and using
proper nesting, opening, and closing tags. You can use online HTML validation tools to
check your code's validity.
10. Follow the Web Content Accessibility Guidelines (WCAG) to make your web content
accessible to users with disabilities. Use semantic HTML, provide meaningful alt text for
images, and ensure keyboard navigation works properly.
11. Test your HTML code on multiple browsers to ensure consistent functionality and
appearance. Different browsers might interpret HTML tags and styles differently.
12. Validate cross-device compatibility – test your website on different devices, screen
sizes, and resolutions to ensure responsive design and cross-browser compatibility.
13. Use meaningful IDs and class names – when assigning IDs and class names to
elements, choose descriptive names that convey their purpose or function. Avoid using
generic names like "div1" or "element2" as they don't provide meaningful context.
14. Specify the character encoding for your HTML documents using the <meta
charset="utf-8"> tag to ensure proper rendering of special characters and symbols.
15. Last but not least – regularly update your knowledge. Web technologies evolve rapidly.
Keep learning and staying updated with the latest HTML specifications, best practices,
and techniques to maintain the quality of your web projects.
By incorporating these HTML best practices into your web development workflow, you'll create
web pages that are cleaner, more efficient, and better equipped to provide a great user
experience. Following these guidelines not only benefits your website's visitors but also makes
your code more maintainable and collaborative.
You've made great progress. This module covered how to create web content that's both
optimized and accessible. You've learned how to use semantic markup to enhance user
experience, incorporate microformats and microdata, ensure web accessibility, understand and
apply WCAG guidelines, use ARIA roles, states, and properties, maintain cross-browser
compatibility, and follow HTML best practices. Are you ready to use these skills?
5.7.1 Harbor Light Community Center Website: Adding Accessibility and Structured Data
Scenario
The local community center, "Harbor Light Community Center," currently has a basic website
that provides information about its services, events, and educational programs. While the website
is functional, it lacks semantic structure, accessibility features, and modern web practices that
could enhance user experience and accessibility. You, as an aspiring web developer, have
volunteered to revamp the website.
Your goal is to apply your understanding of semantic markup, accessibility, and HTML best
practices to make the website more informative, accessible, and user-friendly for everyone in the
community.
Instructions
Follow the instructions below to create the webpage step by step:
1. Semantic HTML Implementation
• Convert the first <div> that includes the community center's logo and welcome message
into a <header> element.
• Transform the second <div> with textual navigation into a <nav> element containing a
list (<ul>) of navigation links (<li> with <a> tags). Assign href attributes to these links
for in-page navigation.
2. Main Content Structure
• Enclose the content starting from "About Us" to "Join Our Events" in a <main> element
for the primary content area.
• For each major section ("About Us", "Our Services", "Join Our Events"), replace
the <div> with a <section> element and ensure the use of appropriate headings
(<h2> instead of <h1> for section titles to maintain hierarchy).
• Ensure the event listed in the "Join Our Events" section ("Annual Summer Festival") is
enclosed with the <p> tag. Separate the name of the event and the time it takes place with
a line break. Add importance to the event name using the <strong> tag.
3. Optimizing Events SEO with Schema.org
• For the event's start date, enclose the date within a <time> element, ensuring to use
the datetime attribute for specifying the machine-readable date format.
• Implement Schema.org's Event microdata in this section for better SEO and structure,
wrapping the event details. Start with a <section> element attributed with itemscope
and itemtype="http://schema.org/Event". Make sure that the description and start date of
the event are marked up with itemprop="description" and itemprop="startDate",
respectively.
4. Contact Section and Footer
• Convert the last <div> into a <footer> element.
• Add an actual email link using [email protected] and the mailto protocol in the
"Contact Us" section for direct email communication.
• Add a paragraph at the end of the <footer> to include the copyright symbol followed by
the year and the organization's name: "© 2050 Harbor Light Community Center".
5. Accessibility Enhancements
• Apply descriptive alt attributes to the logo.jpg and community-center.jpg images
("Harbor Light Community Center Logo" and "Harbor Light Community Center People"
respectively).
• Add the navigation ARIA role to the navigation for better accessibility.
• For the decorative banner added to the website, ensure it's correctly marked to be ignored
by screen readers to enhance accessibility – apply the aria-hidden="true" attribute to
the <img> tag of the decorative banner. Ensure the alt attribute is set to an empty string
(alt="") to reinforce that this image does not convey essential information.
6. Adding Anchor Links for Navigation
• Assign unique IDs to each section (id="about", id="services", id="events",
and id="contact") corresponding to the navigation links.
• Add anchor links by updating the <nav> links to point to these IDs, enabling smooth
scrolling to each section.
7. Replace Deprecated Tag and Introduce CSS
• Locate and remove the deprecated <font> tag. In the <head> section of your HTML, add
an internal stylesheet (<style> element). Within this stylesheet, set the font style for
the <body> element to ensure all text inherits this style, effectively replacing the visual
effect previously applied with the <font> tag.
• Remove the deprecated <center> tag and apply CSS for centering and spacing:
o Wrap the webpage image logo element in a <div> container.
o In the <style> block of the <head> section, define a class named .center-and-
space-content. The class should center the content horizontally within
its <div> container (use the text-align: center; property) and introduce padding for
both vertical and horizontal spacing (use the padding: 10px; property), enhancing
the visual layout.
8. Testing and Review
• Validate the HTML to ensure it meets web standards.
• Test for accessibility, ensuring all content is accessible and navigable.
• Experiment, experiment, experiment!
<!DOCTYPE html>
<html>
<head>
<title>Harbor Light Community Center</title>
</head>
<body>
<font face="Arial, sans-serif">
<div>
<center><img src="https://edube.org/uploads/media/default/0001/04/logo.jpg" alt="Center
Logo">
Welcome to Harbor Light Community Center</center>
</div>
<div>
Home | About | Services | Events | Contact
</div>
<div class="banner">
<img src="https://edube.org/uploads/media/default/0001/04/decorative-banner.jpg"
alt="Decorative Banner">
</div>
<div>
<h1>About Us</h1>
<p>The Harbor Light Community Center has been at the heart of our community for over
30 years, offering a wide range of services and programs designed to support and enrich the lives
of our residents.</p>
<p><img src="https://edube.org/uploads/media/default/0001/04/community-center.jpg"
hspace="10" vspace="10"></p>
</div>
<div>
<h1>Our Services</h1>
<p>From educational workshops and sports leagues to wellness programs and art classes,
our services are tailored to meet the diverse needs of our community members.</p>
</div>
<div>
<h1>Join Our Events</h1>
<p>Our community center is a hub of activity, hosting events throughout the year. Don't
miss our annual summer festival for fun, food, and festivities for all ages.</p>
<br>
Annual Summer Festival:
Starts: July 20, 2050
</div>
<div>
Contact Us
<p>Have questions or want to get involved? Email us!</p>
</div>
</font>
</body>
</html>
Sample Solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Harbor Light Community Center</title>
<style>
body {
font-family: Arial, sans-serif;
}
.center-and-space-content {
text-align: center; /* Centers inline or inline-block content within the div */
padding: 10px; /* Adds padding around the content inside the div */
}
</style>
</head>
<body>
<header>
<div class="center-and-space-content">
<img src="https://edube.org/uploads/media/default/0001/04/logo.jpg" alt="Harbor Light
Community Center Logo">
<p>Welcome to Harbor Light Community Center</p>
</div>
</header>
<nav role="navigation">
<ul>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#events">Events</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<main>
<section id="about">
<h2>About Us</h2>
<p>The Harbor Light Community Center has been at the heart of our community for over
30 years, offering a wide range of services and programs designed to support and enrich the lives
of our residents.</p>
<p><img src="https://edube.org/uploads/media/default/0001/04/community-center.jpg"
alt="Community Center People"></p>
</section>
<section id="services">
<h2>Our Services</h2>
<p>From educational workshops and sports leagues to wellness programs and art classes,
our services are tailored to meet the diverse needs of our community members.</p>
</section>
<footer>
<h2 id="contact">Contact Us</h2>
<p>Have questions or want to get involved? Email us at <a
href="mailto:[email protected]">[email protected]</a>.</p>
<p>© 2050 Harbor Light Community Center</p>
</footer>
</body>
</html>
Skills you'll gain: Working with advanced HTML features, embedding external content,
and using HTML APIs and graphics.
At the end of this module, you'll complete a comprehensive project that incorporates
these advanced techniques and a final test to conclude the module.
6.1 Favicons
Favicons generally help users easily identify and distinguish between different websites when
multiple tabs or bookmarks are open. They are typically displayed as a tiny square image,
usually 16x16 pixels or 32x32 pixels in size (or even larger for high-resolution displays! Be sure
to create favicons in multiple sizes to ensure they look crisp and clear across various devices and
screen resolutions). They are commonly in the .ico, .png, or .gif file formats.
Favicons can be customized to reflect a brand logo, symbol, or any other relevant image that
represents the website's identity. Remember, adding a favicon is not just about aesthetics; it's
about leaving a lasting impression on your visitors.
To add a favicon to your HTML document, you need to place the following code inside
the <head> section:
index.html
<link rel="icon" href="favicon.ico" type="image/x-icon">
In this example, the rel attribute specifies the relationship of the linked resource to the
document, and href points to the location of the favicon file. The type attribute defines the file
type of the favicon, which is typically image/x-icon for .ico files.
If you prefer to use a different format for your favicon, change the file extension and
the type attribute to reflect the desired change. For example, if you want to use a PNG format
for your favicon, you can use the following code:
index.html
<link rel="icon" href="favicon.png" type="image/png">
It's important to place the favicon file in the root directory of your website so that it can be
easily accessed by the browser.
Remember to create multiple sizes of your favicon to ensure compatibility across different
devices. Here's an example that includes multiple sizes using the sizes attribute:
index.html
<link rel="icon" href="favicon.png" type="image/png"
sizes="16x16 32x32">
Feel free to experiment with different favicon designs, file formats, and sizes to find the perfect
representation for your website. Get creative, have fun, and make your favicon a memorable
symbol of your brand!
6.2 iFrames
They were first introduced in HTML 4.0 in 1997. They allow you to display (embed) external
content within your own web page, creating an integration of different sources of information.
What kind of external content? It can be maps, videos, social media feeds, other HTML
documents, and more. You can think of iFrames as virtual windows that let you peek into other
websites without leaving your own.
To create an iFrame, simply use the <iframe> tag in your HTML code. It allows you to specify
the source of the content you want to embed and use attributes to customize its appearance and
behavior.
For example, let's say you want to embed a YouTube video in your web page. To do so, you can
use the following code:
index.html
<iframe src="https://www.youtube.com/embed/VIDEO_ID" width="560"
height="315" frameborder="0" allowfullscreen></iframe>
• In the code snippet you set the source attribute (src) to the URL of the YouTube video
you want to embed, in this case https://www.youtube.com/embed/VIDEO_ID.
• You also specify the width and height of the iFrame to ensure the video fits nicely within
your page.
• The frameborder attribute is set to "0" to remove the border around the iFrame (to
show the border, set the attribute to "1").
• The allowfullscreen attribute allows the video to be viewed in fullscreen mode.
(You can also use "true" to allow fullscreen and "false" to restrict it.)
6.2.2 iFrame Attributes
When working with iFrames, you can utilize several attributes to customize their behavior and
appearance. You’ve already got familiar with the width and height attributes, letting you to
control the size of the iFrame. You're also familiar
with frameborder and allowfullscreen attributes.
• scrolling – controls the scrolling behavior within the iFrame. You can set it to "yes"
to enable scrolling, "no" to disable scrolling, or "auto" to let the browser determine if
scrolling is necessary. For example: scrolling="no".
• sandbox – sets the sandbox mode for the iFrame, which provides additional security
restrictions. You can use the sandbox attribute to restrict actions such as form
submission, script execution, and pop-up windows. For example: sandbox="allow-
scripts allow-popups".
When it comes to iFrames, you can make them responsive by setting their width and height
using relative units, such as percentages, instead of fixed pixel values. This allows the iFrames
to scale dynamically with the screen size, ensuring optimal viewing experience across devices.
For example, instead of using a fixed width of 560 pixels, you can set the width to 100% to
make the iFrame span the entire width of its parent container:
index.html
<iframe src="https://www.example.com" width="100%"
height="315"></iframe>
By using responsive techniques, your iFrames will adapt beautifully to any screen size, providing
a consistent and enjoyable experience for all users.
Here are some popular examples of HTML entities and their corresponding symbols:
You can use HTML entities to display these special characters or symbols in your HTML code.
For example, if you want to display a copyright sign (©), you would use © in your code:
index.html
OpenEDG © 2035. All rights reserved.
You can find the official list of character entities in the HTML Living Standard – Section 13.5:
Named Character references.
By understanding and utilizing HTML entities and encoding, you can confidently include special
characters, symbols, and emojis in your HTML code, ensuring that your web content is displayed
correctly and accurately across different browsers and devices.
6.3.2 Emojis
Emojis are small graphical icons or symbols used to express emotions, ideas, or concepts in
electronic communication.
They originated in Japan in the late 1990s and have since become widely popular and commonly
used in various forms of digital communication, including text messages, social media,
and online content.
Emojis are often used to convey emotions like happiness, sadness, excitement, or even to
represent specific objects like a sunflower or an animal like a dog. With a vast collection of
emojis available, you can choose from a wide variety of options to find the perfect emoji that
suits your message or content.
You can include emojis in your code using HTML entities or Unicode representations. To do
this, simply place the respective HTML entity code or Unicode representation within your text or
within appropriate HTML tags, such as <p>, <span>, or <h1>.
Here's an example of how you can include the "smiling face with open mouth and smiling eyes"
emoji (😄) in a paragraph:
• 😄, or
• 😄,
You can place these codes directly in your HTML code, and when the page is rendered, the
corresponding emoji will be displayed.
It's important to note that emoji support can vary across devices and browsers, so it's always a
good idea to test how emojis appear on different platforms. Additionally, it's worth mentioning
that the availability of emojis may also depend on the font being used to render the text.
Here are a couple of good sources where you can find official emoji character entity references
or Unicode representations:
• Unicode Emoji Charts – the Unicode Consortium, the organization behind emojis, has a
great online chart where you can explore the full range of emojis and find their official
Unicode codes: https://unicode.org/emoji/charts/full-emoji-list.html.
• Emojipedia – a user-friendly resource with loads of information about
emojis: https://emojipedia.org/.
Popular Emojis
Here are some of the most popular emojis and their corresponding HTML codes to create them
in your HTML content:
How do you do it? You need to divide an image into clickable areas, called hotspots, where each
hotspot can be linked to a specific destination, such as a web page or an action.
You can think of the <map> element as a special container that holds all your hotspots. Each
hotspot is defined using the <area> element, which determines the shape and coordinates of
the clickable area. By combining these elements, you can easily create interactive image maps
that enhance user experience and add interactivity to your web pages.
index.html
<h2>Choose the door game</h2>
<p>Open the door to see what's waiting for you behind it.</p>
<img
src="https://edube.org/uploads/media/default/0001/03/choose-the-
door.jpg"
alt="A picture with two doors" usemap="#two-doors">
<map name="two-doors">
<area shape="rect" title="A door with a white knob"
coords="80,80,275,450" href="https://example.com/option1"
alt="Open the door to Option 1">
<area shape="rect" title="A door with a black knob"
coords="540,75,745,460" href="https://example.com/option2"
alt="Open the door to Option 2">
</map>
Let's see what happens in the code. In this sample, interactive game called "Choose the Door,"
you can open the door to reveal what's hidden behind it. The image displays two doors with
different colored knobs. Each door is a clickable hotspot. If you click on the door with the white
knob, it will open the door to Option 1, which is represented by a specific URL. On the other
hand, if you click on the door with the black knob, it will open the door to Option 2, which is
also associated with a specific URL. Take your pick and see what awaits you behind the doors!
Then, experiment with your own image map.
There are several online tools that can help you create image maps easily without requiring in-
depth coding knowledge. Here are a couple of them:
• Image-Map.net: https://www.image-map.net/,
• Image Map Generator: https://imagemap.org/.
You can think of it as a special toolkit that helps different parts of a website talk to each other. It
allows you to add extra features and services to your web pages without starting from scratch.
Let's say you want to include a custom video player, an interactive map, or a way to remember
user settings on your site. With the right APIs, integrating these elements becomes
straightforward, allowing you to focus on creating a great user experience. You don't need to
create these features from scratch; you just need to know how to incorporate and use these APIs
in your project.
In the following sections, we'll explore some basic examples of HTML APIs, giving you a
glimpse into how they can transform and enhance your web projects.
This can be very useful for providing services tailored to their location, like showing the weather
in their area, finding nearby stores, or customizing content based on where they are.
Imagine you're making a website that tells users the weather. Instead of making them type their
city, you could use the Geolocation API to automatically find out where they are and then show
them the weather in their city.
Let's take a look at an example code that utilizes the Geolocation API to fetch the user's current
coordinates and display them on the webpage:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Geolocation Example</title>
</head>
<body>
<h1>Your Location</h1>
<p>Click the button to get your current location.</p>
<p id="result"></p>
<script>
const getLocationButton =
document.getElementById('getLocation');
const resultElement = document.getElementById('result');
getLocationButton.addEventListener('click', () => {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
resultElement.textContent = `Latitude: ${latitude},
Longitude: ${longitude}`;
});
} else {
resultElement.textContent = "Geolocation is not
supported by your browser.";
}
});
</script>
</body>
</html>
• HTML Structure – it sets up a simple webpage with a title, a button that says "Get
Location", and a paragraph where the location will be displayed.
• JavaScript Functionality – this is what happens when someone clicks the "Get Location"
button:
o The script first checks if the user's browser supports the Geolocation API.
o If the browser supports it, the script asks the browser for the user's current
position.
o Once it gets the position, it extracts the latitude and longitude from the position
data and displays it in the paragraph.
o If the Geolocation API is not supported by the user's browser, it displays a
message saying "Geolocation is not supported by your browser."
If the script section looks daunting initially, it's okay. The purpose of this example is to showcase
the types of functionalities you can integrate into your websites by utilizing APIs.
Think of APIs as "black boxes" – you don't need to know all the inner workings to use them. The
key takeaway is recognizing that these tools enable you to enhance your site with advanced
features without having to build everything from scratch.
You can even make your own music player or video player without needing any extra software.
It's all possible with a bit of HTML, some style changes with CSS, and a sprinkle of JavaScript
for functionality.
index.html
<audio controls>
<source src="/uploads/media/default/0001/04/your-audio-
file.mp3" type="audio/mp3">
Your browser does not support the audio element.
</audio>
The code snippet adds an audio player to your webpage that plays a song.
The controls attribute adds play, pause, and volume controls automatically, so you don't have
to do anything else to get a basic player running. If you want to customize it, you can start
exploring the API's capabilities with JavaScript in the third part of the Web Development
Essentials series – Web Dev Essentials: JavaScript.
• Session Storage, which is like a temporary memory for your website visit. It remembers
things while your browser is open, but once you close it, everything is forgotten.
• Local Storage, which you can think of as a more permanent memory. It keeps data even
after you close and reopen your browser. This is great for saving preferences that make
your visits more personal and convenient.
For instance, you can use this API to remember a user's chosen theme or username, so the next
time they visit the website these will be applied automatically, enhancing their experience on
your site:
index.html
// Save the theme to local storage
localStorage.setItem('theme', 'dark');
1. Saving a theme setting – the code starts by saving a setting on your computer that tells
the website what theme you prefer, in this case, a "dark" theme. It's like leaving a note for
yourself so you remember something later.
2. How it saves – it uses something called localStorage to save this note. Think
of localStorage as a small, private storage space on your computer where the website
can save bits of information. Here, it saves a piece of information with the label "theme"
and assigns it the value "dark".
3. Getting the theme back – later, when you come back to the website, the code looks into
that storage space to find the note it left earlier. It checks for the "theme" label to see
what you preferred.
4. Applying your preference – once it finds that note and sees "dark", it knows you prefer
the dark theme. So, it changes the website's appearance to dark mode. This is done by
adding "dark" to the website's list of characteristics (specifically, to the body of the
webpage), which triggers the dark theme to activate.
In essence, this code is like a personal assistant for the website. When you tell it you like the
website to be in dark mode, it remembers your choice by writing it down. The next time you
visit, it looks at its notes, sees you like dark mode, and sets everything up just the way you like it
before you even have to ask.
1
Small pieces of information left on the user's computer by a webpage via a web browser.
Think of it as a way to tap your users on the shoulder and say, "Hey, check this out!" when you
have something important to tell them. This could be a reminder, an alert, or a news update.
This feature is really useful for web applications, news sites, or any website that wants to keep its
users up-to-date without needing them to stay on the webpage.
Imagine you want to make your webpage more engaging by adding a dynamic background, a
playful animation, or even a simple game. The Canvas API is your go-to resource for bringing
those ideas to life – from simple designs to complex interactive experiences.
In the next section, we will dive into a basic example that showcases how you can start
incorporating these visual enhancements into your website.
Conclusion
These are just a few examples of HTML APIs that can add useful and interactive features to your
web pages. As you learn about and experiment with these APIs, you'll gain the ability to create
more interactive, engaging, and user-friendly web experiences. The knowledge gained in this
unit will lay the groundwork for your continued exploration into more advanced web
development topics.
• the Canvas element (<canvas>), which allows you to draw and animate 2D shapes and
images directly through JavaScript, and
• Scalable Vector Graphics (SVG) (<svg>), a way to include high-quality graphics that
can scale to any size without losing clarity, perfect for logos, icons, and complex
illustrations.
Both of these methods offer unique advantages and can be used in different scenarios depending
on your project needs.
6.6.2 Canvas
The <canvas> element acts as a virtual canvas where you can draw shapes, images, and
animations. It employs a pixel-based approach for graphics creation, granting precise control
over individual pixels. Think of it as a digital drawing board that can be manipulated using
JavaScript.
While you can create the <canvas> element in HTML, you need JavaScript to make it perform
meaningful actions (drawing on a canvas in HTML involves using the Canvas APIe1, a set of
tools for drawing shapes, lines, images, text, and more on the canvas).
Therefore, at this stage, we're merely introducing the concept of canvas, with more in-depth
exploration coming up when we delve into JavaScript.
For now, let's look at a basic example:
index.html
<canvas id="myCanvas" width="300" height="200"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(10, 10, 200, 100);
</script>
1
A collection of JavaScript methods and functions that allow you to interact with and manipulate the content within the canvas
element.
SVG graphics are resolution-independent, which makes them suitable for various devices and
screen sizes.
index.html
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="black" />
</svg>
1. The <svg> element defines the SVG container with a width and height of 100 units.
2. The <circle> element is used to draw a circle, with a center at coordinates (50, 50), a
radius of 40 units, and a fill color of black. The result is a simple black circle displayed
on the webpage.
When starting with SVGs, creating vector graphics from scratch might seem daunting.
Fortunately, there are websites where you can find thousands of ready-made SVG icons and
graphics for free. These can be a great resource for sprucing up your website without needing to
draw everything yourself.
As you continue your learning journey, we encourage you to delve deeper into these topics and
leverage their capabilities to enhance your web projects. If you're eager for more knowledge
(we're sure you are!), we recommend visiting the MDN Web Docs to learn more:
You've accomplished a significant milestone. In this concluding module, you explored advanced
HTML concepts such as favicons and iFrames, HTML entities, emojis, creating image maps,
delving into various HTML APIs, and investigating HTML Graphics.
These skills equip you to add richer content and functionality to your web projects, pushing the
boundaries of what you can achieve with HTML. Are you ready to leverage these advanced
techniques in your future projects?
You are part of a collaborative project aiming to create an interactive web page titled
"Discover Your World". This page is designed to educate users about different
continents and their unique geographical features through a fun and engaging
interactive map. You've been tasked with setting up the HTML structure and ensuring
that the page is visually appealing and functional. Another developer from your team will
handle the JavaScript functionality, providing scripts for geolocation features and
interactions with the map.
As the front-end developer, your job is to prepare the groundwork for this interactive
experience. You will:
• Add a Favicon – ensure the web page stands out with a globe-themed favicon to
match the world discovery theme.
• Embellish with Emojis – make the header more inviting by incorporating a globe
emoji.
• Prepare for Geolocation – insert a button that will later be linked to geolocation
functionality, allowing users to discover which continent they're currently on
based on their physical location.
• Create an Interactive Map – using an image of the world map, define clickable
areas corresponding to each continent. This map will later be scripted to display
information about each continent, such as major rivers, mountains, and
landmarks.
Once your tasks are completed, the web page will display a beautiful world map, inviting
users to click on a continent to learn more about it. The geolocation button will enhance
the interactive experience by providing users with personalized information based on
their location. This project, when combined with the JavaScript functionality provided by
your teammate, will offer an educational and engaging way to learn about our world.
Remember, the JavaScript functionality, including handling clicks on the map areas and
implementing the geolocation feature, will be provided by another developer on your
team. Your focus is on setting up the HTML structure and ensuring the page is ready for
those interactive elements to be integrated.
Instructions
1. Favicon Addition
• Prepare for dynamic interactions by linking an external JavaScript file. This script
will handle user interactions and display continent-specific information. In
the <head> section or just before the closing tag of your HTML document, add
a <script> tag with the src attribute pointing to the location of your script.js file:
"script.js".
3. Add an Emoji to Your Heading
• Add a globe emoji to the page title to emphasize the world exploration theme.
Insert the emoji with the codepoint code point U+1F30D directly into the HTML
content of your <h1> tag. Remember, to specify this emoji in HTML using the
codepoint, you need to replace the "U+1" part with the characters "&#x".
• Go to Unicode.org/emoji/charts, choose an emoji that fits the theme of the page,
and insert it somewhere into your HTML code.
• Implement a feature that allows users to find out which continent they are
currently on. Below the paragraph tag, add a <button> that, when clicked, uses
the Geolocation API to display the user's current continent along with interesting
geographical facts..
• Give the button an id attribute with the value getLocation, and set its text
content to something descriptive, like "Discover Location".
• Enhance the page with an image map of the world. Users should be able to click
on different continents to learn about key geographical features. For each
continent on your world map, add an <area> tag within the <map> tag.
• Use the following attributes to define each continent area:
o alt and title for "North America", "South America", "Europe", "Africa",
"Asia", and "Australia and Oceania"
o id for "north-america", "south-america", "europe", "africa", "asia", and
"australia-and-oceania"
o shape – "rect" for each of the areas
• The coords attribute values will depend on the specific areas of your image
map. Use an image map generator or manually determine the coordinates.
Alternatively, use the following values: "386,283,41,17" (North America),
"209,501,358,288" (South America), "391,68,505,217" (Europe),
"533,217,387,448" (Africa), "893,153,506,1" (Asia), and "679,353,872,480"
(Australia and Oceania).
Html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Discover Your World</title>
<!-- Task 1: Add the favicon link here -->
<!-- Task 2: Add link to script here -->
</head>
<body>
<h1>Discover Your World <!-- Task 3: Add an emoji here --></h1>
<p>Click the button to learn about the continent you're on and some famous geographical
features.</p>
<!-- Task 4: Add a button for displaying geolocation information here -->
Script:
document.addEventListener('DOMContentLoaded', function() {
const continentInfo = {
'north-america': {
continent: 'North America',
river: 'Mississippi River',
mountain: 'Denali',
landmarks: 'Grand Canyon, Statue of Liberty, Niagara Falls'
},
'south-america': {
continent: 'South America',
river: 'Amazon River',
mountain: 'Aconcagua',
landmarks: 'Machu Picchu, Galapagos Islands'
},
'europe': {
continent: 'Europe',
river: 'Danube River',
mountain: 'Mont Blanc',
landmarks: 'Eiffel Tower, Colosseum, Acropolis of Athens'
},
'africa': {
continent: 'Africa',
river: 'Nile River',
mountain: 'Mount Kilimanjaro',
landmarks: 'Sphinx, Table Mountain'
},
'asia': {
continent: 'Asia',
river: 'Yangtze River',
mountain: 'Mount Everest',
landmarks: 'Great Wall of China, Petra'
},
'australia-and-oceania': {
continent: 'Australia and Oceania',
river: 'Murray River',
mountain: 'Mount Kosciuszko',
landmarks: 'Sydney Opera House, Great Barrier Reef, Uluru'
}
};
function displayContinentInfo(continentId) {
const info = continentInfo[continentId];
if (info) {
alert(`Continent: ${info.continent}\nRiver: ${info.river}\nMountain:
${info.mountain}\nLandmarks: ${info.landmarks}`);
} else {
alert('Information not available');
}
}
document.querySelectorAll('area').forEach(area => {
area.addEventListener('click', function() {
const continentId = this.id;
displayContinentInfo(continentId);
});
});
discoverLocationButton.addEventListener('click', () => {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const continentId = determineContinentByGeo(latitude, longitude);
displayContinentInfo(continentId);
}, (error) => {
alert("Error obtaining geolocation: " + error.message);
});
} else {
alert("Geolocation is not supported by your browser.");
}
});
function determineContinentByGeo(latitude, longitude) {
if (latitude > 35 && longitude > -10 && longitude < 40) {
return 'europe';
} else if (latitude < 0 && longitude > -80 && longitude < -34) {
return 'south-america';
} else if (latitude > 0 && longitude > -130 && longitude < -70) {
return 'north-america';
} else if (latitude > 5 && latitude < 60 && longitude > 40 && longitude < 180) {
return 'asia';
} else if (latitude > -35 && latitude < 35 && longitude > 10 && longitude < 50) {
return 'africa';
} else if (latitude < -10 && longitude > 110 && longitude < 180) {
return 'australia-and-oceania';
}
alert("Continent could not be determined based on your location.");
return null; // Fallback for locations not covered
}
});
Solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Discover Your World</title>
<link rel="icon"
href="https://edube.org/uploads/media/default/0001/04/web-
favicon.png" type="image/png">
<script src="script.js"></script>
</head>
<body>
<h1>Discover Your World 🌍</h1>
<p>Click the button to learn about the continent you're on
and some famous geographical features. </p>
<img
src="https://edube.org/uploads/media/default/0001/04/continents.
jpg" usemap="#image-map" alt="World Map">
<map name="image-map">
<area target="" alt="North America" title="North
America" id="north-america" coords="386,283,41,17" shape="rect"
href="javascript:void(0);">
<area target="" alt="South America" title="South
America" id="south-america" coords="209,501,358,288"
shape="rect" href="javascript:void(0);">
<area target="" alt="Europe" title="Europe" id="europe"
coords="391,68,505,217" shape="rect" href="javascript:void(0);">
<area target="" alt="Africa" title="Africa" id="africa"
coords="533,217,387,448" shape="rect"
href="javascript:void(0);">
<area target="" alt="Asia" title="Asia" id="asia"
coords="893,153,506,1" shape="rect" href="javascript:void(0);">
<area target="" alt="Australia and Oceania"
title="Australia and Oceania" id="australia-and-oceania"
coords="679,353,872,480" shape="rect"
href="javascript:void(0);">
</map>
</body>
</html>
<script>
document.addEventListener('DOMContentLoaded', function() {
const continentInfo = {
'north-america': {
continent: 'North America',
river: 'Mississippi River',
mountain: 'Denali',
landmarks: 'Grand Canyon, Statue of Liberty, Niagara
Falls'
},
'south-america': {
continent: 'South America',
river: 'Amazon River',
mountain: 'Aconcagua',
landmarks: 'Machu Picchu, Galapagos Islands'
},
'europe': {
continent: 'Europe',
river: 'Danube River',
mountain: 'Mont Blanc',
landmarks: 'Eiffel Tower, Colosseum, Acropolis of Athens'
},
'africa': {
continent: 'Africa',
river: 'Nile River',
mountain: 'Mount Kilimanjaro',
landmarks: 'Sphinx, Table Mountain'
},
'asia': {
continent: 'Asia',
river: 'Yangtze River',
mountain: 'Mount Everest',
landmarks: 'Great Wall of China, Petra'
},
'australia-and-oceania': {
continent: 'Australia and Oceania',
river: 'Murray River',
mountain: 'Mount Kosciuszko',
landmarks: 'Sydney Opera House, Great Barrier Reef, Uluru'
}
};
function displayContinentInfo(continentId) {
const info = continentInfo[continentId];
if (info) {
alert(`Continent: ${info.continent}\nRiver:
${info.river}\nMountain: ${info.mountain}\nLandmarks:
${info.landmarks}`);
} else {
alert('Information not available');
}
}
document.querySelectorAll('area').forEach(area => {
area.addEventListener('click', function() {
const continentId = this.id;
displayContinentInfo(continentId);
});
});
const discoverLocationButton =
document.getElementById('discoverLocation');
discoverLocationButton.addEventListener('click', () => {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const continentId = determineContinentByGeo(latitude,
longitude);
displayContinentInfo(continentId);
}, (error) => {
alert("Error obtaining geolocation: " + error.message);
});
} else {
alert("Geolocation is not supported by your browser.");
}
});
</script>
Imagine you and your friends are avid travelers, each with a unique perspective and
love for different corners of the globe. Over countless journeys, you've encountered
cities that captured your hearts, stirred your imaginations, and left you with stories
begging to be shared. Inspired by these adventures, you've decided to launch the
"Global Adventures Blog" to showcase "My Top 3 Cities in the World," a curated
collection of your most cherished urban explorations.
Your task is to create a vibrant and engaging travel blog that brings to life the essence
of your top 3 cities. This blog will serve as a digital scrapbook, featuring detailed entries
about each city's unique attractions, culinary delights, cultural richness, and the indelible
impressions they've left on you.
As the HTML architect, your mission is to craft the structural foundation of this blog,
laying out a canvas for stories, photos, and memories to unfold. Later, your colleagues
will infuse the blog with eye-catching styles (CSS) and interactive elements (JS).
(For convenience, the styles have been provided to you in the editor.)
Instructions
1. Homepage (index.html)
Your homepage is the gateway to your global adventures, setting the tone for the entire
blog. It should radiate the excitement of discovery, the warmth of shared experiences,
and the allure of the unknown. This is where you invite fellow wanderers to join you and
your friends on a journey through the cities that have captured your hearts.
• Header – Start with a <header> element that serves as the introduction to your
blog. Incorporate an <h1> heading that's both inviting and evocative, such as
"Journeys of Friendship: Exploring the World Together." Follow this with
a <p> tag to offer a brief but compelling welcome message, perhaps sharing a
glimpse into what makes traveling with friends so special and hinting at the
adventures that lie ahead.
• Navigation Bar – Below your header, implement a <nav> element containing a
list (<ul>) of links (<li><a href="...">...</a></li>) for easy navigation.
Your navbar should include links to the Home page, Cities (with dropdowns or
links to individual city pages if you decide to expand later), Gallery, Contact, and
Subscribe pages. This ensures that visitors can effortlessly explore every facet of
your blog.
• Slideshow or Image Selection – To visually engage your visitors from the
outset, consider incorporating a slideshow or a selection of standout images
representing each of the three cities. This can be achieved with a simple
JavaScript plugin or CSS for styling, but for the structure, ensure you have a
dedicated <div> or <section> for this feature right below the navigation bar.
Use the <img> tag for each image, and consider adding <figcaption> for
captions that tease the story behind the image or the city it represents.
Hide
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Global Adventures Blog</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Journeys of Friendship: Exploring the World
Together</h1>
<p>Welcome to our Global Adventures Blog, where every
lane, alley, and boulevard has a tale waiting to be discovered.
Join us as we share our top 3 cities that have stolen our hearts
and fueled our wanderlust.</p>
</header>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="city1.html">Cities</a></li>
<li><a href="city2.html">Cities</a></li>
<li><a href="city3.html">Cities</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
<section id="photo-gallery">
<!-- Placeholder for images -->
</section>
<section id="newsletter">
<!-- Placeholder for newsletter -->
</section>
Dedicate a page to each city, weaving together narratives, visuals, and personal
anecdotes to portray the city's essence.
• Header and Introduction – Begin with a <header> containing the city's name
as an <h1> tag. Follow with a <p> tag for an introductory paragraph that
highlights your personal connection to the city or an unforgettable experience you
had there.
• Structured Content Sections – Divide your content into sections
(<section> tags) for different themes such as landmarks, culinary delights,
cultural experiences, and personal anecdotes. Use <h2> or <h3> tags for
subtitles.
• Multimedia Elements – Use <figure> and <figcaption> to add images that
tell a story or highlight key attractions, embedding these within the relevant
sections. Embed videos using <iframe> tags to provide virtual tours or share
moments that pictures alone can't capture.
• Personal Reflections – Include sections for personal stories or reflections to
share why these cities are meaningful to you. This could be a memorable
interaction, a culinary discovery, or a moment that took your breath away.
Hide
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>City A - Global Adventures Blog</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>City A: A Journey Through Time and Taste</h1>
<p>Our adventure in City A was more than just a visit;
it was a deep dive into a culture rich with history and culinary
excellence. Here's what made City A unforgettable for us.</p>
</header>
<nav>
<!-- Navigation bar -->
</nav>
<section id="landmarks">
<h2>Iconic Landmarks</h2>
<figure>
<img src=" alt="Landmark in City A">
<figcaption>The majestic view of Landmark X, a
historical beacon of City A.</figcaption>
</figure>
<p>Exploring the landmarks of City A, we were captivated
by the stories behind each architectural marvel...</p>
</section>
<section id="culinary-delights">
<h2>Culinary Delights</h2>
<figure>
<img src=" alt="Cuisine in City A">
<figcaption>A taste of City A's renowned dish, a
true culinary masterpiece.</figcaption>
</figure>
<p>City A's cuisine is a palette of flavors, each dish
narrating its own story of tradition and innovation...</p>
</section>
<section id="cultural-experiences">
<h2>Cultural Experiences</h2>
<p>Immersing ourselves in the culture of City A was like
walking through a living museum, each street and alley echoing
the tales of yesteryears...</p>
<iframe width="560" height="315" src=" title="YouTube
video player" frameborder="0" allow="accelerometer; autoplay;
clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</section>
<section id="personal-anecdotes">
<h2>Our Stories</h2>
<p>Among the myriad of experiences, one particular
moment stood out for us in City A. It was when...</p>
</section>
<footer>
<!-- Footer content -->
</footer>
</body>
</html>
3. Gallery Section
Offer a visual journey through your travels, letting the beauty and diversity of your
experiences shine through photographs.
• Header – Start with an <h1> tag to name your gallery (e.g., Travel Gallery) and
a <p> tag for a brief introduction that invites visitors to explore your gallery.
• Photo Gallery Structure – Use a <section> with a class (e.g., photo-gallery) to
contain your gallery. Within this section, create a list (<ul>) where each list item
(<li>) represents a photo entry. Using a list to create an image gallery is a
common practice in web development for several reasons: it enhances semantic
structure, improves accessibility, facilitates styling, and aids in maintaining
organized content for both users and search engines.
• Images and Captions – For each photo, use a <figure> element to group the
image (<img>) and its caption (<figcaption>). This semantic HTML structure
not only organizes your gallery but also provides context for each image,
enhancing the storytelling aspect of your gallery.
• Contextual Captions – Use <figcaption> to provide anecdotes or brief stories
about each photo. This could be a memorable experience, the emotions you felt
at that moment, or an interesting fact about the location.
Hide
<section id="photo-gallery">
<h1>Travel Gallery</h1>
<p>Step into our world of adventures. Each photo tells a
story, each moment a memory.</p>
<ul>
<li>
<figure>
<img src=" alt="Breathtaking view of City A">
<figcaption>The day we lost track of time
watching the sunset in City A.</figcaption>
</figure>
</li>
<li>
<figure>
<img src=" alt="Vibrant street in City B">
<figcaption>A vibrant street in City B that
danced to the rhythm of local life.</figcaption>
</figure>
</li>
<li>
<figure>
<img src=" alt="Delicious dish from City C">
<figcaption>Our first taste of City C's
legendary cuisine – unforgettable.</figcaption>
</figure>
</li>
<!-- Add more <li> elements for each photo you wish to
showcase -->
</ul>
</section>
Invite readers to connect, share their own stories, or ask questions about your travels.
Craft a user-friendly contact form with <input> fields for basic information and a
<textarea> for messages, fostering a community of fellow travel enthusiasts.
• Form Structure – Start with a <form> tag to define the form area. Use the
method attribute to specify how to send form data (e.g., method="post").
• Basic Information Fields – Include <input> elements for essential information
such as name, email, and subject. Use appropriate type attributes for each (text,
email, and so on), and ensure each input has a corresponding <label> for
accessibility.
• Message Textarea – Add a <textarea> element for longer messages, allowing
readers to share their stories or inquiries in more detail.
• Submit Button – Provide a submit button (<input
type="submit"> or <button type="submit">) so users can easily send their
messages.
• Styling and Accessibility – Ensure labels are clearly associated with their
respective input fields (using the for and id attributes) to enhance accessibility.
Hide
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Us - Global Adventures Blog</title>
<!-- Include any external CSS files here -->
</head>
<body>
<h1>Contact Us</h1>
<p>Got a travel story to share? Questions about our
adventures? Drop us a message!</p>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="subject">Subject:</label>
<input type="text" id="subject" name="subject">
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4"
required></textarea>
5. Newsletter Subscription
Offer a way for readers to stay updated on your latest adventures and blog entries. Set
up a subscription form for visitors to receive email updates, ensuring they never miss
out on new stories or travel tips.
• Form Setup – Use a <form> tag to create the subscription form area, specifying
a method attribute (typically post) to indicate how the form data should be sent.
• Email Input Field – Include an <input> element with
the type="email" attribute for subscribers to enter their email addresses. This
ensures that the form accepts only valid email formats. Accompany this with
a <label> for better accessibility.
• Subscription Confirmation – Consider adding a checkbox (<input
type="checkbox">) for users to confirm their willingness to receive newsletters,
which aligns with best practices for consent.
• Submit Button – Incorporate a submit button using <input
type="submit"> or <button type="submit">, labeled with an action-
oriented text like "Subscribe" or "Join Us".
• Enhancing User Experience – Utilize placeholder text within the email input to
provide an example or instruction (e.g., "Enter your email address").
Hide
<section id="newsletter">
<h1>Stay Updated with Our Adventures!</h1>
<p>Subscribe to our newsletter and never miss a story from
the road.</p>
<div>
<input type="checkbox" id="consent" name="consent"
required>
<label for="consent">I agree to receive email
updates and promotions.</label>
</div>
6. Footer
Craft a footer that serves as a closing statement for your website, providing essential
information and links that reinforce the connectivity and community of your Global
Adventures Blog.
• Essential Links – Begin with a <footer> tag encompassing the entire footer
section. Inside, use a <nav> or <ul> element to list links such as "About Us,"
"Privacy Policy," "Terms of Use," and any other important pages. These links
offer visitors more information about your blog and legal assurances, enhancing
transparency and trust. (For the purpose of this project, you can use
placeholders (e.g., href="#") for these links, allowing you to focus on structure
without needing complete content.)
• Social Media Icons – Include icons linked to your blog's social media profiles
(Faceblock, Tweety, Instadrama, etc.). This encourages visitors to follow your
adventures on other platforms. Utilize <a> tags for each social media link, and
you can use either text links, icons from a font library like FontAwesome, or
images for the icons. Remember to add alt attributes for accessibility if you're
using images.
• Contact Information – Provide a section within the footer for your contact
information, including an email address or a contact form link. This makes it
easier for readers to reach out with questions, collaborations, or feedback.
• Copyright Notice – Add a simple copyright notice stating the current year and
your blog's name, reinforcing the ownership and rights to the content on your
site. This can be a simple text like "© 2035 Global Adventures Blog."
• Design and Accessibility – Ensure that the footer is visually distinct from the
main content area. Keep accessibility in mind by ensuring that text contrast ratios
meet WCAG guidelines, and that any icons used are properly labeled with text
equivalents. For semantic clarity and structural organization within a footer, it
may be more appropriate to use <div> elements for grouping content rather
than <section> elements. The <footer> element itself is a semantic tag that
indicates the content is footer-specific, typically containing information like
copyright notices, links to privacy policies, terms of use, about us pages, and
contact information.
Hide
<footer>
<nav>
<ul>
<li><a href="/about.html">About Us</a></li>
<li><a href="/privacy-policy.html">Privacy
Policy</a></li>
<li><a href="/terms-of-use.html">Terms of
Use</a></li>
</ul>
</nav>
<div class="social-media">
<a href=" target="_blank" rel="noopener
noreferrer">Faceblock</a>
<a href=" target="_blank" rel="noopener
noreferrer">Tweety</a>
<a href=" target="_blank" rel="noopener
noreferrer">Instadrama</a>
</div>
<div class="contact-info">
<p>Contact us at: <a
href="mailto:[email protected]">contact@example-
globaladventuresblog.com</a></p>
</div>
<div class="copyright">
<p>© 2035 Global Adventures Blog. All rights
reserved.</p>
</div>
</footer>
Enhancing your website with small, yet impactful, elements like favicons and emojis can
significantly improve user experience and make your site stand out.
• Create Your Favicon – Use a graphic design tool to create a simple yet
memorable icon that represents your travel blog. This icon should be clear and
recognizable even at small sizes. Common dimensions for a favicon are 16x16
(standard favicon size, commonly used by most browsers), 32x32, or 48x48
pixels.
• Convert to .ico Format – For broad compatibility, save your favicon in
the .ico format. There are several online tools available that can convert your
image to a favicon .ico file.
• Add to Your Website – Place the .ico file in the root directory of your website.
Then, link to it within the <head> section of your HTML document.
• Choose Relevant Emojis – Select emojis that complement your content and
enhance the storytelling without overwhelming the text. For city descriptions,
consider using flags, landmarks, food items, or emotions.
• Insert into Your HTML – You can directly copy and paste emojis into your
HTML code. Place them in headings, paragraphs, captions, or even navigation
menus to attract attention and convey meaning at a glance.
• Accessibility Tip – When using emojis, remember to add descriptive text for
screen readers within aria-label attributes or similar techniques to ensure
your content is accessible to all users.
Hide
<!-- Adding a Favicon -->
<link rel="icon" href="path/to/favicon.ico" type="image/x-icon">
As you embark on this project, envision your blog as a bridge connecting the world's
cities with a community of curious and passionate travelers. Through your HTML
craftsmanship, you're not just building a website; you're weaving a tapestry of
experiences that celebrates the beauty of discovery and the bonds forged through
shared adventures. With each line of code, you're inviting readers to join you and your
friends on a journey of exploration, one city at a time.
This project not only tests your HTML skills but also encourages creativity in how you
present and structure content, making it a fitting culmination of the HTML Essentials
course.