0% found this document useful (0 votes)
9 views236 pages

10. Web Design1

This document is a comprehensive teaching module on web design and development, covering essential topics such as the fundamentals of the internet, HTML, CSS, and JavaScript. It aims to equip students with the necessary skills and knowledge for their exit exam and provides detailed explanations of web technologies, protocols, and the differences between the internet and the World Wide Web. The module includes learning objectives and practical exercises to enhance understanding and application of web development concepts.

Uploaded by

kemalahmed2015s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views236 pages

10. Web Design1

This document is a comprehensive teaching module on web design and development, covering essential topics such as the fundamentals of the internet, HTML, CSS, and JavaScript. It aims to equip students with the necessary skills and knowledge for their exit exam and provides detailed explanations of web technologies, protocols, and the differences between the internet and the World Wide Web. The module includes learning objectives and practical exercises to enhance understanding and application of web development concepts.

Uploaded by

kemalahmed2015s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 236

Internet and web design

Introduction

Welcome to the comprehensive web design and development teaching


module designed to equip you with the essential knowledge and skills needed
to ace your exit exam. This module serves as your roadmap for revising the
fundamentals of the internet and the web, as well as mastering the core
languages and technologies of web development: HTML, CSS, JavaScript,
and their related concepts. Whether you're gearing up for your exam or
simply looking to solidify your understanding of these crucial topics, this
module is your go-to resource for success.

Our journey begins with a thorough review of the internet and the web,
providing you with a clear understanding of how data is transmitted and
accessed across the vast network of interconnected devices. From the
underlying protocols that govern communication to the role of web servers
and browsers, you will gain insight into the infrastructure that powers the
digital landscape we navigate every day.

Next, we delve into the foundational language of web development: HTML


(Hypertext Markup Language). Through interactive lessons and practical
exercises, you will refresh your knowledge of HTML syntax, tags, and
elements, mastering the art of creating well-structured web documents that
lay the groundwork for engaging online experiences.

Tinsae D@2024 Internet and web design


Building upon your HTML expertise, we then explore the realm of CSS
(Cascading Style Sheets), the language responsible for styling and enhancing
the visual presentation of web pages. You will revisit CSS selectors,
properties, and values, honing your skills in creating aesthetically pleasing
layouts and designs that captivate users and convey your message effectively.

No web development curriculum would be complete without a deep dive into


JavaScript, the dynamic scripting language that powers interactivity and
functionality on the web. From basic scripting concepts to advanced DOM
manipulation techniques, you will sharpen your JavaScript skills and learn
how to create dynamic, responsive web experiences that delight users and
elevate your projects to the next level.

Learning Objectives

Based on this module students will be able to:


Fundamentals of Internet:
 Understand the foundational concepts of the internet, including its
infrastructure, protocols, and the role of web browsers and servers.
 Explain the process of data transmission over the internet and how
information is accessed and exchanged across networks.
HTML:
 Create well-structured web documents using HTML, incorporating
essential tags and elements to define the structure and content of web
pages.
 Apply HTML best practices to ensure document validity, accessibility,

Tinsae D@2024 Internet and web design


and compatibility across different browsers and devices.
CSS:
 Utilize CSS to style and enhance the visual presentation of web pages,
including the use of selectors, properties, and values to control layout,
typography, and color.
 Implement CSS techniques such as flexbox and grid to create
responsive and adaptive layouts that adjust seamlessly to various screen
sizes and devices.
JavaScript:
 Write JavaScript code to manipulate HTML elements dynamically,
responding to user interactions and events to create interactive web
experiences.
 Apply JavaScript principles to enhance website functionality, including
form validation, DOM manipulation, and asynchronous data loading,
to create engaging and responsive web applications.
Lesson 1: Fundamentals of Internet and the Web

1. Introduction

The Internet is a global network of interconnected computers and devices


that allows for the sharing and exchange of information. It provides a
communication infrastructure that enables usersto connect with each other
and access various services and resources. The internet is not only one
network. It consists of thousands of connected networks of varying sizes.
Networks connect computers and allow them to share files and
information. It is like a road in front of your house leading to the nearest
Tinsae D@2024 Internet and web design
town, then to the national highway and through highways to several other
places and cities in the country. Like the highways, electrical lines, water
supply lines or railway network, Internet connects countries and regions of
the earth to one another through networked computers and communication
lines.

The internet is a loose collection of academic, government, business and


individual networks linked around the world via many communication
channels. The word is coined from the phrase ‘interconnected networks.

No one person or organization runs the internet. Instead, the Internet


Society (ISOC), a private not for profit group, makes recommendations
guiding its growth. Many organizations connect their networks into the
internet to make this worldwide network possible. The Internet Society
decides the protocols or rules that make the internet work, such as the
Transmission Control Protocol (TCP) and Internet Protocol (IP).

The World Wide Web, often referred to as the Web, is a system of


interconnected hypertext documents and resources accessible via the
Internet. It provides a graphical interface for navigating and accessing
information, allowing users to browse websites and interact with web-
based applications. It has revolutionized the way we access and share
information, connect with others, and engage in various online activities.
The terms Internet and World Wide Web are used interchangeably in
nonprofessional terms they are not the same. It is common practice to say
"going on the Internet" whenever we open any web page on a browser.
However, the World WideWeb or the Web is one of the most popular

Tinsae D@2024 Internet and web design


Internet services available. The Web is a collection of interconnected
documents (web pages) and other web resources, linked by hyperlinks and
URLs.It uses HTTP as an underlying protocol for information transfer,
which is one of the several other protocols available in networking theory

1.1. What is the difference between internet and world wide web?

The internet serves as the expansive network connecting millions of


computers and devices worldwide, facilitating the exchange of data and
communication through a complex system of hardware, software, and
protocols. It forms the backbone for various online services and
technologies, including email, file sharing, instant messaging, and more,
extending far beyond the boundaries of the World Wide Web.

On the other hand, the World Wide Web (WWW) is a subset of the
internet, consisting of interconnected documents and resources accessed
through web browsers. Created by Tim Berners- Lee in 1989, the web
allows users to navigate between web pages via hyperlinks, accessing a
diverse range of content such as websites, web applications, multimedia,
and online services. While the internet provides the infrastructure, the
World Wide Web represents the interconnected ecosystem of information
and resources that has become integral to our digital lives.
1.2. Applications of the Internet

The Internet offers a wide range of services and applications that enable
users to perform various tasks.
 World Wide Web (WWW): The web as a collection of

Tinsae D@2024 Internet and web design


interconnected websites, web pages, and multimedia content
accessible through web browsers.
 Email: Electronic mail services that allow users to send and
receive messages and attachments across the Internet.
 Social Media: Platforms that enable users to connect, share, and
communicate with others, fostering online communities and user-
generated content.
 Online Streaming: Services for streaming audio, video, and
other multimedia content, such as music, movies, TV shows, and
live events.
 E-commerce: Online platforms for buying and selling goods and
services, facilitating electronic transactions and global
marketplaces.
 Cloud Computing: The delivery of computing resources,
including storage, servers, and software, over the Internet,
providing on-demand access and scalability.

1.3. How the World Wide Web Works

The Web works as per the internet's basic client-server format as shown in
the following image. The servers storeand transfer web pages or
information to user's computers on the network when requested by the
users. A web server is a software program which serves the web pages
requested by web users using a browser. The computer of a user who
requests documents from a server is known as a client. Browser, which is
installed on the user' computer, allows users to view the retrieved
Tinsae D@2024 Internet and web design
documents.

All the websites are stored in web servers. Just as someone lives on rent in
a house, a website occupies a space in a server and remains stored in it.
The server hosts the website whenever a user requests its Webpages, and
the website owner has to pay the hosting price for the same. The moment
you open the browser and type a URL in the address bar or search
something on Google,the WWW starts working. There are three main
technologies involved in transferring information(web pages) from servers
to clients (computers of users). These technologies include Hypertext
Markup Language (HTML), Hypertext Transfer Protocol (HTTP) and
Web browsers.
1.4. Web sites

A website is a collection of web pages and related content that are hosted
on a web server and can be accessed via the World Wide Web. It serves as
a virtual space where individuals, organizations, businesses, and other
entities can share information, showcase products or services,

Tinsae D@2024 Internet and web design


communicate with users, and engage in various online activities. Websites
are designed to be viewed using web browsers, and they can range from
simple single-page sites to complex multi-page portals. While Web pages
are documents written in HTML, which is a markup language that defines
the structure and layout of content on the page. HTML tags are used to
markup elements such as headings, paragraphs, images, links, and more.
1.5. Internet Protocols
Internet protocols are a set of rules and standards that dictate how data is
transmitted and communicated across networks within the internet
infrastructure. These protocols ensure that devices, computers, and servers
can communicate effectively and reliably, regardless of their location or the
underlying technology used. Without these protocols, the seamless exchange
of information that defines the internet would not be possible. Some of the
common internet protocols are:
1.5.1.Transmission Control Protocol (TCP):
TCP is a connection-oriented protocol responsible for ensuring reliable and
ordered delivery of data packets between devices on a network. It breaks data
into smaller segments, assigns sequence numbers to each segment for
reassembly, and includes error checking to guarantee data integrity.
1.5.2.Internet Protocol (IP):
IP is a fundamental protocol responsible for addressing and routing data
packets between devices on the internet. It assigns unique IP addresses to
devices and determines the best path for data packets to reach their
destination across interconnected networks.
1.5.3.Hypertext Transfer Protocol (HTTP):
Tinsae D@2024 Internet and web design
HTTP is the protocol used for transmitting hypertext documents, such as web
pages, between web servers and clients (e.g., web browsers). It operates over
TCP and defines how requests and responses are formatted and transmitted,
enabling users to access and interact with web content.
1.5.4.Hypertext Transfer Protocol Secure (HTTPS):
HTTPS is the secure version of HTTP, providing encrypted communication
between web servers and clients. It uses SSL/TLS encryption to protect
sensitive data, such as login credentials and payment information, from
interception and eavesdropping.
1.5.5.File Transfer Protocol (FTP):
FTP is a protocol used for transferring files between computers over a
network, typically the internet. It enables users to upload, download, and
manage files on remote servers, providing authentication and data transfer
functionalities.
1.5.6.Simple Mail Transfer Protocol (SMTP):
SMTP is the standard protocol for sending email messages between email
servers. It defines how email messages are formatted, relayed, and delivered,
ensuring reliable communication between mail servers.
1.6.7. Domain Name System (DNS):
DNS translates domain names (e.g., www.example.com) into IP addresses
(e.g., 192.0.2.1) that computers use to identify each other on the internet. It
acts as a distributed database, mapping human- readable domain names to
numerical IP addresses and facilitating the resolution of domain names to IP
addresses.
1.6.8. Post Office Protocol (POP) / Internet Message Access Protocol
Tinsae D@2024 Internet and web design
(IMAP):
POP and IMAP are protocols used by email clients to retrieve email
messages from mail servers. POP downloads emails to the client's device
and typically deletes them from the server, while IMAP syncs emails
between the server and multiple client devices, allowing users to access their
emails from anywhere.
1.6. HTTP vs HTTPs

HTTP (Hypertext Transfer Protocol) and HTTPS (Hypertext Transfer


Protocol Secure) are both protocols used for communication between
clients (such as web browsers) and servers (web servers). However, they
differ in terms of security mechanisms and the way data is transmitted.
Here are the main differences between HTTP and HTTPS:

i. Security

HTTP: HTTP does not provide any built-in security measures. Data
transmitted over HTTP is sent in plain text, making it vulnerable to
interception and eavesdropping. It does not offer data encryption or
protection against tampering.

HTTPS: HTTPS incorporates SSL (Secure Sockets Layer) or TLS


(Transport Layer Security) protocols to establish an encrypted connection
between the client and server. This encryption ensures that data transmitted
over HTTPS is encrypted, making it significantly more secure. It protects
against eavesdropping, tampering, and interception of sensitive
information.

Tinsae D@2024 Internet and web design


ii. Encryption

HTTP: Data transmitted over HTTP is not encrypted. It is sent as plain


text, which means anyone with access to the network can potentially
intercept and view the data.

HTTPS: HTTPS encrypts the data being transmitted between the client
and server. The encryption process ensures that the data is converted into
a secure format that can only be decrypted by the intended recipient (the
server). This protects the confidentiality and integrity of the data.

iii. Data Integrity


HTTP: Since data transmitted over HTTP is not encrypted, it is susceptible
to modification during transit. Attackers can intercept the data and alter its
contents without detection.

HTTPS: HTTPS ensures data integrity by using cryptographic


mechanisms. It verifies that the data received by the client is the same as
the data sent by the server. If any modification or tampering occurs during
transit, the integrity check will fail, and the connection will be terminated.

iv. Authentication and Trust

Tinsae D@2024 Internet and web design


HTTP: HTTP does not provide any built-in mechanisms for server
authentication or establishing trust. As a result, it is susceptible to man-in-
the-middle attacks where attackers can impersonate the server or intercept
and modify the communication.

HTTPS: HTTPS employs digital certificates issued by trusted Certificate


Authorities (CAs) to authenticate the identity of the server. This ensures that
the client is communicating with the intended and legitimate server,
reducing the risk of phishing attacks and unauthorized access.

v. URL Scheme
HTTP: URLs for HTTP resources start with "http://" in the address bar of web
browsers.
HTTPS: URLs for HTTPS resources start with "https://" in the address bar.
The presence of "https://" indicates that the connection is secure, and the
data transmitted between the client and server is encrypted.

In summary, while HTTP is a standard protocol for web communication, it


lacks security measures such as encryption and authentication. In contrast,
HTTPS provides secure communication by encrypting data, verifying
server authenticity, and ensuring data integrity. HTTPS is essential for
protecting sensitive information, maintaining user privacy, and establishing
trust in online interactions.

1.7. Domain Name System (DNS)

Tinsae D@2024 Internet and web design


The Domain Name System (DNS) is a hierarchical naming system that
translates domain names into IP addresses. The Domain Name System
(DNS) operates in a hierarchical structure, which plays a vital role in
translating human-readable domain names into IP addresses that computers
can understand. This hierarchical nature allows for efficient and
decentralized management of domain names across the Internet. The
Domain Name System (DNS) can be thought of as the directory of the
Internet. We find an online page or website by typing in the URL – like
acme.comor some-site.com. Our web browsers, on the other hand, need to
translate the URL to Internet Protocol (IP) addresses to find the correct site.
It is a DNS that translates domain names to IP addresses so our browsers can
resolve, or connect to, requested Internet resources.
Every single device on the Internet has a unique IP address by which it can
be uniquely identifiedby the other online devices. A DNS server eliminates
the need for us to memorize these IP addresses every time we want to visit
a site or connect to a device. It is much easier for us to typein a URL than
IPv4 IP addresses (E.g. 192.168.1.1) or, worse, the more complex IPv6
addresses (E.g. 2400:cb00:2048:1::c629:d7a2).
The DNS architecture consists of a hierarchical and decentralized name
resolution system for computers, services or any other resources connected
to the Internet or a private network. It storesthe various associated
information of the domain names assigned to each of the resources.
Queriesfor a resource pass through the DNS – with the URLs as parameters.
The DNS then takes the URLs, translates them into the target IP addresses,
Tinsae D@2024 Internet and web design
and sends the queries towards the correct resource.

How does DNS work?

Let’s delve deeper and see more details on how DNS works. The first thing
we need to know is that there isn’t a single DNS, but a selection of them,
that can help resolve a single IP address.
A computer has its own cache of DNS data – a local IP-address-to-URL
matching – that it uses for quick references. But, it can’t store all the
information for every website or device out there; hence,the need for root,
recursive, Top Level, Second Level, and authoritative DNS servers.
When a user asks to go to a website, the browser first checks the local DNS
cache for the correct resolution (from URL to IP address) and, if not found,
goes:
 Out to the recursive DNS server – which is normally operated
by the local ISP provider

– to check which root DNS server it needs to go to find an answer.


Once the address is found, it is escalated to…
 One of the root DNS servers out there – which are run by
about 13 independent organizations – to find the address of the
correct Top Level DNS (TLD) server to query forthe address
depending on whether it is a “.com”, “.org” or “.net” site, for
example. Root

Tinsae D@2024 Internet and web design


DNS sit at the top of the DNS hierarchy. It should be noted here that
every website addressor URL has an implied “.” at the end, even if we
don’t type it in. This “.” designates (or points to) the DNS root
nameservers at the top of the DNS hierarchy where it can find
information about the correct TLD server to head on to.
 At the TLD server – of which there are about 1000 spread across the
globe – the query is pointed towards the correct authoritative DNS
where the required information (IP address) is actually stored.
 And, at the authoritative DNS server – which holds a broad range of
IP address information – the corresponding IP is sent back to the
recursive DNS, which forwards it tothe client machine and the user
(you) can go on to the website.
Every time a query is made, the IP address to URL mapping is cached in
every DNS for the next user instead of having to go back and search for the
information every single time. This helps in keeping the servers
synchronized and updated and results in faster response times.

DNS hierarchy

The DNS hierarchy, also called the domain name space, is an inverted tree
structure. The DNS hierarchy tree has a single domain at the top of the
structure called the root domain – indicated bythe “.” as we have mentioned
above. Below the root domain are the top-level domains that dividethe DNS
hierarchy into segments containing second-level domains, sub-domains,
and hosts.

Tinsae D@2024 Internet and web design


Hence, the DNS hierarchy is comprised of the following five levels: Root
Level Domain, Top Level Domains (TLD), Second Level Domains (SLD),
Subdomains and Hosts.

Within the hierarchy, the resolution process starts at the Root Level DNS,
the Top Level DNS, working its way down to the Second Level DNS, then
through any number of sub-domains until we get to the actual hostname we
want to resolve into an IP address. Let’s have a look at each component
individually to see
1.8. Web browser

A web browser is a software application that allows users to access and


navigate the World Wide Web (WWW). It enables the retrieval and display
of web pages, files, images, videos, and other online content. Web browsers
act as a user interface for accessing and interacting with the vast amount of
Tinsae D@2024 Internet and web design
information available on the internet. Web browsers play a crucial role in
enabling usersto access and interact with the vast array of information and
services available on the internet. Understanding their features and settings
empowers users to customize their browsing experienceand maximize
productivity while ensuring security and privacy.

1.8.1.Popular Web Browsers

 Google Chrome: Developed by Google, known for its speed,


security, and extensive features.

 Mozilla Firefox: An open-source browser known for


its privacy features,
customization options, and developer tools.

 Safari: Developed by Apple, Safari is the default browser for


Apple devices, offeringa seamless integration with the macOS and
iOS ecosystems.

 Microsoft Edge: Microsoft's web browser, built on


Chromium, offering fast performance, compatibility, and
integration with Windows systems.

 Opera: A feature-rich browser known for its speed, built-in VPN,


ad blocker, and unique features like sidebar extensions.

Tinsae D@2024 Internet and web design


Summary question for Lesson 1

1. What is the fundamental difference between the Internet and the World Wide Web?
2. How does a web browser work, and what are the key components involved in rendering a
webpage?
3. Describe the role of HTTP and HTTPS protocols in web communication. How do they differ?
4. What is DNS (Domain Name System), and how does it facilitate internet browsing?
5. What are cookies in the context of web browsing, and how are they used by websites?
6. Explain the significance of TCP/IP in internet communication. How does it ensure data
transmission reliability?
7. Describe the difference between client-side scripting and server-side scripting. Provide examples
of each.
8. How do search engines like Google index and rank web pages?
9. What are some common security threats associated with browsing the internet, and what
measures can users take to protect themselves from these threats?
10. Can you explain the concept of IPv6 and its significance in the context of internet addressing?

Lesson 2: HTML
2.1.Introduction to HTML
HyperText Markup Language, commonly referred to as HTML, is the
standard markup languageused to create web pages. Web browsers can
read HTML files and render them into visibleor audible web pages. HTML
describes the structure of a website semantically along with cues for
presentation, making it a markup language, rather than a programming
language. HTML, an acronym for Hyper Text Markup Language, specifies
how the structure of a webpage will be withthe help of various markups. It
is a structured markup language that is used to create Web pages. Markup
languages like HTML bundle together codes which are elements that are used
to representthe structure and format of a document. A user agent, usually a
Web browser which renders (delivers) the document, interprets the meaning
of these codes to decipher (making it into simplerhuman readable text) how
to structure or display a document. The HTML elements are made up of
Tinsae D@2024 Internet and web design
alphanumeric tokens surrounded by angle brackets, for example, <B>,
<HTML>, <IMG> and <HR> .

Almost all elements possess a pair of tags i.e. a start tag and an end tag. The
start tag is a mnemonic symbol for the element enclosed in ‘<’ ’>’, also
known as angle brackets, for instance, the symbol associated with bolding
text is B and the start tag for this purpose is <B>. An end tag is the same as
that for a start tag, but with an exception that there exists a forward slash
preceding the text symbol of start tag: </B>. The instruction applied by an
element modifies whatever content is present between the starting and
ending tags:

This is an example of a simple HTML document.


Example:

<! DOCTYPE html>

<html>

<head>

<title>Page Title</title>

</head>

<body>

<h1>It is the First Heading</h1>


Tinsae D@2024 Internet and web design
<p>It is the first paragraph. </p>

</body>

</html>

Output:

2.1. Different Versions of HTML

HTML (Hypertext Markup Language) has been the cornerstone of web


development since its inception in the early 1990s. As the primary language for
creating web pages and applications, HTML has undergone several revisions and
updates to meet the evolving needs of developers and users alike. Each version of
HTML has brought new features, capabilities, and standards, shaping the way we
interact with the web.

HTML 1.0:
HTML 1.0, introduced in 1993 by Tim Berners-Lee, marked the first standardized
version of HTML. It provided a basic set of markup tags for structuring and

Tinsae D@2024 Internet and web design


formatting hypertext documents, laying the groundwork for the World Wide Web
as we know it today.

HTML 2.0:
HTML 2.0, released in 1995, expanded upon the foundation established by HTML
1.0. It introduced support for forms, allowing users to interact with web pages
through text fields, checkboxes, and buttons, paving the way for more dynamic and
interactive web experiences.
HTML 3.2:
HTML 3.2, introduced in 1997, further extended the capabilities of HTML,
introducing support for tables, frames, and multimedia elements such as images,
audio, and video. These new features enabled developers to create more complex
layouts and incorporate multimedia content into their web pages.
HTML 4.01:
HTML 4.01, released in 1999, represented a major update to the HTML
specification. It introduced stricter rules and improved support for scripting and
styling, standardizing the Document Object Model (DOM) and introducing support
for cascading style sheets (CSS), allowing for more precise control over document
layout and presentation.
XHTML (Extensible Hypertext Markup Language):
XHTML emerged as a reformulation of HTML as an application of XML, designed
to be more compatible with XML-based technologies and standards. XHTML 1.0,
released in 2000, introduced stricter syntax rules and required documents to be
well-formed XML, helping to improve consistency and interoperability across
Tinsae D@2024 Internet and web design
different platforms and devices.
HTML5:
HTML5, introduced in 2014, represents the latest evolution of the HTML
specification. It introduces new semantic elements, APIs, and multimedia
capabilities, providing native support for audio and video playback, offline storage,
geolocation, canvas drawing, and responsive design. HTML5 is well-suited for
building modern web applications and multimedia-rich websites, reflecting the
ever-changing landscape of web development and the increasing demands of users
and developers alike.
2.2. HTML Elements, Tags and Attributes
While getting started with HTML, you will likely encounter new—and often
strange— terms. Over time you will become more and more familiar with all of
them, but the three common HTML terms you should begin with are elements,
tags, and attributes.

2.2.1. Elements

Before we start adding tags to our document, let’s look at the anatomy of an
HTML element (its syntax) and firm up some important terminology. HTML
elements are the building blocks of webpages. They define the structure and
content of a webpage by encapsulating different parts of the page within specific
tags. Each HTML element consists of an opening tag, content, and a closingtag.
The opening tag denotes the start of an element, the closing tag marks its end, and
the contentlies between the tags. Elements can be nested within each other,
creating a hierarchical structure that represents the relationship between different

Tinsae D@2024 Internet and web design


parts of the webpage.
Here's an example of an HTML element: Thus, an element will look like the
following:

Figure 2-2 The parts of an HTML container element.


2.2.2. Tags

An HTML tag is a component of HTML markup that is used to define elements


within an HTML document. HTML tags are enclosed within angle brackets ("<"
and ">") and consist of the tag name. They provide instructions to web browsers
on how to interpret and render the content with in the tags. Here's an example of
an HTML tag:

<p>This is a paragraph tag.</p>

HTML tags can be categorized into different types based on their purpose and
the behavior they define for the elements. Not all elements have content,
however. Some are empty by definition, such as the img element used to add an
image to the page.
Tinsae D@2024 Internet and web design
In HTML, the capitalization of element names is not important. So <img>,
<Img>, and <IMG> are all the same as far as the browser is concerned. However,
in XHTML (the stricter version of HTML) all element names must be all
lowercase in order to be valid. Many web developers havecome to like the
orderliness of the stricter XHTML markup rules and stick with all lowercase.

2.2.3. Attributes

HTML elements can also have attributes that provide additional information or
modify their behavior. Attributes are properties used to provide additional
information about an element. The most common attributes include the id
attribute, which identifies an element; the class attribute, which classifies an
element; the src attribute, which specifies a source for embeddable content; and
the href attribute, which provides a hyperlink reference to a linked resource.
Attributes are defined within the opening tag, after an element’s name. Generally
attributes includea name and a value. The format for these attributes consists of
the attribute name followed by an equals sign and then a quoted attribute value.
The syntax for an attribute is
as follows:
attributename="value"
Attributes go after the element name, separated by a space. In non-empty

<element attributename="value">

<element attributename="value">Content</element>

elements, attributes goin the opening tag only:

Tinsae D@2024 Internet and web design


You can also put more than one attribute in an element in any order. Just
spaces: keep them separatedwith

<element attribute1="value" attribute2="value">

Tinsae D@2024 Internet and web design


An Element with Attributes
What are the different types of HTML
Attributes?

There are three types of HTML attributes:

A. Core Attributes

B. Internationalization Attributes

C. Generic Attributes

A. HTML Core Attributes

The most widely used attribute is core attributes. There are 4 types of core
attributes:

 Id

 Class

 Title
Tinsae D@2024 Internet and web design
 Style

The Id Attribute:

This is the most widely used attribute. The id attribute is used to give a unique
id to an HTMLelement. Each element in HTML with an id attribute has its
own unique identity, just as each of us has our own unique identity. Multiple
elements can’t share the same id.
For example:

<p id= "html"> This is HTML tutorial </p>

<p id= “python”> This is Python tutorial </p>

In the above example, it is easy to distinguish the two paragraphs with the
name- id attributehaving two different values i.e. html and python.
The class Attribute:

The class attribute is used to specify a class to an HTML element. It is not


unique like the id attribute. Multiple elements can share the same class. It is
used to associate an element with astylesheet, JS.
The title Attribute:

The id attribute is used to give a title to an HTML element. When the HTML
element isloading, a tooltip of the cursor comes and shows the written title.
For example:

Tinsae D@2024 Internet and web design


<h4 title= “hello, motto”> TITLE ATTRIBUTE</p>

The style Attribute:

The style attribute is used to give styling to an HTML element. It is a property


of CSS (Cascading Style Sheet). It is mainly used by the CSS. It is the inline
property of an element.In CSS, if we want to style within an HTML element
we use the style attribute in inline of anHTML element.

B. HTML Internationalization Attributes

There are three types of internationalization attributes i.e. dir, lang, xml:lang

The dir Attribute:

The dir attribute tells the browser in which direction should the text flow.
There are twotypes of dir attributes:
ltr: Left to rightrtl: Right to left

Tinsae D@2024 Internet and web design


The lang Attribute:

This attribute is replaced by xml:lang attribute. Earlier it was used to


indicate thelanguage for the web page.
The xml:lang Attribute:

Value for the xml:lang should be ISO-639 country code.

C. HTML Generic Attributes

Generic attributes include various attributes which are mostly used. Some
common genericattributes are:
The “align” Attribute:

align attribute uses align name for HTML element and uses left, right, and
center values toindicate the text accordingly. It is used for horizontal aligns
tags.
The “valign” Attribute:

valign attribute uses valign name for HTML element and uses top, middle, and
bottom valuesto indicate the text accordingly. It is used for vertical aligns tags.
The “bgcolor” Attribute:

bgcolor attribute uses bgcolor name to HTML element and uses numeric,
hexadecimal, RGBcode values to change the element's background color
accordingly.
The “width” Attribute:

Tinsae D@2024 Internet and web design


The width attribute uses the width name of the HTML element and uses
numeric values tochange the element’s width according to the numeric given.
The “height” Attribute:

The height attribute uses the height name of the HTML element and uses
numeric values tochange the element’s height according to the numeric given.
The “src” Attribute:

The src attribute is mostly used by the img element that we’ll be going to
discuss later. Thissrc attribute specifies the URL path to that element that is to
be displayed. We can choose any of the two paths:
1. Absolute URL - Links to an external image that is hosted on another
website.

Example: src="https://www.w3schools.com/images/img_girl.jpg".
Notes: External images might be under copyright. If you do not get
permission to use it,you may be in violation of copyright laws. In addition,
you cannot control external images; it can suddenly be removed or
changed.
2. Relative URL - Links to an image that is hosted within the website.
Here, the URL does not include the domain name. If the URL begins
without a slash, it will be relativeto the current page. Example:
src="img_girl.jpg". If the URL begins with a slash, it will be relative to
thedomain. Example: src="/images/img_girl.jpg".

The “alt” Attribute:

Tinsae D@2024 Internet and web design


The alt attribute is mostly used by the img element. This alt attribute specifies
the alternate text to that image that is to be displayed. For some issues, if that
image is not visible then alttext helps to tell us about the description of that
image.

2.2.4. Block and In-line level HTML elements

When working with HTML, it's essential to understand the distinction between
block-level elements and inline-level elements. These two types of elements play
a crucial role in structuringand formatting the content of a web page. In this
article, we will explore the characteristics, behaviors, and use cases of block and
inline-level elements in HTML.

1. Block-Level Elements:

Block-level elements are HTML elements that create a block-level box. These
elements typicallystart on a new line and occupy the full width available within
their parent container. Some common examples of block-level elements include
<div>, <p>, <h1> to <h6>, <ul>, <li>, and
<section>.
Key characteristics of block-level elements:
 Start on a new line: Block-level elements create a line break before and
after themselves,visually separating them from other content.

 Occupy the full width: By default, block-level elements extend


horizontally to fill theentire width of their parent container.

Tinsae D@2024 Internet and web design


 Support width and height properties: You can specify custom
dimensions for block-levelelements using CSS properties such as width
and height.

 Allow nesting of other elements: Block-level elements can contain


other block-levelelements as well as inline-level elements.

Common use cases for block-level elements:

 Grouping and organizing content: <div> and <section> elements are


commonly used asstructural containers to group and organize related
content.

 Paragraphs and headings: <p> elements for paragraphs and <h1> to


<h6> elements forheadings are examples of block-level elements used for
text content.

 Creating lists: <ul> and <ol> elements, along with their list items <li>,
are block-levelelements used to create unordered and ordered lists.

2. Inline-Level Elements:

Inline-level elements, as the name suggests, are HTML elements that do not
create line breaks and are contained within a line of text or other inline
elements. Examples of inline-level elementsinclude <span>,
<a>, <strong>, <em>, <img>, and <input>.

Key characteristics of inline-level elements:

 Do not start on a new line: Inline-level elements do not force a line


Tinsae D@2024 Internet and web design
break and are renderedwithin the same line as surrounding text or other
inline elements.

 Occupy only necessary space: Inline-level elements take up only as


much space asrequired by their content, without extending to the full
width of the parent container.

 Do not support width and height properties: Inline-level elements do


not accept explicitwidth or height values. Their dimensions are
determined by their content.

 Inline-level elements cannot contain block-level elements but can


contain other inline-level elements.

Common use cases for inline-level elements:

 Styling specific portions of text: <span>, <strong>, <em>, and similar


inline elements arecommonly used for applying styling, such as color,
font weight, or emphasis, to specific portions of text.

Tinsae D@2024 Internet and web design


 Creating hyperlinks: The <a> element is used to create hyperlinks that
allow users tonavigate to other web pages or different sections within the
same page.

 Inserting images: The <img> element is used to insert images into a web
page. Althoughit is an inline-level element, it may affect the flow of
surrounding text.

Understanding the distinction between block-level elements and inline-level


elements is essentialfor proper HTML structure and styling. It enables you to
organize and format your content effectively, ensuring a visually pleasing and
semantically meaningful web page layout.

In conclusion, block-level elements create block-level boxes, start on new lines,


and occupy thefull width of their parent containers. They are suitable for
grouping content and creating structural sections. On the other hand, inline-level
elements do not create line breaks, occupy only necessary space, and are
typically used for applying styling or inserting specific elements within text. By
leveraging the characteristics and appropriate use of these elements, you can
create well-structured and visually appealing web pages.

2.3. Basic Document structure of an HTML document

Now that you know what HTML elements, tags, and attributes are, let’s take a
look at putting together our first web page. If anything looks new here, no
worries—we’ll decipher it as we go.

Tinsae D@2024 Internet and web design


Figure 2-4 shows the recommended minimal skeleton of an HTML5 document.
I say “recommended” because the only element that is required in HTML is the
title. But I feel it is better, particularly for beginners, to explicitly organize
documents with the proper structural markup. And if you are writing in the stricter
XHTML, all of the following elements except metamust be included in order to
be valid. Let’s take a look at what’s going on in Figure 2-4.

1. I don’t want to confuse things, but the first line in the example isn’t an element
at all; it is a document type declaration (also called DOCTYPE declaration)
that identifies this document as an HTML5 document. I have a lot more to say
about DOCTYPE declarations in Chapter 10,but for this discussion, suffice it
to say that including it lets modern browsers know they shouldinterpret the
document as written according to the HTML5 specification.
2. The entire document is contained within an html element. The html element is
called the root element because it contains all the elements in the document,
and it may not be contained within any other element. It is used for both
HTML and XHTML documents.

3. Within the html element, the document is divided into a head and a body. The
head element contains descriptive information about the document itself, such
as its title, the style sheet(s) ituses, scripts, and other types of “meta”
information.
4. The Meta elements within the head element provide information about the
document itself. A Meta element can be used to provide all sorts of
information, but in this case, it specifies the character encoding (the
Tinsae D@2024 Internet and web design
standardized collection of letters, numbers, and symbols) used in the
document. I don’t want to go into too much detail on this right now, but know
that there are many good reasons for specifying the charset in every document,
so I have included it as part of the minimal document structure.
5. Also in the head is the mandatory title element. According to the HTML
specification, every document must contain a descriptive title.
6. Finally, the body element contains everything that we want to show up in the
browser window.

Figure 2-4The Basic structure of an HTML document.

Tinsae D@2024 Internet and web design


2.3.2 Meta tags and their importance

Meta tags are a fundamental component of HTML that play a crucial role in
improving a website's visibility, accessibility, and overall performance. These
small snippets of code provide valuable information about a web page to search
engines, social media platforms, and browsers. In this section, we will explore
the importance of Meta tags in HTML and how they contribute to the success of
your website.

What Are Meta Tags?


Meta tags are HTML elements placed within the head section of a web page.
They serve as metadata, providing information about the page to various entities,
including search engines and social media platforms. While users typically do
not see Meta tags directly, they play a significantrole behind the scenes in shaping
how your website is displayed and understood by different systems. One of the
primary benefits of Meta tags are

1. Improving Search Engine Optimization (SEO):

One of the primary benefits of Meta tags is their impact on search engine
optimization. Search engines use Meta tags to understand the content and
relevance of a web page, which influences itsranking in search results. Some key
meta tags for SEO include:

 <title> tag: Defines the title of the web page. It appears in search engine
results and browsertabs as the clickable headline.

 <meta name="description" content="..."> tag: Provides a concise


Tinsae D@2024 Internet and web design
description of the page's content. It appears in search engine results
below the title, influencing users to clickon the link.

 <meta name="keywords" content="..."> tag: Specifies relevant


keywords related to thepage's content, helping search engines understand
the page's relevance to specific search queries.

 <meta name="robots" content="..."> tag: Instructs search engine


crawlers on how to interact with and index the page. It can specify
whether to index the page, follow links, orset page restrictions.
By optimizing these meta tags with relevant and accurate information, you can
improve your website's visibility in search engine results and attract more
organic traffic.

2. Enhancing Social Media Sharing:

Meta tags also play a crucial role in how your website is shared and displayed on
social media platforms. When someone shares a web page on platforms like
Facebook or Twitter, Meta tags provide the necessary information to populate
the post with relevant content. Some key Meta tagsfor social media sharing
include:

 <meta property="og:title" content="..."> tag: Specifies the title of the


page when sharedon social media platforms.

 <meta property="og:description" content="..."> tag: Provides a


description of the page'scontent when shared on social media.

 <meta property="og:image" content="..."> tag: Specifies an image to


Tinsae D@2024 Internet and web design
be displayedalongside the shared link on social media platforms.

By including these meta tags, you can control how your website appears when
shared on socialmedia, ensuring a consistent and appealing representation that
attracts users' attention.

3. Improving Website Accessibility:

Meta tags also contribute to improving the accessibility of your website. They
provide additional information to assistive technologies like screen readers,
enabling them to accurately interpret andpresent the content to users with
disabilities. For example:

 <meta name="viewport" content="width=device-width, initial-


scale=1.0"> tag: Specifies the viewport settings for responsive web
design, ensuring optimal display on different devices.

 <meta name="theme-color" content="#ffffff"> tag: Sets the theme


color for the website,allowing browsers to customize the user interface
based on the specified color.

By including these meta tags, you enhance the accessibility and usability of your
website, makingit more inclusive for all users.

Tinsae D@2024 Internet and web design


In conclusion, meta tags are integral to the success of your website. By utilizing
the appropriate meta tags, you can optimize your website for search engines,
enhance social media sharing, and improve accessibility. Investing time and
effort into crafting effective meta tags will positively impact your website's
visibility, user engagement, and overall performance on the web. Rememberto
keep your meta tags accurate, concise, and relevant to maximize their
effectiveness.
2.4. HTML Text basic tags
2.4.1. Heading Tags

HTML headings are titles or subtitles that you want to display on a webpage.
HTML also has six levels of headings, which use the elements <h1>, <h2>,
<h3>, <h4>, <h5>, and <h6>. Search engines use the headings to index the
structure and content of your web pages. Users often skim apage by its headings.
It is important to use headings to show the document structure. <h1>
headingsshould be used for main headings, followed by <h2> headings, then the
less important <h3>, andso on. While displaying any heading, browser adds one
line before and one line after that heading.

Example

Tinsae D@2024 Internet and web design


<!DOCTYPE html>
<html>
<head>
<title>Heading Example</title>
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>

Tinsae D@2024 Internet and web design


This will produce the following result:

2.4.2. Paragraph Tag

A paragraph always starts on a new line, and is usually a block of text. The
HTML <p> element defines a paragraph. A paragraph always starts on a new
line, and browsers automatically add some white space (a margin) before and
after a paragraph. Paragraphs are widely used for varioustypes of textual content,
such as articles, descriptions, and explanations. You can add attributes tothe <p>
element to provide additional information or control its appearance. Each
paragraph of text should go in between an opening <p> and a closing </p> tag.
Here's an example of a basic paragraph without any attributes::

Example

Tinsae D@2024 Internet and web design


<!DOCTYPE html>
<html>
<head>
<title>Paragraph Example</title>
</head>
<body>
<p>Here is a first paragraph of text.</p>

Tinsae D@2024 Internet and web design


<p>Here is a third paragraph of text.</p>
</body>
</html>

This will produce the following result:

Now let's explore some commonly used attributes with examples:


Class Attribute (class): Used to define a class for the paragraph, allowing you
to apply CSS stylesor target it with JavaScript.

<p class="important">This is an important paragraph.</p>

ID Attribute (id): Provides a unique identifier for the paragraph, which


can be used to refer to it from CSS or JavaScript.

Style Attribute (style): Allows you to apply inline CSS styles directly to the
paragraph. Here's anexample of changing the font color and size:

<p id="intro">This is the introduction paragraph.</p>


<p style="color: red; font-size: 18px;">This paragraph has custo
m styles applied.</p>

Tinsae D@2024 Internet and web design


2.4.3. Horizontal Line Tag

In HTML, the horizontal line tag is represented by the <hr> element. It is used
to create a horizontal line or separator on a webpage. The <hr> tag is a self-
closing tag, meaning it doesn't require a closing tag. Here's an example of a basic
horizontal line:
Example

<!DOCTYPE html>
<html>
<head>
<title>Horizontal Line Example</title>
</head>
<body>
<p>This is paragraph one and should be on top</p>
<hr />
<p>This is paragraph two and should be at bottom</p>
</body>
</html>

This will produce the following result:

You can also add attributes to the <hr> element to modify its appearance or
behavior. Here aresome commonly used attributes with examples:
Tinsae D@2024 Internet and web design
Width Attribute (width): Specifies the width of the horizontal line. It can be
set in pixels (px) oras a percentage of the container width.

<hr width="50%">

Size Attribute (size): Sets the height or thickness of the horizontal


line. The value can be a numeric value or one of the predefined size
values: small, medium, or large.

<hr size="3">

Align Attribute (align): Determines the alignment of the horizontal line within its
container. Thepossible values are left, center, right, or justify.

<hr align="center">

Line Break Tag

In HTML, the line break is represented by the <br> element. It is a self-closing


tag, meaning it doesn't require a closing tag. The <br> element is used to insert a
line break within a block of textor content, forcing the text after it to start on a
new line. Here's an example of a basic line break: Example:

Tinsae D@2024 Internet and web design


<!DOCTYPE html>
<html>
<head>
<title>Line Break Example</title>
</head>
<body>
<p>Hello<br />
You delivered your assignment on time.<br />
Thanks<br />
Miskir</p>
</body>
</html>

This will produce the following result:

2.4.4. Preserve Formatting Tag

The <pre> tag stands for "preformatted text" and is used to display text exactly
as it is written, preserving all formatting, including spaces, line breaks, and
indentation. It is commonly used todisplay code snippets, poetry, or any content
that requires precise formatting. Here's an exampleof using the <pre> tag to
preserve formatting:

Example:

Tinsae D@2024 Internet and web design


<!DOCTYPE html>
<html>
<head>
<title>Line Break Example</title>
</head>
<body>
<p>Hello<br />
You delivered your assignment on time.<br />
Thanks<br />
Miskir</p>
</body>
</html>

This will produce the following result:

Tinsae D@2024 Internet and web design


2.5. HTML Basic Text Formatting and color
2.5.1. HTML – Formatting Elements

In HTML, there are several formatting elements that you can use to apply
specific styles or formatting to your content. These elements help structure and
present your text in a visually appealing and meaningful way. Here are some
commonly used formatting elements in HTML:

A. Bold (<b> or <strong>):

The <b> element and its semantic counterpart <strong> are used to make text
appear in a bold orstronger font weight.

Code snip Result

<b>This text is bold.</b>

<strong>This text is also bold.</strong>

B. Italic (<i> or <em>):

The <i> element and its semantic counterpart <em> are used to make text appear
in an italicizedor emphasized style.

Code snip Result

Tinsae D@2024 Internet and web design


<i>This text is italicized.</i>

<em>This text is also emphasized.</em>

C. Underline (<u>):

The <u> element is used to underline text.


Code snip Result
<u>This text is underlined.</u>

D. Strikethrough (<s> or <del>):

The <s> element and its semantic counterpart <del> are used to display text with
a strikethroughor line through it.

Tinsae D@2024 Internet and web design


Code snip Result
<s>This text has a strikethrough.</s>

<del>This text is also deleted.</del>

E. Superscript (<sup>):
The <sup> element is used to display text as a superscript, typically for indicating
footnotes,mathematical exponents, or citations.

Code snip Result


E = mc<sup>2</sup>

F. Subscript (<sub>):

The <sub> element is used to display text as a subscript, typically for chemical
formulas,mathematical subscripts, or annotations.

Code snip Result


H<sub>2</sub>O

G. Code (<code>):

The <code> element is used to represent a fragment of computer code or inline

Tinsae D@2024 Internet and web design


code snippets.

Code snip Result


Use the <code>print()</code> f

unction to display output.


These formatting elements help convey visual cues or semantic meaning to the
text within your HTML documents. It's important to note that the use of semantic
elements (<strong>, <em>, <del>,etc.) is preferred over non-semantic elements
(<b>, <i>, <s>, etc.) as they provide additional meaning to assistive technologies
and search engines. However, both options are valid and can beused based on
your specific requirements.

2.5.2. HTML Quotation and Citation Elements

In HTML, there are specific elements designed for marking up quotations and
citations. These elements provide semantic meaning to the quoted or cited
content, allowing browsers, search engines, and assistive technologies to
interpret and present the information correctly. Here are thequotation and citation
elements in HTML:

A. Blockquote (<blockquote>):

The <blockquote> element is used to indicate a longer quotation that is


separate from the maintext. It typically renders as an indented block of text.

Code snip
Tinsae D@2024 Internet and web design
<blockquote>

<p>This is a longer quotation that should be set apart from the main
text.</p>
<cite>John Doe</cite>

</blockquote>
Result

The <cite> element can be used within the <blockquote> element to provide
the source or authorof the quotation.

B. Q (<q>):

The <q> element is used to mark up short inline quotations within a paragraph or
sentence.

Code snip
<p>He said, <q>This is a short quotation</q>, and continued his

speech.</p>
Result

Tinsae D@2024 Internet and web design


C.Cite (<cite>):

The <cite> element is used to indicate the title of a creative work, such as a
book, article, or song,or to provide a reference to the source of information.

Code snip
<p>The article titled <cite>HTML Basics</cite> provides an intr

oduction to web development.</p>


Result

D. Dfn (<dfn>):

The <dfn> element is used to mark the defining instance of a term within a
document. It iscommonly used in glossaries or to provide definitions of technical
terms.

Code snip
<p>The <dfn>HTML</dfn> stands for Hypertext Markup
Language</p>
Result

Tinsae D@2024 Internet and web design


E. Address (<address>):

The <address> element is used to represent contact information or the contact


details of the authoror owner of a document.

Code snip
<address>

<p>John Doe</p>

<p>1234 Main Street</p>

<p>City, State ZIP</p>

</address>
Result

Tinsae D@2024 Internet and web design


The <address> element is commonly used within the footer section or at
the end of an article to provide the contact information associated with
the document.

F. Bidirectional Override (<bdo>):

The <bdo> element is used to override the text directionality (left-to-right or


right-to-left) of thecontent within it.

Code snip
<bdo dir="rtl">This text is right-to-left.</bdo>
Result

By specifying the dir attribute with a value of "rtl" (right-to-left) or "ltr" (left-
to-right), you canchange the directionality of the text within the <bdo> element.

G. Abbreviation (<abbr>):

The <abbr> element is used to mark up abbreviations or acronyms within a


document. It can beused to provide the full expansion or explanation of an
abbreviation.
Tinsae D@2024 Internet and web design
Code snip
<p>The <abbr title="Hypertext Markup Language">HTML</abbr> is t

he standard markup language for creating web pages.</p>


Result

In the example above, the <abbr> element is used to mark the abbreviation
"HTML" and providethe full expansion using the title attribute. When the user
hovers over the abbreviation, the full expansion will be displayed as a tooltip.
Including the <abbr> element helps provide additional context and
understanding for abbreviations or acronyms used in your content. It enhances
accessibility, allowing assistive technologies to provide the full expansion of the
abbreviation when necessary.

These quotation and citation elements help provide structure and clarity to quoted
or cited contentin HTML documents. They aid in accessibility, search engine
optimization, and proper renderingacross different devices and browsers. It's
important to use these elements appropriately and in accordance with their
intended purpose to ensure accurate interpretation and presentation of the quoted
or cited information.

2.6. HTML Comments

Tinsae D@2024 Internet and web design


HTML comments are used to add explanatory or informational notes within the
HTML code. Theyare not displayed on the rendered web page and are intended
for developers or anyone reading thecode to understand the purpose or context of
certain elements or sections. Comments are helpful for adding documentation,
reminders, or temporarily disabling code without deleting it. Here's
how you can create HTML comments:

<!-- This is an HTML comment. -->

Comments start with <!-- and end with -->. Anything placed between these
delimiters will be treated as a comment and will not be rendered by the browser.
Here's an example of comments used in HTML code:

In the example above, comments are used to provide explanations and notes
within the HTML code. The comments labeled "CSS Styles" and "JavaScript
Scripts" indicate the purpose of the

linked files. The comment "Main Content" helps identify the main content
section within the body.The "TODO" comment serves as a reminder for future
development tasks.

<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<!-- CSS Styles -->

Tinsae D@2024 Internet and web design


<link rel="stylesheet" href="styles.css">
</head>
<body>
<!-- Main Content -->
<h1>Welcome to my website!</h1>
<p>This is the homepage.</p>
<!-- TODO: Add more content here -->
<!-- JavaScript Scripts -->
<script src="script.js"></script>
</body>

Comments are a useful tool for organizing, documenting, and communicating


within your HTML

code. They improve code readability and maintainability, especially when


working collaboratively or revisiting the codebase in the future.

2.7. HTML Colors

A. Color Values

In HTML, you can specify colors using various methods, including predefined
color names, hexadecimal color codes, RGB values, or HSL values. These color
representations allow you to define the color of text, backgrounds, borders, and
other elements on your web page. Here are thedifferent ways to specify colors in
HTML:

Tinsae D@2024 Internet and web design


 Predefined Color Names: HTML provides a set of predefined color names
that you can use directly. Some examples include "red," "green," "blue,"
"yellow," and "black." Here's how you can use a predefined color name:

<p style="color: red;">This text is in red.</p>

 Hexadecimal Color Codes: Hexadecimal color codes represent colors using


a combination of six hexadecimal digits (0-9 and A-F). The first two digits
represent the red component, the nexttwo represent green, and the last two
represent blue. Here's an example:

<p style="color: #00FF00;">This text is in green.</p>


 RGB Values: RGB (Red, Green, Blue) values allow you to specify the
intensity of each colorcomponent using decimal values between 0 and 255.
Here's an example:

<p style="color: rgb(255, 0, 0);">This text is in red.</p>

 HSL Values: HSL (Hue, Saturation, Lightness) values represent colors


using three parameters:hue (0- 360), saturation (0-100%), and lightness (0-
100%). Here's an example:

<p style="color: hsl(120, 100%, 50%);">This text is in green.</p>

These methods can be applied to the color property using inline styles or in a
separate CSS file todefine the color of various HTML elements. Additionally,
you can use the same color representations for other CSS properties such as

Tinsae D@2024 Internet and web design


background-color, border-color, and more. By specifying colors in HTML, you
can customize the visual appearance of your web page and createa visually
appealing design. It's important to choose appropriate colors that provide good
contrastand readability for your content.

Figure 2-5 Standard Colors IN HTML

Tinsae D@2024 Internet and web design


Set color Properties in HTML
In HTML, you can use CSS properties to specify colors for text, background,
and borders of HTML elements. Here are examples of how to use the color,
background-color, and border-colorproperties to control the color of different
elements:

 Text Color:

You can use the color property to define the color of text within an HTML
element. You can specify the color using predefined color names, hexadecimal
color codes, RGB values, or HSL values.

<p style="color: red;">This text is in red.</p>


<h1 style="color: #00FF00;">This heading is in green.</h1>
<span style="color: rgb(255, 0, 0);">This span is in red.</span>
<div style="color: hsl(120, 100%, 50%);">This div is in green.</
div>

Result

Tinsae D@2024 Internet and web design


 Background Color:

The background-color property is used to set the background color of an HTML


element. It can beused to give a specific color to the background of a text block,
a container, or the entire page.

Result

Tinsae D@2024 Internet and web design


 Border Color:

The border-color property is used to specify the color of the border around an
HTML element. It can be combined with other border-related properties to
control the style, width, and placement ofthe border.

Result

Tinsae D@2024 Internet and web design


In these examples, the style attribute is used to apply inline CSS styles to the
HTML elements. However, it's generally recommended to use external CSS files
or internal <style> tags for better separation of concerns and maintainability. By
using the color, background-color, and border-colorproperties, you can easily
customize the appearance of text, background, and borders on your HTML
elements, allowing for visually appealing designs and better readability.

2.8. HTML Image and Multimedia

2.8.1. HTML Images

There are many reasons why you might want to add an image to a web page: you
might want to include a logo, photograph, illustration, diagram, or chart. There
are several things to consider when selecting and preparing images for your site
but taking time to get them right will make it look more attractive and
professional. In this section you will learn how to:

 Include an image in your web pages using HTML

 Pick which image format to use

 Show an image at the right size

Tinsae D@2024 Internet and web design


 Optimize an image for use on the web to make pages load faster

Choosing images for your site

A picture can say a thousand words, and great images help make the difference
between an averagelooking site and a really engaging one. Images can be used
to set the tone for a site in less time than it takes to read a description. If you do
not have photographs to use on your website, there arecompanies who sell stock
images; these are images you pay to use (there is a list of stock photography
websites below). Remember that all images are subject to copyright, and you can
getin trouble for simply taking photographs from another website. Images
Should...

 Be relevant
 Convey information
 Convey the right mood

 Be instantly recognizable
 Fit the color palette
Image file types

When using the <img> element, you can supply JPEG (.jpg or .jpeg), GIF (.gif),
PNG (.png), or SVG (.svg) files. The following is a brief description of each file
type that should help you decidewhich file type to use for your application.

 JPG Also known as JPEG, this is best for photographs because it offers high
Tinsae D@2024 Internet and web design
compressionand up to
16.8 million color combinations, butthe compression algorithm is lossy,
meaningthat you lose detail every time you save the file.
 GIF GIF is great to use on small images that have a fixed number of colors.
GIF also supports transparent color. GIF uses lossless compression and is
best for logos and worst for photos. GIF also supports the ability to
encapsulate multiple images in one file, whichis commonly used to provide
animated GIFs.
 PNG PNG is a great all-around file type due to its lossless high
compression. PNG files can be 48- bit true color or 16-bit grayscale. PNG
not only supports transparent color but also offers variable transparency.
Photos aren’t compressed to be as small as JPG photos but being lossless
makes it worth the extra size in many scenarios. You might use PNG asyour
storage type for photos that you want to edit, but when displaying them on
the web, you might want to save the PNG as JPG to achieve the best
compression.
 SVG SVG is Scalable Vector Graphics and is great for drawings but not
for photos. SVGimages can be scaled up or down without losing detail
because the file contains the instructions to draw the image, as opposed to
the other file types that contain a raster-basedimage. Raster-based images
are composed of color dots that make up the image. If you need to scale a
raster-based image up or down, you will see that in color, dots are re-
sampled, and the image typically ends up looking blocky.
Tinsae D@2024 Internet and web design
Adding Images

The <img> tag is an HTML element used to display images on a web page. It is
a self-closing tag,meaning it does not have a closing tag. The <img> tag requires
the src attribute, which specifies the source URL or file path of the image. It also
supports several optional attributes to provide additional information and control
the behavior and appearance of the image.

There are 2 ways to insert the images into a webpage:

 By providing a full path or address (URL) to access an internet file.

 By providing the file path relative to the location of the current web page
file.

We will first discuss inserting the image to the webpage & simultaneously, we
will understandboth the above approaches.

Adding images on a webpage: The <img> tag is used to add or embed the images
Tinsae D@2024 Internet and web design
to a webpage/website. The “img” tag is an empty tag, which means it can contain
only a list of attributes and it has no closing tag. The addition of the images
improves the quality along with enhancing the design structure, appearance of
the webpage. Nowadays, a website does not directlyadd images to a web page,
as the images are linked to web pages by using the <img> tag which holds space
for the image.
Syntax:
<imgsrc="url"alt="some_text"width=""height="">
Attributes:
The <img> tag has following attributes:
 src: It is used to specify the path to the image.

 alt: It is used to specify an alternate text for the image. It is useful as it


informs the user about what the image means and also due to any network
issue if the image cannot be displayed then this alternate text will be
displayed.

 crossorigin: It is used to import images from third-party sites that allow cross-
origin access

Tinsae D@2024 Internet and web design


to be used with canvas.

 height: It is used to specify the height of the image.

 width: It is used to specify the width of the image.

 ismap: It is used to specify an image as a server-side image map.

 loading: It is used to specify whether a browser should defer the loading


of images until some conditions are met or load an image immediately.
 longdesc: It is used to specify a URL to a detailed description of an image.

 referrerpolicy: It is used to specify which referrer information to use


when fetching an image i.e. no-referrer, no-referrer-when-downgrade,
origin, origin-when-cross-origin, unsafe-url.
 sizes: It is used to specify image sizes for different page layouts.

 srcset: It is used to specify a list of image files to use in different situations.

 usemap: It is used to specify an image as a client-side image map.

Example 1: This simple example illustrates the use of the <img> tag in HTML
that is used toembed the image into the webpage.

Tinsae D@2024 Internet and web design


<!DOCTYPE html>
<html>
<head>
<title>Welcome To GFG</title>
</head>
<body>
<h2>Inserting Picture</h2>
<p>This is the demo of <img> tag.</p>
<img src="img_girl.jpg">
</body>
</html>

Tinsae D@2024 Internet and web design


Note: on the above example you can change the value of the src attribute by your

own or it willbe provided by your course instructor. Here is the output of the
above example:Output of the above code in a browser:

The ‘src’ attribute

Every image has an src attribute which tells the browser where to find the image
you want to display. The URL of the image provided points to the location where
the image is stored. When the webpage loads for the first time, then the browser
gets the image from a web server and insertsit into the page. If the image is not
spotted by the browser then users will get a broken link icon. Itmight be possible
if the file path is wrong or the image got deleted from that location.
Tinsae D@2024 Internet and web design
Example 2: Use of src attribute

The example illustrates the use of the src attribute in the <img> tag.

<!DOCTYPE html>
<html>
<head>
<title>src Attribute Example</title>
</head>
<body>
<p>Insert an image from the same folder with the file:</p>
<img src="img_girl.jpg">
<p>Insert an image from another folder:</p>
<img src="/images/stickman.gif">
<p>Insert an image from a web site:</p>
<img src="https://www.w3schools.com/images/lamp.jpg" >
</body>
</html>

Note: on the above example you can change the value of the src
attribute by your own or it will be provided by your course instructor.
Here is the output of the above example:

Output of the above code in a browser:

Tinsae D@2024 Internet and web design


In the above example the src stands for source. It shows how to Insert an image
from the same folder , Insert an image from another folder and Insert an image
from a web site.

The ‘alt’ attribute

alt: If the image cannot be displayed then the alt attribute acts as an alternative
description for theimage. The value of the alt attribute is a user-defined text. It
generally happens when the user, forsome reason, cannot view it due to a slow
internet connection or an error in the src attribute, or ifthe user uses a screen
reader.

Example 3: The example illustrates the use of the alt attribute in the <img> tag.

Tinsae D@2024 Internet and web design


<!DOCTYPE html>
<html>
<head>
<title>Alt Attribute Example</title>
</head>
<body>

<p>inserted image using "img" tag and Adding image name in usi
ng "alt" attribute:</p>
<img src="" alt="Girl in a jacket">
</body>
</html>

Output:

Tinsae D@2024 Internet and web design


The width and height attributes -Image Size
Setting width and height of Image: The width and height attributes are used to
specify the height and width of an image. The attribute values are specified in
pixels by default. The width and heightattributes are always declared in pixels.

Example 4: The example illustrates the use of the width & height attribute in the
<img> tag.

<!DOCTYPE html>
<html>
<body>
<h2>Image Size</h2>
<p>Here we specify the width and height of an image with the width an
d height attributes:</p>

<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">

</body>

</html>

Alternatively, You can use the style attribute to specify the width and height of
an image.

Example 5: The example illustrates the use of the style attribute to set the width
& height of animage.

Tinsae D@2024 Internet and web design


<!DOCTYPE html>

<html>

<body>

<h2>Image Size</h2>

<p>Here we use the style attribute to specify the width and height of an image:</p>

<img src="img_girl.jpg" alt="Girl in a jacket" style="width:500px;height:600px;">

</body>

</html>

Note that: Both the above examples (4 and 5) have the same output on the
browser.
Common Image Format: Here is the commonly used image file format that is
supported by allthe browsers.

S.N Abbreviati File Type Extension


o on
.

1. PNG Portable Network Graphics. .png

2. JPEG. Joint Photographic Expert .jpg, .jpeg, .jfif,


Group image. .pjpeg, .pjp

3. SVG Scalable Vector Graphics. .svg.

Tinsae D@2024 Internet and web design


4. GIF Graphics Interchange Format. .gif

5. ICO Microsoft Icon. .ico, .cur

6. APNG Animated Portable Network .apng


Graphics.

2.8.2. Adding sound to your HTML document

The <audio> tag is an HTML element used to embed audio content within a web
page. It providesa native way to play audio files directly in the browser
without the need for external plugins. Youcan use the
<audio> tag to add various audio formats such as MP3, WAV, or OGG to
your web pages. Here's an example of the <audio> tag with some commonly
used attributes:

Tinsae D@2024 Internet and web design


src
ur

Output of the above example on a browser:

In this example:
 src: Specifies the source URL or file path of the audio file. It is a required
attribute.

 controls: Adds default audio controls (play, pause, volume, etc.) to the
audio player,allowing users to control the playback.
 autoplay: Starts playing the audio automatically when the page loads.

 loop: Makes the audio repeat continuously.

The content placed between the opening and closing <audio> tags, in this case,
"Your browser does not support the audio element," will be displayed if the
browser does not support the <audio>tag or the specified audio format.
Tinsae D@2024 Internet and web design
Here's another example demonstrating additional attributes:

<audio src="audio.mp3" controls preload="metadata" volume="0.5">


Your browser does not support the audio element.

</audio>

Preload: Specifies the audio preloading behavior. The value "metadata" indicates that
onlythe audio metadata, such as duration, should be loaded. Other values include
"auto" (the entire audio file is preloaded) and "none" (no preloading).
 Volume: Sets the initial volume of the audio. The value ranges from 0.0
(silent) to 1.0 (fullvolume).

These are just a few examples of the attributes that can be used with the <audio>
tag. Other attributes, such as muted, controlsList, crossorigin, and more, provide
additional control and customization options for embedding and controlling
audio content on a web page.Remember to provide fallback content within the
<Audio> tags, as shown in the examples, so that users can understand and interact
with the audio content if their browser does not support the <audio> tag or the
specified audio format.

2.8.3. Adding Video to your HTML document

The <video> tag is an HTML element used to embed video content within a web
page. It providesa native way to play video files directly in the browser without
the need for external plugins. Withthe <video> tag, you can add various video
formats such as MP4, WebM, or Ogg to your web pages.

Tinsae D@2024 Internet and web design


Here's an example of the <video> tag with some commonly used attributes:

<!DOCTYPE html>
<html>
<body>
<video controls autoplay loop width="640" height="360">
<source src="movie.mp4" type="video/mp4"> Your
browser does not support the video tag.
</video>
</body>
</html>

Output of the above example on a browser:

In this example:

Tinsae D@2024 Internet and web design


 src: Specifies the source URL or file path of the video file. It is a
required attribute.

 controls: Adds default video controls (play, pause, volume, etc.) to


the video player,allowing users to control the playback.
 autoplay: Starts playing the video automatically when the page loads.

 loop: Makes the video repeat continuously.

 width: Sets the width of the video player in pixels or as a


percentage of the parent container.
 height: Sets the height of the video player in pixels or as a
percentage of the parent container.
The content placed between the opening and closing <video> tags, in this case,
"Your browser does not support the video element," will be displayed if the
browser does not support the <video>tag or the specified video format. Here's
another example demonstrating additional attributes:

<video src="video.mp4" controls preload="metadata" poster="poster.jpg">


Your browser does not support the video element.

</video>

Tinsae D@2024 Internet and web design


 preload: Specifies the video preloading behavior. The value "metadata"
indicates that onlythe video metadata, such as duration and dimensions,
should be loaded. Other values include "auto" (the entire video file is
preloaded) and "none" (no preloading).
 poster: Specifies an image to be displayed as a placeholder or poster frame
before the video is played.
These are just a few examples of the attributes that can be used with the <video>
tag. Other attributes, such as muted, controlsList, crossorigin, playsinline, and
more, provide additional control and customization options for embedding and
controlling video content on a web page. Remember to provide fallback content
within the <video> tags, as shown in the examples, so thatusers can understand
and interact with the video content if their browser does not support the
<Video> tag or the specified video format.
2.9. HTML Lists and Table
2.9.1. HTML Lists

Lists are used to group together related pieces of information, so they are clearly
associated with each other and easy to read. In modern web development, lists
are workhorse elements, frequentlyused for navigation as well as general content.
Humans are natural list makers, and HTML provides elements for marking up
three types of lists:

 Unordered lists. Collections of items that appear in no particular order.

 Ordered lists. Lists in which the sequence of the items is important.

Tinsae D@2024 Internet and web design


 Description lists. Lists that consist of name and value pairs, including but
not limited to terms and definitions.

Figure 2-6 Types of lists with example


All list elements—the lists themselves and the items that go in them—are
displayed as block elements by default, which means that they start on a new line
and have some space above and below, but that may be altered with CSS. In this
section, we’ll look at each list type in detail.

A. Unordered lists

Unordered lists are often referred to as bulleted lists. Instead of being numbered,
each element in the list has the same marker. The markup to create an unordered
list looks just like an ordered listexcept that the list is created by using
<ul>...</ul> tags rather than ol. The elements of the list areplaced within <li>
tags, just as with ordered lists. Browsers have standardized on using a solid bullet
to mark each item in an unordered list by default. Text browsers usually use an
asterisk forthese lists. The following input and output example shows an
unordered list. example shows the results in a browser.

Example
Tinsae D@2024 Internet and web design
<!DOCTYPE html>

<html>

<head>

<title> Unordered lists Example</title>

</head>

<p>Things I like to do in the morning:</p>

<body>

<ul>

<li>Drink a cup of coffee</li>

<li>Watch the sunrise</li>

<li>Listen to the birds sing</li>

<li>Hear the wind rustling through the trees</li>

<li>Curse the construction noises for spoiling the peaceful mood</li>

</ul >

</body>

Output

Figure 2-7 An unordered list output

Tinsae D@2024 Internet and web design


Customizing Unordered Lists

As with ordered lists, unordered lists can be customized using the type attribute
or the list-style- type property. As mentioned in the section on ordered lists, the
type attribute is no longer valid forHTML5. The bullet styles are as follows:

 "disc"—A disc or bullet; this style is the default.

 "square"—Obviously, a square rather than a disc.

 "circle"—As compared with the disc, which most browsers render as a


filled circle, this value should generate an unfilled circle.
In this case, the values for list-style-type and for the type attribute are the same.
In the following input and output example, you see a comparison of these three
types as rendered in a browser (seeFigure 2.7):

Example

</ul>

Tinsae D@2024 Internet and web design


</ul>

</ul>

Output

Figure 2-8Unordered lists with different bullet styles

If you don’t like any of the bullet styles used in unordered lists, you can substitute
an image of your own choosing in place of them. To do so, use the list-style-
image property. By setting this property, you can use an image of your choosing
for the bullets in your list. Here’s an example :

Tinsae D@2024 Internet and web design


<ul style="list-style-image: url(/https/www.scribd.com/bullet.gif);">

<li>Example</li>

</ul>

Nesting Lists
A nested list is a list inside another list. You can create a nested unordered list, or
a nested orderedlist, or even an ordered list nested inside an unordered one.
Remember that the only direct child ofthe <u>l tag is
<li>.

Tinsae D@2024 Internet and web design


Example: Nested Unordered List, It is used to nest the list items ie., a list inside
<ul>

<li>DSA</li>

<ul>

<li>Array</li>

<li>Linked List</li>

<li>stack</li>

<li>Queue</li>

</ul>

<li>Web Technologies</li>

<ul>

<li>HTML</li>

<li>CSS</li>

<li>JavaScript</li>

</ul>

<li>Aptitude</li>

<li>Gate</li>

<li>Placement</li>
another list.

Tinsae D@2024 Internet and web design


Output

Figure 2-9 Nested Unordered List

B. Ordered lists

Ordered lists are surrounded by the <ol>...</ol> tags (ol stands for ordered list),
and each item within the list is included in the <li>...</li> (list item) tag. When
the browser displays an ordered list, it numbers and indents each of the elements
sequentially. You don’t have to perform the numbering yourself and, if you add
or delete items, the browser renumbers them the next time thepage is loaded.
Ordered lists are lists in which each item is numbered or labeled with a counter
ofsome kind (like letters or roman numerals).

Use numbered lists only when the sequence of items on the list is relevant.
Ordered lists are goodfor steps to follow or instructions to the readers, or when
Tinsae D@2024 Internet and web design
you want to rank the items in a list. If you just want to indicate that something
has a number of elements that can appear in any order, use an unordered list
instead. For example, the following is an ordered list of steps that explain how
to boil an egg.

You can see how the list is displayed in a browser in the example bellow.

Example:

Output :
Tinsae D@2024 Internet and web design
Figure 2-10 An ordered list in HTML
Customizing Ordered Lists

There are two customizations that are specific to ordered lists. The first enables
you to change thenumbering style for the list, and the second enables you to
change the numbering itself. There aretwo ways to change the numbering style:
the CSS property list-style-type, and the type attribute, which is obsolete in
HTML5. If you’re creating a new ordered list, you should always use the
CSSproperty, however, you may see existing Web pages in which the type
attribute is used instead.

Attributes:
Tinsae D@2024 Internet and web design
 compact: It defines the list should be compacted (compact attribute is not
supported in HTML5. Use CSS instead.).
 reversed: It defines that the order will be descending.

 start: It defines from which number or alphabet the order will start.

 type: It defines which type(1, A, a, I, and i) of the order you want in your
list of numeric,alphabetic, or roman numbers.

Figure 2-11 Ordered List Numbering Styles

You can specify types of numbering in the <ol> tag using the style attribute, like
this:

<ol style="list-style-type: lower-alpha;">

By default, the decimal type is assumed.

Tinsae D@2024 Internet and web design


If you were to set the list style type upper-roman to the to the <ol> tag, as follows,
it wouldappear in a browser as shown in Figure 2:12
Example:

<h1>The days of the week in French</h1>

<ol style="list-style-type: upper-roman;">

<li>Lundi</li>

<li>Mardi</li>

<li>Mercredi</li>

<li>Jeudi</li>

<li>Vendredi</li>

<li>Samedi</li>

<li>Dimanche</li>
</ol >

Output:

Tinsae D@2024 Internet and web design


Figure 2-12 An ordered list displayed using an alternative numbering style.
Let me digress briefly to talk about how you can use Chrome’s Developer Tools
to edit styles onthe fly. If you want to see what the list in Figure 5.2 looks like
with the lower-roman list style, you can change the style attribute directly and
see the results. Just open the developer tools, make sure the elements tab is open,
and then click on the style attribute of the <ol> tag. You canthen edit the attribute
and see the page change instantly. The updated developer tools window isshown
in Figure 2:13

Figure 2-13 The Chrome developer tools with the updated


<ol> tag.

You can also use the list-style-type property with the <li> tag, changing the
Tinsae D@2024 Internet and web design
numbering type in themiddle of the list, but you need to change every list item
following it if you want them all to havethe same new type. Using the start
attribute, you can specify the number or letter with which to start your list. The
default starting point is 1, of course. You can change this number by using start.
<ol start="4">, for example, would start the list at number 4, whereas <ol
style="list-style-type: lower- alpha"start="3"> would start the numbering with c
and move through the alphabet from there. The value for the start attribute should
always be a decimal number, regardless of the numbering style being used. For
example, you can list the last six months of the year and start numbering with
the Roman numeral VII as follows. The results appear in Figure 2:14

Example:

st<

Output:

Tinsae D@2024 Internet and web design


Figure 2-14 An ordered list with an alternative numbering style and starting
number.
Example : Nested ordered list,
a nested ordered list is a list that has a list inside another list.

Bl

Tinsae D@2024 Internet and web design


</ol>

Output :

C. Definition Lists

Definition lists differ slightly from other lists. Each list item in a definition list has
two parts:
 A term

 The term’s definition

Each part of the glossary list has its own tag: <dt> for the term (definition term ),
and <dd> forits definition (definition description). <dt> and <dd> usually occur
in pairs, although most browsers can handle single terms or definitions. The
entire glossary list is indicated by the tags
<dl>...</dl> (definition list).

The following is a glossary list example with a set of herbs and descriptions of
how they grow(see Figure 2.14):

Tinsae D@2024 Internet and web design


Example :

<dt>Basil</dt>

ur
is heavenly</dd>

stab

</dl>

Output:

Figure 2-15 A definition list


Tinsae D@2024 Internet and web design
2.9.2. HTMLTables

Creating tables in HTML is a degree more complex. Think about how many
different types of tables there are. A table can be a three-by-three grid with labels
across the top, or two side-by-sidecells, or a complex Excel spreadsheet that
comprises many rows and columns of various sizes. Representing tables in
HTML is heavy on tags, and the tags can be hard to keep track of when youget
going.

The basic approach with table creation is that you represent tabular data in a linear
fashion, specifying what data goes in which table cells using HTML tags. In
HTML, tables are created from left to right and top to bottom. You start by
creating the upper-left cell and finish with the bottom-right cell. This will all
become clearer when you see some actual table code .

Table Parts
Before getting into the actual HTML code to create a table, here are some table-
related terms you’llsee throughout this lesson:

 The caption indicates what the table is about: for example, “Voting
Statistics, 1950–1994,” or
“Toy Distribution Per Room at 1564 Elm St.” Captions are optional.

 The table headings label the rows, columns, or both. Usually they’re in an
emphasized font that’s

Tinsae D@2024 Internet and web design


different from the rest of the table. They’re optional.

 Table cells are the individual squares in the table. A cell can contain
normal table data ora table heading.
 Table data is the values in the table itself. The combination of the table
headings and table data makes up the sum of the table.

Figure 2-16 The elements that make up a table.

The <table> Element


All the components of a table are placed within a <table>...</table> element:
<table>
...table caption (optional) and contents...
</table>
Here’s the code that produces the table shown in Figure 10.1. Don’t be concerned
if you don’t know what all this means right now. For now, notice that the table
starts with a <table> tag and its attributes and ends with a </table> tag:

Tinsae D@2024 Internet and web design


<table border="1">

<caption>Vital Statistics</caption>

<tr>

<th>Name</th>

<th>Height</th>

<th>Weight</th>

<th>Eye Color</th>

<tr
>
</tr>

</tr>

<tr
>

</tr
>
Tinsae D@2024 Internet and web design
</tr <td>Tom</td>
>
<td>6'0"</td>
<tr
<td>165</td>
> <td>
Aliso <td>Hazel</td>

n</td
>

<td>5
'4"</t
d> <td>Susan</td>

<td> <td>5'1"</td>

140< <td>97</td>
/td>
<td>Brown</td>
<td>
Blue<
/td>

Tinsae D@2024 Internet and web design


</table>
Rows and Cells

Now that you’ve been introduced to the <table> element, we’ll move on to the
rows and cells. Inside the
<table>...</table> element, you define the actual contents of the table. Tables are
specified in HTML row by row, and each row definition contains all the cells in
that row. So, to create a table, you start with the top row and then each cell in turn,
from left to right. Then you define a second row and its cells, and so on. The
number of columns is calculated based on how many cells there are in each row.
Each table row starts with the <tr> tag and ends with the closing
</tr>. Your table can have as many rows and columns as you like, but you should
make sure that each row has the same number of cells so that the columns line
up. The cells within each row arecreated using one of two elements:
 <th>...</th> elements are used for heading cells. Generally,
browsers center the contents of a <th> cell and render any text in the
cell in boldface.
 <td>...</td> elements are used for data cells. td stands for table data.

Tinsae D@2024 Internet and web design


In this table example, the heading cells appear in the top row and are defined with
<tr>

<th>Name</th>

<th>Height</th>

<th>Weight</th>

<th>Eye Color</th>

</tr>
the followingcode:
The top row is followed by three rows of data cells, which are coded as follows:

<td>5'4"</td>

</tr>

Tinsae D@2024 Internet and web design


<td>6'0"</td>

</tr>

<td>5'1"</td>

</tr>

As you’ve seen, you can place the headings along the top edge by defining the <th>
elements inside

the first row. Let’s make a slight modification to the table. You’ll put the
headings along the left edge of the table instead. To accomplish this, put each
<th> in the first cell in each row and followit with the data that pertains to each
heading. The new code looks like the following:

Tinsae D@2024 Internet and web design


Example:

</tr>

<td>5'4"</td>

<td>6'0"</td>

<td>5'1"</td>

</tr>

</tr>

Output:
Tinsae D@2024 Internet and web design
Figure 2-17 An example of a table that includes headings in the leftmost column.

Captions

Table captions tell your visitor what the table is for. The <caption> element,
created just for this purpose, displays the text inside the tag as the table caption
(usually centered above the table). Although you could use a regular paragraph
or a heading as a caption for your table, tools that process HTML files can extract
<caption> elements into a separate file, automatically number them, or treat them
in special ways simply because they’re captions.
If you don’t want a caption, it’s optional. If your table is understandable without
a caption or you have described it in some other location, you can leave it off.

Tinsae D@2024 Internet and web design


The <caption> element goes inside the <table> element just before the table

<table>

<caption>Vital Statistics</caption>

<tr >

rows, and it containsthe title of the table. It closes with the </caption> tag:
You can include details inside a caption to provide additional information about
the table that is

hidden by default. When you include details, you need to also include a summary
that acts as a title for the additional details. Chrome, Safari, and Opera all support
showing and hiding content with the <detail> and
<summary> tags. You can use the <details> and <summary> tags inside the
<caption> tag:

<caption>

<details>

<summary>Vital Statistics</summary>

<p>This table includes the name, height, and, weight of various employees.</p>

</details>

</caption>

Figure 2.18 shows a <detail> element that has been clicked on to show the
hidden content.

Tinsae D@2024 Internet and web design


Figure 2-18 A visible details

2.10.HTML Forms
HTML forms provide a way for users to interact with a website by submitting
data. HTML Formsare used to select different kinds of user input. HTML forms
are used to pass data to a server. Theyare essential for capturing user input, such
as text, selections, and file uploads. HTML forms consist of various form
elements, including input fields, checkboxes, radio buttons, dropdown lists,and
buttons. These elements are configured using attributes to define their behavior
and appearance. An HTML form can contain input elements like text fields,
checkboxes, radio-buttons,submit buttons and more. HTML provides a range of
form elements that allow developers to createinteractive forms for collecting user
input. Each form element is configured using variousattributes to define its
behavior and appearance. In addition to the standard HTML form
elements,HTML5 introduced new form elements and attributes that enhance the
Tinsae D@2024 Internet and web design
form-building process. Let's
explore both the standard and HTML5 form elements along with their attributes:
The <form> tagis used to create an HTML form:
Example

<form action="/submit" method="POST">

<!-- form elements go here -->

</form>

In the above example:

 <form>: Defines a container for form elements. Wraps all form elements
and provides thenecessary context for form submission.
 The form attributes

 action: Specifies the URL where the form data is submitted.

 method: Specifies the HTTP method used for form submission (e.g.,
"GET" or"POST").
2.10.1. HTML Forms - The Input Element

The most important form element is the <input> element. The <input> element
is used to selectuser information. An <input> element can vary in many ways,
depending on the type attribute. An <input> element can be of type text field,
checkbox, password, radio button, submit button,and more. The most common
input types are described below.

Tinsae D@2024 Internet and web design


A. Text Fields

<input type="text"> defines a one-line input field that a user can enter text or
alphanumericcharacters. The default width of a text field is 20 characters. :

<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username" placeh
older="Enter your username" required maxlength="20">
</form>

Output: How the HTML code above looks in a browser:

Description of the code:

In this example, we have a form field for capturing the user's username. Let's
break down theattributes and their significance:

 type="text": Specifies that the input field should accept text input.

 id="username": Assigns a unique identifier to the input field, which


can be used toassociate it with labels or perform JavaScript
manipulations.
 name="username": Provides a name for the input field. When the form
is submitted, thisname- value pair will be sent to the server.

Tinsae D@2024 Internet and web design


 placeholder="Enter your username": Displays a hint or example value
within the inputfield to guide users on what information to enter.
 required: Specifies that the input field must be filled out before the
form can be submitted.It enforces mandatory user input.
 maxlength="20": Sets the maximum number of characters that can be
entered into theinput field. In this case, the username is limited to 20
characters.

This <input type="text"> example demonstrates the usage of attributes to


define the behavior and appearance of the text input field. Users will see a labeled
input field where they can enter their username. The required attribute ensures
that the field cannot be left blank, and the maxlengthattribute limits the input to a
maximum of 20 characters. The placeholder text provides additionalguidance to
users regarding the expected input format.

B. Password Field

The <input type="password"> element is used to create a password input field in


HTML. It masksthe user's input, displaying asterisks or bullets instead of the
actual characters. This helps protect sensitive information, such as passwords or
PINs. Here's an example of <input type="password">with attributes and a
description.

Tinsae D@2024 Internet and web design


<form>
<label for="password">Password:</label>
<input type="password" id="password" name="password" req
uired minlength="8">
</form>

Output: How the HTML code above looks in a browser:

Note: The characters in a password field are masked (shown as asterisks or


circles).

C. Radio Buttons

The <input type="radio"> element is used to create a set of radio buttons in


HTML. Radio buttonsallow users to select a single option from a group of
mutually exclusive choices. Here's an exampleof <input type="radio"> with
attributes and a description:

Tinsae D@2024 Internet and web design


<form>
<label>Preferred Language:</label>
<input type="radio" id="english" name="language" value="
english" checked>
<label for="english">English</label>
<input type="radio" id="spanish" name="language" value="s
panish">
<label for="spanish">Spanish</label>
</form>

Output: How the HTML code above looks in a browser:

In this example, we have a set of radio buttons for selecting the preferred
language. Let's breakdown the attributes and their significance:
 type="radio": Specifies that the input field should be rendered as a radio
button.

 id="english" and id="spanish": Assigns unique identifiers to each radio


button. TheseIDs are used to associate the labels with the corresponding
radio buttons.
 name="language": Provides a common name for the radio buttons.
This ensures that onlyone option can be selected within the same group.
 value="english" and value="spanish": Assigns a value to each radio
button. When theform is submitted, the selected value will be sent to the
server.

Tinsae D@2024 Internet and web design


 checked: Specifies the default selected radio button. In this case, the
"English" option ispre- selected.
D. Checkboxes

The <input type="checkbox"> defines a checkbox. Checkboxes let a user select


ZERO or MOREoptions of a limited number of choices. Here's an example of
<input type="checkbox"> with attributes and a description:

<form>
<label for="option1">Option 1:</label>
<input type="checkbox" id="option1" name="options[]" value="op
tion1">

<label for="option1">Option 1</label>


<label for="option2">Option 2:</label>
<input type="checkbox" id="option2" name="options[]" value="op
tion2">

<label for="option2">Option 2</label>

Tinsae D@2024 Internet and web design


<input type="checkbox" id="option3" name="options[]" value="op
tion3">

<label for="option3">Option 3</label>


</form>

Output: How the HTML code above looks in a browser:

This <input type="checkbox"> example demonstrates the usage of attributes to create


a group of checkboxes. Users will see labeled checkboxes for "Option 1," "Option 2,"
and "Option 3." Theycan select one or more checkboxes based on their preferences.
The name attribute groups the checkboxes together, and the value attribute determines
the value associated with each checkbox.Upon form submission, the selected values
will be sent to the server as an array, indicated by the name attribute using square
brackets [].
E. Submit Button
<input type="submit"> defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page
specified in theform's action attribute. The file defined in the action attribute

Tinsae D@2024 Internet and web design


<form action ="demo_form_action.asp " method="post">
Username: <input type="text" name="user"><br>
Password: <input type="password" id="password" name="password" r
equired minlength="8"><br>
<input type="submit" value="Submit">
</form>

usually does something with the received input:


Output: How the HTML code above looks in a browser:

If you type some characters in the text field above, and click the "Submit" button, the
browser willsend your input to a page called "demo_form_action.asp". The page will
show you the received input.
2.10.2. Text area

The <textarea> element is used to create a multi-line text input field in HTML. It
allows users to enter and edit larger amounts of text. Here's an example of
<textarea> with attributes and a description:

<form>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" cols="30" placeho
lder="Enter your message" required></textarea>
</form>

Tinsae D@2024 Internet and web design


Output: How the HTML code above looks in a browser:

In this example, we have a textarea for capturing a message from the user. Let's
break down theattributes and their significance:

 rows="4": Specifies the visible number of rows (lines) for the textarea.
In this case, thetextarea will display four rows.

Tinsae D@2024 Internet and web design


 cols="30": Specifies the visible number of columns (characters per row)
for the textarea.In this case, the textarea will display 30 columns.
 placeholder="Enter your message": Displays a hint or example value
within the textareato guide users on what information to enter.
 required: Specifies that the textarea must be filled out before the form
can be submitted.It enforces mandatory user input.

This <textarea> example demonstrates the usage of attributes to create a multi-line


text input field.Users will see a labeled textarea where they can enter their
message. The rows and cols attributescontrol the size of the textarea, specifying
the visible number of rows and columns. The placeholder attribute provides
additional guidance to users regarding the expected input. The required attribute
ensures that the textarea cannot be left blank before form submission.

2.10.3. Drop-down list

The <select> element is used to create a drop-down list or a select menu in


HTML. It allows usersto choose an option from a list of predefined options.
Here's an example of <select> with attributesand a description:

Tinsae D@2024 Internet and web design


<form>
<label for="country">Country:</label>
<select id="country" name="country">
<option value="usa">Ethiopia</option>
<option value="canada">USA</option>
<option value="uk">UK</option>
<option value="australia">Australia</option>
</select>
</form>

Output: How the HTML code above looks in a browser:

In this example, we have a select menu for choosing a country. Let's break down the
attributesand their significance:
 <option> elements: Represent the available options within the select menu.
Each <option>element contains a value attribute and the text content that
represents the option. Users canchoose one of these options.

The selected option in the select menu will be sent to the server upon form
submission. By default,the first option (<option>) in the list is displayed as the
initially selected option. In the example, "Ethiopia" will be the initially selected

Tinsae D@2024 Internet and web design


option. This <select> example demonstrates the usage of attributes to create a
select menu in HTML. Users will see a labeled drop-down list where they
canchoose a country. The available options are represented by the <option>
elements. The selected option will be sent to the server when the form is
submitted, associated with the specified name.
2.10.4. Button

The <button> element is used to create a clickable button in HTML. It allows


users to trigger an action or perform an operation. Here's an example of <button>
with attributes and a description:

<form>
<button type="button" id="submitBtn" onclick="submitForm()">Logi
n</button>
</form>

Output: How the HTML code above looks in a browser:

In this example, we have a button that triggers a form submission. Let's break down
the attributesand their significance:
 type="button": Specifies that the button element should be rendered as a
regular button.It is used to perform custom actions or trigger JavaScript
functions.
 onclick="submitForm()": Specifies the JavaScript code or function to be
executed whenthe button is clicked. In this example, the submitForm()
Tinsae D@2024 Internet and web design
function will be called.
 Button content: The text "Submit" is the content of the button, which is
displayed to theuser.
When the button is clicked, it triggers the JavaScript function specified in the
onclick attribute. The function can perform various actions, such as validating
form data, manipulating the DOM, or initiating an AJAX request.
2.10.5. HTML5 Form Elements and Attributes:

HTML5 introduced several new form elements and attributes to enhance the
functionality and userexperience of web forms. Here are some of the notable
HTML5 form elements and attributes. These HTML5 form elements and
attributes enhance the functionality and user experience of webforms by
providing built-in validation, specialized input types, and more interactive
controls. Theyallow developers to create more intuitive and user-friendly forms
while reducing the need for custom JavaScript validation and user input
handling. Here is a combined example that illustratesHTML 5 form elements.

<form>
<fieldset>
<legend>Contact Information</legend>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="website">Website:</label>
<input type="url" id="website" name="website">
<label for="phone">Phone:</label>

Tinsae D@2024 Internet and web design


<label for="age">Age:</label>
<input type="number" id="age" name="age" min="0" max="120">
<label for="birthdate">Birthdate:</label>
<input type="date" id="birthdate" name="birthdate">
<label for="meeting-time">Meeting Time:</label>
<input type="time" id="meeting-time" name="meeting-time">
<label for="event-datetime">Event Date and Time:</label>
<input type="datetime-local" id="event-datetime" name="event-datetime">
<label for="color">Favorite Color:</label>
<input type="color" id="color" name="color" value="#ff0000">

<label for="rating">Rating (1-10):</label>


<input type="range" id="rating" name="rating" min="1" max="10"
>
</fieldset>
</form>

Output: How the HTML code above looks in a browser:

Tinsae D@2024 Internet and web design


In this example, we have a <fieldset> element that groups related form fields
together, and a

<legend> element that provides a caption or title for the fieldset. Inside the
fieldset, there arevarious input fields with different types and attributes.
 <input type="email"> represents an email input field where users can
enter their emailaddresses. The required attribute ensures that the field
must be filled out.

 <input type="url"> represents a URL input field for users to enter website
addresses.

 <input type="tel"> represents a telephone input field for entering phone


numbers.

 <input type="number"> represents a numeric input field where users


can enter their age.The min and max attributes define the allowed range of
values.

 <input type="date"> represents a date input field for selecting a specific


date.

 <input type="time"> represents a time input field for choosing a


particular time of day.

 <input type="datetime-local"> represents a combined date and time input


field.

 <input type="color"> represents a color input field that allows users to


Tinsae D@2024 Internet and web design
pick a color froma color palette.

 <input type="range"> represents a slider input field where users can


select a value withina specified range.

This combined example showcases the usage of different input types and
attributes to create a formwith various data input fields. The <fieldset> and
<legend> elements provide structure and a caption for the related fields,
enhancing the form's usability and organization.

2.11.The HTML <div> Element

The HTML <div> element is a block level element that can be used as a container
for grouping other HTML elements. The <div> element has no special meaning.
Except that, because it is a block level element, the browser will display a line
break before and after it. When used togetherwith CSS, the <div> element can
be used to set style attributes to large blocks of content. Anothercommon use of
the <div> element, is for document layout. It replaces the "old way" of defining
layout using tables. Using <table> elements for layout is not the correct use of
<table>. The purpose of the <table> element is to display tabular data.

2.12.The HTML <span> Element

The HTML <span> element is an inline element that can be used as a


container for text. The

Tinsae D@2024 Internet and web design


<span> element has no special meaning. When used together with CSS, the
<span> element can be used to set style attributes to parts of the text.

HTML Grouping Tags

<div>: Defines a section in a document (block-level)


<span>: Defines a section in a document (inline)

Example
<!DOCTYPE html>
<html>
<head>
<title>Line Break Example</title>
</head>
<body>
<div id="container" class="wrapper">
<h1>Welcome to <span class="highlight">My Website</span></h1>
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vestibulum consectetur, risus vel fermentum malesuada.</p>
<p>Suspendisse potenti. <span class="highlight">Vivamus</spa
n> accumsan nibh eu leo tincidunt, sit amet ultrices lectus luct
us.</p>
</div>
</div>
</body>
</html>

Tinsae D@2024 Internet and web design


Output

In this example, we have a <div> element with the attributes id="container" and
class="wrapper".Inside the
<div>, there is an <h1> element and another <div> element with the class
"content". Within the "content"
<div>, there are two <p> elements. The <span> element with the class
"highlight" is used within the <h1> and one of the <p> elements. Let's break
down the example:
 <div id="container" class="wrapper">: The outer <div> acts as a
container with the assigned ID "container" and the class "wrapper". This
can be used for applying styles or targeting the container with JavaScript.

 <h1>Welcome to <span class="highlight">My Website</span></h1>:


The <h1> element contains the text "Welcome to" followed by the word
"My Website" enclosed in a
<span> element with the class "highlight". This allows you to apply
specific styles or effects to the enclosed text.
 <div class="content">: The inner <div> acts as a container with the class
"content". It can be used to group related content or apply specific styles to
Tinsae D@2024 Internet and web design
the content within.

 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum


consectetur, risus vel fermentum malesuada.</p>: The first <p> element
contains some placeholder text.

 <p>Suspendisse potenti. <span class="highlight">Vivamus</span>


accumsan nibh eu leotincidunt, sit amet ultrices lectus luctus.</p>: The
second <p> element contains the text "Suspendisse potenti." followed by
the word "Vivamus" enclosed in a <span> element withthe class
"highlight".

In this combined example, the <div> element is used as a container to group and
organize the content of the webpage. The <span> element is used within the <h1>
and <p> elements to highlightspecific words or phrases. You can style or
manipulate the container <div> using the assigned IDor class, and target the
highlighted text using the specified class.

The usage of <div> and <span> elements in combination provides flexibility in


structuring and styling the content within HTML documents, allowing you to
create visually appealing and well-organized web pages.
2.13.HTML Layout
2.13.1. HTML Layouts

HTML layouts refer to the structural organization and arrangement of content on


a web page. HTML provides a variety of layout techniques that can be used to
create well-structured and visually appealing web pages. Here are some
commonly used HTML layout techniques. By combining these layout techniques
Tinsae D@2024 Internet and web design
and approaches, web developers can create visually appealing, accessible, and
responsive web page layouts. The choice of layout technique depends on the
specific requirements of the project, the complexity of the design, and the level
of flexibility and responsiveness needed.

A. Website Layout Using HTML5

Tag Desc
Defines a header for a document
header
or a section
Defines a container for
nav
navigation links
section Defines a section in a document
Defines an independent self-
article
contained article
Defines content aside from the
aside
content (like a sidebar)
Defines a footer for a document
footer
or a section
details Defines additional details

Defines a heading for the details


summary
element
HTML5 offers new semantic elements to clearly define different parts of a web
page:
Below is an example of a simple website layout using HTML5. This example
includes a header, navigation menu, main content area, sidebar, and footer.

Tinsae D@2024 Internet and web design


<!DOCTYPE html>
<html>
<head>
<title>Simple Website Layout</title>

<style>

body {

font-family: Arial, sans-


serif;margin: 0; padding: 0;

}
header {

background-color:
#333;color: #fff; text-
align: center;padding:
10px;
}

nav
{
background-color:
#444;color: #fff; text-
align: center;padding:
}
10px;

Tinsae D@2024 Internet and web design


nav a {

color: #fff;

text-decoration: none;padding: 5px 10px;


}

nav a:hover {

background-color: #555;

.container {

display: flex; flex-wrap: wrap; max-width: 1200px;

Tinsae D@2024 Internet and web design


margin: 0 auto;

main {

flex: 3; padding: 20px;


}

aside {

flex: 1;

background-color: #f5f5f5;padding: 20px;


}

footer {

background-color: #333;color: #fff;


text-align: center;padding: 10px; clear: both;
}

</style>

</head>

<body>

<header>

Tinsae D@2024 Internet and web design


<h1>Simple Website</h1>

</header>

<nav>

<a href="#">Home</a>

<a href="#">About</a>

<a href="#">Services</a>

<a href="#">Contact</a>

</nav>

<div class="container">

Tinsae D@2024 Internet and web design


<main>
<h2>Welcome to Our Website</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipisci
ng elit. Nulla eget nulla vel nisi commodo rutrum in at nunc.

</p>
</main>
<aside>
<h3>Side Bar</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipisci
ng elit. Nulla eget nulla vel nisi commodo rutrum in at nunc.

</p>
</aside>
</div>
<footer>
<p>&copy; 2023 Simple Website. All rights reserved.</p>
</footer>

The above example demonstrates a simple website layout using HTML5


and basic CSS styling. Let's break down the different components of the
layout:

 <!DOCTYPE html>: This line specifies the document type and version,
indicating that thedocument follows the rules of HTML5.
 <html>: The root element of the HTML document, encompassing all the
content.
Tinsae D@2024 Internet and web design
 <head>: Contains metadata about the document, such as the page title
and links to external stylesheets.
 <title>: Specifies the title of the webpage that appears in the browser's title
bar or tab.

 <style>: This section includes inline CSS code that defines the styles for
various elementsused in the layout.
 <body>: The main content of the webpage is placed within this element.

 <header>: Represents the top section of the webpage, commonly used


for the site'sbranding, logo, and main heading.
 <h1>: An HTML heading element that indicates the primary heading of the
page.

 <nav>: Represents the navigation menu section, typically containing


links to differentpages or sections of the website.
 <a>: The anchor tag is used to create hyperlinks to other pages or
resources. In this example,the navigation links are styled as buttons.
 <div class="container">: A container div used to hold the main content and
the sidebar.

 <main>: This element contains the primary content of the webpage. In


the example, itcontains a welcome message and some Lorem Ipsum text.
 <aside>: Represents the sidebar section, which contains additional
content related to themain content. In this example, it has a simple text
paragraph.
Tinsae D@2024 Internet and web design
 <footer>: Represents the footer section of the webpage, usually
containing copyright information, contact details, or other relevant links.
 CSS Styling: The embedded CSS code provides basic styling for various
elements, such assetting the font family, background colors, padding, and
layout with flexbox.

The output:

Tinsae D@2024 Internet and web design


The layout is designed to be responsive, with the use of flex properties to arrange
the main contentand sidebar in a row on larger screens and stack them vertically
on smaller screens. The header, navigation menu, and footer are styled with
consistent colors, creating a unified look and feel throughout the webpage.
Overall, this example serves as a foundation for building a simple, responsive,
and visually appealing website layout using HTML5 and basic CSS styling
techniques. More elements, content,and styles can be added to create a complete
and fully functional website.
B. HTML Layout Using <div> Elements

The <div> element was not designed to be a layout tool.

The div element is a block level element, designed for grouping HTML elements.
But layout canbe designed using <div> elements, because CSS can position and
style <div> elements. The following example uses five <div> elements to create
a multiple column layout:

Example

Tinsae D@2024 Internet and web design


<!DOCTYPE html>
<html>
<body>
<div id="container" style="width:500px">
<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bottom:0;">Main Title of Web Page</h1></div>
<div id="menu" style="background-color:#FFD700;height:200px;widt
h:100px;float:left;">

<b>Menu</b><br>
HTML<br>
CSS<br>

JavaScript</div>

Tinsae D@2024 Internet and web design


idth:400px;float:left;">
Content goes here</div>

<div id="footer" style="background-color:#FFA500;clear:both;text


-align:center;">
Copyright © 2023</div>

</div>
</body>

The HTML code above will produce the following result:

C.HTML Layout Using Tables

The <table> element was not designed to be a layout tool.

The purpose of the <table> element is to display tabular data. But layout can be
designed using

<table> element, because all table elements can be styled with CSS. The
following example usesa table with 3 rows and 2 columns - the first and last
row spans 2 columns using the colspan attribute:

Example
Tinsae D@2024 Internet and web design
<!DOCTYPE html>
<html>
<body>

<table style="width:500px;" cellpadding="0" cellspacing="0">

<tr>

<td colspan="2" style="background-color:#FFA500;">

<h1 style="margin:0;padding:0;">Main Title of Web Page</h1>

</td>

</tr>

<tr>

<td style="background-color:#FFD700;width:100px;vertical-align:top;">
<b>Menu</b><br>HTML<br>
CSS<br> JavaScript

</td>

<td style="background-
color:#eeeeee;height:200px;width:400px;vertical-align:top;">
Content goes here</td>

</tr>

Tinsae D@2024 Internet and web design


<tr>

<td colspan="2" style="background-color:#FFA500;text-


align:center;"> Copyright © W3Schools.com</td>

</tr>

</table>

</body>

</html>

Tinsae D@2024 Internet and web design


Lesson 2: Summary Question

1. What is the <htm tag in an HTML document?


purpose of the l>
2. How do you specify the character encoding for an HTML
document?
3. Explain the role of the <head> tag in HTML and give examples of
common elements within it.
4. What is the significance of the <title> tag in an HTML document?
5. Describe the difference between the <div> and <span> tags in
HTML, and provide examples of their usage.
6. How do you create an unordered list (<ul>) and an ordered list
(<ol>) in HTML? Provide examples.
7. What are semantic HTML tags, and why are they important for web
accessibility and SEO?
8. Explain the purpose of the <img> tag in HTML and how you
specify the image source and alternative text.
9. How do you create a hyperlink in HTML? Provide examples of
both relative and absolute URLs.
10. Describe the <table> tag in HTML and how you structure rows
(<tr>), columns (<td>), and headers (<th>).
11. What are HTML form elements, and how do you create a basic
form using <form> and input tags?

143
12. Explain the purpose of the <iframe> tag in HTML and give
examples of its usage.
13. How do you embed audio and video files in an HTML document?
Provide examples using the <audio> and <video> tags.
14. Describe the <meta> tag in HTML and its role in providing
metadata about the document.
15. What is the purpose of the <script> tag in HTML, and how do
you include external JavaScript files?
16. Explain the <blockquote> tag in HTML and its significance for
displaying quoted content.
17. How do you create headings (<h1> to <h6>) in HTML, and
what is their semantic significance?
18. Describe the <form> tag attributes action and method, and their
role in form submission.
19. Explain the use of the <abbr> tag in HTML for defining
abbreviations or acronyms, and provide an example.
20. How do you create a line break in HTML? Compare and contrast the
<br> tag with the CSS
proper white-space: .
ty pre;

144
Lesson 3: CSS

Basics of Cascading style sheet/CSS

CSS is the acronym for "Cascading Style Sheet". It's a style sheet
language used for describing the presentation of a document written in a
markup language like HTML. CSS helps the web developers to control
the layout and other visual aspects of the web pages. CSS plays a crucial
role in modern web development by providing the tools necessary to
create visually appealing, accessible, and responsive websites.

CSS Versions

Since the inception of CSS, several versions have come into existence.
Some of the notable versions include:

 CSS1 (Cascading Style Sheets Level1) - The initial version of


CSS, released in December 1996. CSS1 provided basic styling
capabilities for HTML documents, including properties for text,
colors, backgrounds, margins, and borders.
 CSS2 (Cascading Style Sheets Level2) - Released in May 1998,
CSS2 introduced new features such as positioning, z-index, media
types, and more advanced selectors like attribute selectors and child
selectors.

145
 CSS2.1 - The version 2.1, published as a W3C Recommendation in
June 2011, clarified and refined CSS2, addressing inconsistencies
and ambiguities in the specification. CSS2.1 focused on improving
interoperability among web browsers.
 CSS3 (Cascading Style Sheets Level 3) - CSS3 is a collection of
modules that extend the capabilities of CSS. It introduces numerous
new features and enhancements, including advanced selectors,
multiple column layouts, animations, transformations, gradients,
shadows, and more.
 CSS4 (Cascading Style Sheets Level 4) - CSS4 is an ongoing effort
to extend CSS3 with new features and enhancements.

Each version of CSS builds upon the previous ones, adding new features
and refining existing capabilities to meet the evolving needs of web
developers and designers. CSS is referred as just CSS now, without a
version number.

Components of CSS

CSS works by associating rules with HTML elements. A CSS rule contains two
main parts:

 a selector which specifies the HTML element(s) to style.


 a declaration block which contains one or more declarations separated by

146
semicolons.

147
Each declaration includes a property name and a value, specifying the
aspect of the element's presentation to control.

Sample Code

<html>
<head>
<title>CSS Tutorial</title>
<style>
h1 {
color: #36CFFF;
}

p{
font-size: 1.5em;
color: white;
}

div {
border: 5px inset gold;
background-color: black;
width: 300px;
text-align: center;
}
</style>
</head>
<body>
<div>
<h1>Hello World!</h1>
<p>This is a sample CSS code.</p>
</div>
</body>
</html>
Just to give you a little excitement about CSS, here is a sample CSS snippet for
your reference.

148
In the above CSS snippet:

 h1, p, and div are the selectors that target the <h1>, <p>, and <div>
elements.
 color, font-size, border, background-color, width, and text-align are the
properties.
 #36CFFF, 1.5em, white, 5px inset gold, black, 300px, and center
are the corresponding values passed to these properties.

CSS handles the look and feel part of a web page. Using CSS, you can
control the color of the text, the style of fonts, the spacing between
paragraphs, how columns are sized and laid out, what background images
or colors are used, layout designs,variations in display for different
devices and screen sizes as well as a variety of other effects.

149
CSS is easy to learn and understand but it provides powerful control over
the presentation of an HTML document. Most commonly, CSS is
combined with the markup languages HTML or XHTML.

Advantages of CSS
 CSS saves time − You can write CSS once and then reuse same
sheet in multiple HTML pages. You can define a style for each
HTML element and apply it to as many Web pages as you want.
 Pages load faster − If you are using CSS, you do not need to write
HTML tag attributes every time. Just write one CSS rule of a tag
and apply it to all the occurrences of that tag. So less code means
faster download times.
 Easy maintenance − To make a global change, simply change the
style, and all elements in all the web pages will be updated
automatically.
 Superior styles to HTML − CSS has a much wider array of
attributes than HTML, so you can give a far better look to your
HTML page in comparison to HTML attributes.
 Multiple Device Compatibility − Style sheets allow content to be
optimized for more than one type of device. By using the same
HTML document, different versions of a website can be presented
for handheld devices such as PDAs and cell phones or for printing.
 Global web standards − Now HTML attributes are being
deprecated and it is being recommended to use CSS. So its a good
150
idea to start using CSS in all the HTML pages to make them
compatible to future browsers.

CSS – Syntax
A CSS comprises of style rules that are interpreted by the browser and then
applied to the corresponding elements in your document. A style rule is made of
three parts −
 Selector − A selector is an HTML tag at which a style will be
applied. This could be any tag like <h1> or <table> etc.
 Property − A property is a type of attribute of HTML tag. Put
simply, all the HTML attributes are converted into CSS
properties. They could be color, border etc.
 Value − Values are assigned to properties. For example, color
property can have value either red or #F1F1F1 etc.

You can put CSS Style Rule Syntax as


follows − selector { property: value }

151
Example − You can define a table border
as follows − table{ border :1px solid #C00;
}
Here table is a selector and border is a property and given value 1px
solid #C00 is the value of that property.
You can define selectors in various simple ways based on your comfort.
Let me put these selectors one by one.
The Type Selectors
This is the same selector we have seen above. Again, one more example
to give a color to all level 1 headings −

h1 {
color: #36CFFF;
}

152
The Universal Selectors

Rather than selecting elements of a specific type, the universal selector


quite simply matches the name of any element type −

* {
color: #000000;
}
This rule renders the content of every element in our document in black.
The Descendant Selectors
Suppose you want to apply a style rule to a particular element only when
it lies inside a particular element. As given in the following example, style
rule will apply to <em> element only when it lies inside <ul> tag.

ul em {
color: #000000;
}
The Class Selectors
You can define style rules based on the class attribute of the elements.
All the elements having that class will be formatted according to the
defined rule.

.black {
color: #000000;
}
This rule renders the content in black for every element with class attribute set to black
in our document. You can make it a bit more particular. For example −

153
h1.black {
color: #000000;
}

This rule renders the content in black for only <h1> elements with class
attribute set to black. You can apply more than one class selectors to
given element. Consider the following example −
<p class = "center bold">
This para will be styled by the classes center and bold.
</p>

The ID Selectors
You can define style rules based on the id attribute of the elements.
All the elements having that id will be formatted according to the
defined rule.

#black {
color: #000000;
}

This rule renders the content in black for every element with id
attribute set to black in our document. You can make it a bit more
particular. For example −

h1#black {
color: #000000;
}

154
This rule renders the content in black for only <h1> elements with id attribute set
to black.

#black h2 {
color: #000000;
}
The true power of id selectors is when they are used as the foundation
for descendant selectors, For example −
In this example all level 2 headings will be displayed in black color
when those headings will lie with in tags having id attribute set to black.
The Child Selectors
You have seen the descendant selectors. There is one more type of
selector, which is very similar to descendants but have different
functionality. Consider the following example −

body > p {
color: #000000;

This rule will render all the paragraphs in black if they are direct child of
<body> element. Other paragraphs put inside other elements like <div>
or <td> would not have any effect of this rule.
The Attribute Selectors
You can also apply styles to HTML elements with particular attributes.
The style rule below will match all the input elements having a type
attribute with a value of text −

155
input[type = "text"] {
color: #000000;
}
The advantage to this method is that the <input type = "submit" /> element is
unaffected, and the color applied only to the desired text fields.
There are following rules applied to attribute selector.
 p[lang] − Selects all paragraph elements with a lang attribute.
 p[lang="fr"] − Selects all paragraph elements whose lang
attribute has a value of exactly "fr".
 p[lang~="fr"] − Selects all paragraph elements whose lang
attribute contains the word "fr".
 p[lang|="en"] − Selects all paragraph elements whose lang
attribute contains values that are exactly "en", or begin with "en-".
Multiple Style Rules
You may need to define multiple style rules for a single element. You
can define these rules to combine multiple properties and corresponding
values into a single block as defined in the following example −

h1 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

156
Here all the property and value pairs are separated by a semicolon (;).
You can keep them in a single line or multiple lines. For better
readability, we keep them in separate lines.
For a while, don't bother about the properties mentioned in the above
block. These properties will be explained in the coming chapters and you
can find complete detail about properties in CSS References
Grouping Selectors
You can apply a style to many selectors if you like. Just separate the
selectors with a comma, as given in the following example −

h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
This define style rule will be applicable to h1, h2 and h3 element as well. The order of
the list is irrelevant. All the elements in the selector will have the corresponding
declarations applied to them.
You can combine the various id selectors together as shown below −

#content, #footer, #supplement {


position: absolute;
left: 510px;
width: 200px;
}

157
CSS - Selectors
CSS selectors are patterns used to select and style HTML elements on a
web page. They allow you to target specific elements or groups of
elements to apply styles like colors, fonts, margins, and more. CSS
selectors are a fundamental part of Cascading Style Sheets (CSS), which
is a language used to control the presentation and layout of web
documents.
The element or elements that are selected by the selector are referred to as subject
of the selector.

Selector lists
If same CSS is used by more than one selector, then these selectors can
be combined together to form a selector list. Thus the CSS rule is
applied to all the individual selectors.

For example, if the same CSS, color: crimson is applied to p element


and .sample class, it is written as:

p {
color: crimson;
}

.sample {
color: crimson;
}

158
p, .sample {
color: crimson;
}
But, we can combine these two rules into one selector list, by adding a
comma to separate them as shown below:
Following syntax will be deemed invalid, as one of the selector is invalid
(..sample - is an incorrect way of defining a class).

p {
color: crimson;
}

..sample {
color: crimson;
}
p, ..sample {
color: crimson;
}

 A white space is acceptable before or after the comma in a selector list


declaration.
 If any of the selectors in the selector list is invalid, the whole rule
gets ignored and deemed invalid.
 It is advisable to define each selector in a new line, as it makes it more
legible.
CSS Selector - Type Selector

A type selector targets an HTML element, such as <h1>, <p>, etc.

159
p {
color: green;
}

h1 {
text-decoration-line: underline;
}

Following example demonstrates the use of a type selector:

<html>
<head>
<style>
div {
border: 5px inset gold;
width: 300px;
text-align: center;
}

p {
color: green;
}

h1 {
text-decoration-line: underline;
}
</style>
</head>
<body>
<div>
<h1>Type selector</h1>
<p>div with border and text-aligned to center</p>
<p>paragraph with green color</p>
<p>h1 with an underline</p>
</div>
</body>
</html>

CSS Selector - Class Selector

A class selector targets an element with a specific value for its class attribute.
160
.style-h1 {
text-decoration-line: underline;
}

.style-p {
color: green;
font-size: 25px;
}

Following example demonstrates the use of a class selector, where


.style-p, .style-h1 and .style- div are class selectors:

<html>
<head>
<style>
.style-div {
border: 5px inset gold;
width: 300px;
text-align: center;
}

.style-p {
color: green;
font-size: 25px;
}

.style-h1 {
text-decoration-line: underline;
}
</style>
</head>
<body>
<div class="style-div">
<h1 class="style-h1">class selector</h1>
<p class="style-p">class .style-p applied</p>
<p>No class applied on this p element</p>
</div>
</body>
</html>

161
CSS Selector - ID Selector

An ID selector targets an element with a specific value for its id attribute.

#style-p {
color: green;
font-size: 25px;
}

#style-h1 {
text-decoration-line: underline;
color: red;
}

Following example demonstrates the use of an id selector, where #style-

162
<html>
<head>
<style>
#style-div {
border: 5px inset purple;
width: 300px;
text-align: center;
background-color: lightgoldenrodyellow;
}

#style-p {
color: green;
font-size: 25px;
}

#style-h1 {
text-decoration-line: underline;
color: red;
}
</style>
</head>
<body>
<div id="style-div">
<h1 id="style-h1">ID selector</h1>
<p id="style-p">id #style-p applied</p>
<p>No id applied on this p element</p>
</div>
</body>
</html>
p, #style-h1 and #style- div are the id selectors applied on the elements:

CSS Selector - Attribute Selector

An attribute selector targets an element based on a specific attribute or


attribute values on an element.

163
a[target] {
background-color: peachpuff;
}

You can also specify the element with an attribute having a specific value.

a[href="https://www.tutorialspoint.com"] {
background-color: peachpuff;
}

Following example demonstrates the use of an attribute selector:

<html>
<head>
<style>
a[target] {
background-color: peachpuff;
color: blueviolet;
font-size: 2em;
}
</style>
</head>
<body>
<h2>Attribute selector</h2>
<p>Styling applied to anchor element with target attribute:</p>
<a href="#">Tutorialspoint</a>
<a href="#" target="_blank">google</a>
<a href="#" target="_self">wikipedia</a>
</body>
</html>

CSS Selector - Pseudo-class Selector


A pseudo-class selector is used to style a specific state of an element,
such as :hover is used to style an element when hovered.
For a detailed list of pseudo-class selectors, refer this link.

164
a :hover {
background-color: peachpuff;
color: green;
font-size: 2em;
}

Following example demonstrates the use of a pseudo-class selector:

<html>
<head>
<style>
a:hover {
background-color: peachpuff;
color: green;
font-size: 2em;
}
</style>
</head>
<body>
<h2>Pseudo-class selector</h2>
<p>Styling applied to anchor element with a pseudo-class:</p>
<a href="#">Tutorialspoint</a>
</body>
</html>

CSS Selector - Pseudo-element Selector


A pseudo-element selector is used to style a specific part of an element
rather than the element itself.
For a detailed list of pseudo-element selectors, refer this link.

a::before {
content: url();
}

Following example demonstrates the use of a pseudo-element selector (::before):

165
<html>
<head>
<style>
a::before {
content: url('images/smiley.png');
}

a::after {
content: " Pseudo-element ::after applied";
color: red;
background-color: chartreuse;
}

</style>
</head>
<body>
<h2>Pseudo-element selector</h2>
<p>Styling applied to anchor element with a pseudo-element:</p>
<a href="#">Tutorialspoint</a>
</body>
</html>

Combinators
Combinator shows the relationship between the selectors. Two or more
simple selectors can be combined using a combinator, to form a
selector. You can read more about combinator here.

Following example demonstrates the use of a descendant selector (space) and


child combinator:

166
<html>
<head>
<style>
/* style applied to only div */
div {
border: 2px solid black;
width: 300px;
}
/* style applied to all li elements directly under ul */
ul li {
background-color: lightpink;
color: purple;
font-size: 1.5em;
padding: 5px;
margin-right: 15px;
}

/* style applied to all li elements that are child element to ol


element */
ol > li {
background-color: bisque;
color: black;
font-size: 0.75em;
padding: 5px;
}
</style>
</head>
<body>
<div>

167
<ul>
<li>Item One</li>
<li>Item Two
<ol>
<li>Nested 1</li>
<li>Nested 2</li>
</ol></li>
<li>Item Three</li>
<li>Item Four</li>
<li>Item Five
<ol>
<li>Nested 3</li>
<li>Nested 4</li>
</ol>
</li>
</ul>
</div>
</body>
</html>

CSS Selector - Universal Selector

Universal selector, denoted by an asterisk mark (*), is a special selector


that matches any and all elements in an HTML document.

/* Selects and styles all elements on the page */


* {
margin: 0;
padding: 0;
}

As per the above syntax, the universal selector is used to apply a margin
and padding of 0 to all HTML elements.

Following example demonstrates the use of a universal selector (*):

168
<html>
<head>
<style>
* {
background-color: peachpuff;
color: darkgreen;
font-size: 25px;
}
</style>

</head>
<body>
<h1>Universal selector (*)</h1>

<div>Parent element
<p>Child paragraph 1</p>
<p>Child paragraph 2</p>
</div>

<p>Paragraph 3</p>
</body>
</html>

CSS - Inclusion
There are four ways to associate styles with your HTML document.
Most commonly used methods are inline CSS and External CSS.

169
You can put your CSS rules into an HTML document using the <style> element. This tag is placed
inside the <head>...</head> tags. Rules defined using this syntax will be applied to all the
elements available in the document. Here is the generic syntax − <!DOCTYPE html>
<html>
<head>
<style type = "text/css" media = "all">
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Embedded CSS - The <style> Element

It will produce the following result −


Attributes
Attributes associated with <style> elements are −
Attribe Value Description

Specifies the style sheet language as a


type text/css content-type (MIME type). This is required
attribute.

170
screen
tty
tv

projecti
on
handhel Specifies the device the document will be
media d print displayed on. Default value is all. This is an
braille optional attribute.
aural
all

Inline CSS - The style Attribute

You can use style attribute of any HTML element to define style rules.
These rules will be applied to that element only. Here is the generic
syntax −

<element style = "...style rules. ">

Attributes

Attribut Value Description


e

The value of style attribute is a

171
style style combination of style declarations separated
rules by semicolon (;).

Example

Following is the example of inline CSS based on the above syntax − <html>
<head>
</head>

<body>
<h1 style = "color:#36C;">
This is inline CSS
</h1>
</body>
</html>

It will produce the following result −

External CSS - The <link> Element

The <link> element can be used to include an external stylesheet file in your
HTML document.

An external style sheet is a separate text file with .css extension. You
define all the Style rules within this text file and then you can include this
file in any HTML document using <link> element.

172
Here is the generic syntax of including external CSS file −

<head>
<link type = "text/css" href = "..." media = "..." />
</head>
Attributes
Attributes associated with <style> elements are −

Attribut Value Description


e

Specifies the style sheet language as a


type text css content-type (MIME type). This attribute
is required.

Specifies the style sheet file having


href URL Style rules. This attribute is a required.

scre
en Specifies the device the document will be
media tty displayed on. Default value is all. This is
tv optional attribute.
projection

173
handh
eld
print
braille
aural
all

Example

Consider a simple style sheet file with a name mystyle.css having the following
rules −

h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

Now you can include this file mystyle.css in any HTML document as follows −

<head>
<link type = "text/css" href = "mystyle.css" media = " all" />
</head>

Imported CSS - @import Rule

174
@import is used to import an external stylesheet in a manner similar to
the <link> element. Here is the generic syntax of @import rule.

<head>
@import "URL";
</head>

Here URL is the URL of the style sheet file having style rules. You can
use another syntax as well −

<head>
@import url("URL");
</head>

Example

Following is the example showing you how to import a style sheet file into
HTML document −

<head>
@import "mystyle.css";
</head>

175
A border, in the context of design and styling, refers to a decorative or
functional element that surrounds the content of an object, such as a text
box, image, or any other HTML element on a web page.

The border property is used to create a border around an element, such


as a div, image, or text. It allows you to customize the appearance of the
border, including its color, width, and style.

Borders play a vital role in the overall aesthetics and design of the webpage.

Importance of borders

The importance of using borders in CSS can be summarized as follows:

 Visual separation: Borders help to visually separate different


elements on a webpage, making it easier for users to understand
the layout and navigation.
 Organization and structure: Borders can be given to grids,
tables or even boxes that makes the content look more organized
and structured.
 Emphasis and focus: Borders can be given to elements to emphasize and
highlight them.
 Design and aesthetics: Borders allow to add you to add
decoration to the elements to enhance the visual appeal. This can
176
be achieved using the style, color and width of border.
Borders - Properties

Following table describes the various properties of border, their


description and default values they hold:

Propert Description Default


y value

specifies whether a border


style should be none
solid, dashed line, double
line, or one of the other
possible values

177
width specifies the width of a medium
border

foreground color of the


color specifies the color of a element and if element is
border blank, then color of the
parent element

Now, we will see how to use these properties with examples.

CSS Borders - border-style Property

The border-style property is one of the essential properties of border.


Following values can be passed to border-style:

Value Description

none No border

hidden A hidden border, same as 'none' except for


table elements

dotted A series of dots

178
dashes A series of short dashes

solid A single solid line

double Two parallel lines with a small gap


between them

groove A border that appears to be carved into the


page

ridge A border that appears to be slightly raised


above the page

inset A border that appears embedded into the


page

outset A border that appears slightly raised out of


the page

179
initial Sets the border-style property to its default
value

inherit Inherits the border-style property from its


parent element

Let us see an example for these values of border-style:


<html>
<head>
<style>
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.dotted {border-style: dotted;}
p.dashes {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.mixed {border-style: none dashed solid dotted;}
</style>
</head>
180
<body>
<h2>border-style Property</h2>
<p class="none">No border.</p>
<p class="hidden">Hidden border.</p>
<p class="dotted">Dotted border.</p>
<p class="dashes">Dashed border.</p>
<p class="solid">Solid border.</p>
<p class="double">Double border.</p>
<p class="groove">Groove border.</p>
<p class="ridge">Ridge border.</p>
<p class="inset">Inset border.</p>
<p class="outset">Outset border.</p>
<p class="mixed">A mixed border.</p>
</body>
<html>

Single Side - Border Style

The property border-style can be exclusively specified for each


single-side. The same set of values can be passed to each single-side
for border-style:

 border-top-style

181
 border-right-style
 border-bottom-style
 border-left-style

Let us see an example:

<html>
<head>
<style>
p {border-top-style: dotted; border-right-style: solid; border-bottom-
style: dashed; border-left-style: double;
padding: 2em;}
</style>
</head>
<body>
<h2>border-style (single-side)</h2>
<p>Different border styles on all sides.</p>
</body>
<html>

CSS BorderS - width Property

The border-width property is next in line after setting border style.


Following values can be passed to border-width:

Value Description

thin a thin border

medium a medium width border

182
thick a thick border

length any length specified (like


0.1em, 5px)

Declare a border-style before declaring border-width, else the border effect will
not be seen.

Let us see an example (with and without specifying border-style):

<html>
<head>
<style>

183
p.thin {border-width: thin;}
p.medium {border-width:
medium;} p.thick {border-width:
thick;} p.length {border-width:
100px;}
p.thin1 {border-style: double; border-width: thin;}
p.medium1 {border-style: dashed; border-width: medium;}
p.thick1 {border-style: solid; border-width: thick;} p.length1
{border-style: dotted; border-width: 10px;}
</style>
</head>
<body>
<h2>border-width without <i>border-style</i> property</h2>
<p class="thin">Thin border.</p>
<p class="medium">Medium border.</p>
<p class="thick">Thick border.</p>
<p class="length">Specific length border.</p>
<h2>border-width with <i>border-style</i> property</h2>
<p class="thin1">Thin width.</p>
<p class="medium1">Medium width.</p>
<p class="thick1">Thick width.</p>
<p class="length1">Specific length width border.</p>
</body>
184
</html>

Single Side - Border Width

The property border-width can be exclusively specified for each


single-side. The same set of values can be passed to each single-side for
border-width:

 border-top-width
 border-right-width
 border-bottom-width
 border-left-width
Let us see an example:

<html>
<head>
<style>
p {border-style: solid;
border-top-width: thin;
border-right-width: thick;
border-bottom-width: medium;
border-left-width: 10px;

padding: 2em;}
</style>
</head>
<body>
<h2>border-width (single-side)</h2>
<p>Different border widths on all sides.</p>
</body>
</html>

185
CSS Borders - color Property
The border-color is the third constituent property of border. It sets the color of
the border.

 border can have one, two, three or all four values.


 If no color is specified for border, the default value is
currentcolor i.e. the foreground color.
 Any type of color value can be passed, such as RGB, RGBA, hexadecimal,
etc.
Following values can be passed to border:
Value Description

color the border will be of the color


specified

transparent the border will be transparent

inherit the parent element's value is


inherited

Declare a border-style before declaring border-color, else the border effect will
not be seen.

Let us see an example (with and without specifying border-style):

186
<html>
<head>
<style>
p.color1 {border-color: red;}
p.hexa1 {border-color: #00ff00;}
p.color2 {border-style: dashed; border-color: red;}
p.hexa2 {border-style: solid; border-color: #00ff00;}
</style>
</head>
<body>
<h2>border-color without <i>border-style</i> property</h2>

<p class="color1">Red color with name.</p>


<p class="hexa1">Green color with hexadecimal.</p>
<h2>border-color with <i>border-style</i> property</h2>
<p class="color2">Red color with name.</p>
<p class="hexa2">Green color with hexadecimal.</p>
</body>
</html>

Single Side - Border Color


The property border-color can be exclusively specified for each
single-side. The same set of values can be passed to each single-side
for border-color:

 border-top-color
 border-right-color
 border-bottom-color
 border-left-color

Let us see an example:

187
<html>
<head>
<style>
p {border-style: solid;
border-top-color: red;
border-right-color: #0000ff;
border-bottom-color: rgb(100,123,111);
border-left-color: rgba(50,123,111,0.4);
padding: 0.5in;}
</style>
</head>
<body>
<h2>Different border color on all sides</h2>
<p>Check the border colors!!!</p>
</body>
</html>

CSS - border-block
The CSS shorthand property border-block is a logical property that
defines width, style and color of both the start and end in the block
dimension at once.

188
 border-block property acts on both the start and finish in the block
dimension. The writing mode, directionality, and text orientation of
the element determine which precise physical borders are impacted.
 When the writing-mode is set to the default horizontal direction,
border-block is applied to the top and bottom borders of an
element.
 Conversely, a vertical writing-mode, applies border-block to the right and
left borders.
Possible values
 <border-width> - The width of the border.
 <border-style> - The line style of the border.
 <border-color> - The color of the border.
Constituent Properties

This property is a shorthand for the following CSS properties:

 border-block-color
 border-block-style
 border-block-width

border-block: <border-block-width> || <border-block-style> || <border-


block-color>
Applies to

Syntax

189
All the HTML elements.
CSS border-block - Basic Example
The following example demonstrates the css border-block property.

<html>
<head>
<style>
.border-demo {
width: 300px;
height: 150px;
margin: 20px;
padding: 20px;
background-color: #f0f0f0;
border-block: 5px dotted #3498db;
}
.add-demo {
font-size: 18px;
color: #111;

}
</style>
</head>
<body>
<div class="border-demo">
<p class="add-demo">This is a bordered element with padding and
background color.</p>
<p>This is an example for border-block property</p>
</div>
</body>
</html>

CSS border-block - writing-mode Property


The following example demonstrates the CSS properties border-
block with vertical writing mode.

190
<html>
<head>
<style>
.vertical-border {
writing-mode: vertical-rl;
direction: ltr;
width: 150px;
height: 250px;
margin: 50px;
padding: 20px;
background-color: #f0f0f0;
border-block: 1rem solid red;
}
.add-style {
font-size: 18px;
color: #333;
}
</style>
</head>
<body>
<div class="vertical-border">
<p class="add-style">This is a vertical bordered element with a solid
red border.</p>
</div>
</body>
</html>
CSS - Margins Property
This chapter discusses about the margins in CSS. Margins are used to
create space around an element.
They define the amount of space between an element's border and adjacent
elements.
Possible Values
Following values can be passed to each side:
Value Description

auto The margin is calculated automatically by the browser

191
length The margin is specified in px, pt, cm, etc

% The margin is specified in percentage (%) of the width of


the containing element

inheri The margin is inherited from the parent element


t
Note: Negative values are allowed to be passed as margin.

selector {
margin: top right bottom left;
}

Syntax

You can specify margins for all sides at once (top, right, bottom, left) or
set specific values for individual sides.

CSS Margins - Related Properties

You can set the margin for each side individually, which is as follows:

Property Description

margin a shorthand property that sets the margin properties


in one declaration

192
margin-top sets the top margin of the element

margin- sets the right margin of the element


right

margi
n- sets the bottom margin of the element

botto
m

margin-left sets the left margin of the element

margin- sets logical block start and end margins


block for an element.

margin- sets logical inline start and end margins


inline of an element.

CSS - Paddings Property

CSS padding is a property that is used to create spacing and add


additional space inside the boundary of an element. This chapter will
discuss about the CSS padding property.

The padding property:

193
 allows you to specify how much space should appear between the
content of an element and its border.
 It adds extra space inside the element, effectively increasing or
decreasing the distance between the content and the border.
 has a default value of 0 (zero). So if you don’t set a padding value
then no padding should appear around the element.
 Negative values are not allowed.

The order of the padding properties is important, and follows this pattern:

padding: top right bottom left

The following diagram demonstrates the various padding properties for


reference:

194
All the padding properties can have the following values:

 length value (in pixels, inches, millimeters, ems).


 percentage (%) value (in % of the width of the containing element).
 inherit value specifies that padding should be inherited from the parent
element.
Example -Simple Padding

Let us see a simple example to set padding with a single length value,
which is applied equally to all four padding sides. Here we add 5 px
195
padding on h2 element :

<!DOCTYPE html>
<html>
<head>
<title>CSS - Padding</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>

196
#myDIV {border: 2px solid;}
h2 {padding: 5px; background-color: skyblue}
</style>
</head>
<body>
<div id="myDIV">
<h2>The padding can be seen around the text.</h2>
</div>
</body>
</html>

Example - Padding and No-padding

Adding padding to an element makes it look clear and attractive.


Observe the following example for the difference between padding and
no padding:

197
<!DOCTYPE html>
<html>
<head>
<title>CSS - Padding</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
#myDIV {border: 2px solid;}
h2 {padding: 2em; background-color: skyblue}
h3 {background-color: silver;}
</style>
</head>
<body>
<div id="myDIV">
<h2>The padding can be seen around the text.</h2>
</div>
<div id="myDIV">
<h3>No padding added to the h3 element. Hence the border is
nearly touching the text.</h3>
</div>
</body>
</html>

Padding - Single-side Properties

CSS provides four separate properties to set padding for top, right, bottom, and
left for an element.

 padding-top

198
 padding-right
 padding-bottom
 padding-left

Following example shows how different padding properties can be set around an
h2 element:

<!DOCTYPE html>
<html>
<head>
<title>CSS - Padding</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
h2 {padding-top: 10px; padding-right: 20px; padding-bottom:
30px; padding-left: 40px; background-color: skyblue; border: 1px
solid;}
</style>
</head>
<body>
<div>
<h2>The different padding property values are set to the h2
element.</h2>
</div>
</body>
</html>

Padding - Shorthand Property

Padding can be set to all the sides of an element at once. The value for
padding properties can be in pixels, inches, ems, or centimeters, apart
from percentage.
199
Let us see an example for the shorthand property of padding:

<!DOCTYPE html>
<html>
<head>
<title>CSS - Padding</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>

h2 {padding: 50px 20px 30px 40px; background-color:


silver;}
</style>
</head>
<body>
<div>
<h2>The different padding property values are set to the h2
element.</h2>
</div>
</body>
</html>

Padding - Set Three Values


Three values can be passed to the padding as padding: 20px 40px 10px.
In this case top padding will be 20px, right and left paddings will be
40px and bottom padding will be 10px.

Following is the example for the same:

200
<!DOCTYPE html>
<html>
<head>
<title>CSS - Padding</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
h2 {padding: 20px 40px 10px; background-color: silver;}
</style>
</head>
<body>
<div>
<h2>The three different padding property values are set to
the h2 element.</h2>
</div>
</body>
</html>

Lesson 3: Summary Questions

1. What is CSS, and what is its primary purpose in web development?


2. Describe the difference between inline, internal, and external CSS
stylesheets.
3. How do you select HTML elements for styling using CSS
selectors? Provide examples of different types of selectors.
4. Explain the concept of specificity in CSS and how it affects the
application of styles to elements.
5. What is the box model in CSS, and how does it influence the
layout of elements on a webpage?
6. Describe the difference between margin, padding, border, and

201
content areas of an element in the box model.
7. How do you apply styles to a specific element when it has multiple
classes? Explain with an example.
8. What are pseudo-classes and pseudo-elements in CSS, and give examples
of each.
9. Describe the difference between the display: block, display: inline-
block
display: inline, and CSS properties.
10. Explain the purpose position property in CSS and describe the values static,
of the
relative, absolute,fixed
and

11. How do you create a CSS animation? Provide an example


illustrating key animation properties.
12. Describe the concept of CSS specificity and inheritance. How
does inheritance work in CSS?
13. What is the purpose of media queries in CSS, and how do they
enable responsive web design?
14. Explain the difference between em, rem, px, and % units in CSS
for defining sizes and dimensions.
15. How do you use CSS preprocessors like Sass or LESS to
enhance the capabilities of CSS? Provide an example of a
feature offered by preprocessors.

202
Lesson 4: Java script

4.1. Introduction

JavaScript is a versatile and widely-used programming language


primarily employed for developing web applications. Initially developed
by Brendan Eich at Netscape in 1995, it has since become one of the core
technologies of the World Wide Web alongside HTML and CSS. Unlike
Java, JavaScript has no relation to the Java programming language.
JavaScript is primarily a client-side scripting language, meaning it runs
on the user's web browser, enabling dynamic interaction with web pages.
It's used for tasks such as form validation, creating interactive elements
like sliders and dropdown menus, and handling asynchronous requests to
fetch data from servers without reloading the entire page.
In addition to client-side scripting, JavaScript can also be used for server-
side programming through platforms like Node.js. This allows
developers to write JavaScript code that runs on the server, enabling full-
stack development with a single programming language.
JavaScript is a high-level, interpreted language with dynamic typing,
meaning variable types are determined at runtime rather than compile-
time. It supports object-oriented, imperative, and functional
programming paradigms, providing developers with a wide range of tools
and techniques for building complex applications.
Lesson 1: Understanding JavaScript
203
 Objective: To introduce students to JavaScript as a programming
language and its role in web development.

Evolution of JavaScript

1. Creation of JavaScript (1995)


 JavaScript was created by Brendan Eich in 1995 while he was
working at Netscape Communications Corporation.
 Originally named Mocha, it was later renamed to LiveScript, and
finally JavaScript due to a partnership with Sun Microsystems.
2. Introduction of ECMAScript (1997)
 JavaScript was submitted to the European Computer
Manufacturers Association (ECMA) for standardization.
 ECMAScript, the standardized specification for JavaScript, was
released as ECMA-262 in June 1997.
 ECMAScript 1 laid the foundation for the language, defining its
syntax, data types, and basic functionality.
3. ECMAScript 3 (1999)
 Significant update to the ECMAScript specification, introducing
new features such as regular expressions, try/catch exception
handling, and switch statement improvements.

204
 This version of ECMAScript was widely adopted and formed
the basis of JavaScript implementations in major web browsers.
4. ECMAScript 4 (Abandoned)
 Development of ECMAScript 4 began but was eventually
abandoned due to disagreements among stakeholders regarding
the proposed features and complexity.
 Instead of releasing ECMAScript 4, the ECMAScript committee
decided to focus on smaller, incremental updates.
5. ECMAScript 5 (2009)
 Released in December 2009, ECMAScript 5 introduced
significant enhancements and improvements to the language.
 New features included strict mode, which provided better error
handling and improved security, as well as array methods like
forEach, map, filter, and reduce.
 ECMAScript 5 was widely adopted and is still supported by all modern
web browsers.
6. ECMAScript 6 (ES2015)
 Released in June 2015, ECMAScript 6, also known as ES6 or
ES2015, was a major milestone in the evolution of JavaScript.
 ES6 introduced many new features and syntax enhancements,
including let and const for variable declaration, arrow functions,
template literals, classes, and modules.
 It also introduced new data structures like Map, Set, and symbols,
as well as promises for asynchronous programming.
205
 ECMAScript 6 aimed to make JavaScript code more
readable, maintainable, and expressive.
7. Subsequent ECMAScript Versions
 Following the release of ECMAScript 6, the ECMAScript
specification adopted a yearly release cycle, with new versions
introduced annually.
 Subsequent versions, including ECMAScript 7 (ES2016),
ECMAScript 8 (ES2017), ECMAScript 9 (ES2018),
ECMAScript 10 (ES2019), ECMAScript 11 (ES2020), and
ECMAScript 12 (ES2021), introduced additional features, syntax
enhancements, and improvements to the language.
 These updates focused on enhancing developer productivity,
improving performance, and addressing pain points in JavaScript
development.
8. Latest Version: ECMAScript 13 (ES2022)
 ECMAScript 13, also known as ES2022, is the latest version of
the ECMAScript specification.
 Released in June 2022, ES2022 introduces new features such as
class fields, private methods and accessors, extended numeric
separators, and more.
 It continues the tradition of improving JavaScript by adding new
capabilities and refining existing features to meet the needs of
modern web development.

206
The evolution of JavaScript, guided by the ECMAScript specification,
has transformed it from a simple scripting language to a powerful,
versatile, and widely-used programming language that powers the
modern web.

4.2. JavaScript Vs HTML, and CSS

JavaScript, HTML, and CSS are fundamental technologies in web


development, each serving distinct yet interconnected roles in creating
dynamic and visually appealing web applications. While HTML
(Hypertext Markup Language) provides the structural backbone of web
pages, defining elements and their arrangement, CSS (Cascading Style
Sheets) enhances the presentation by styling and formatting these
elements. In contrast, JavaScript adds interactivity and dynamic behavior
to web pages, enabling features like form validation, DOM manipulation,
and asynchronous communication with servers.

Comparison:

 Client-side vs. Server-side: JavaScript is primarily known as a


client-side programming language, meaning it is executed on the
client's web browser rather than on the server. However, with the
introduction of technologies like Node.js, JavaScript can also be
used for server-side programming like PHP. Node.js allows
207
developers to run JavaScript code on the server, enabling full-stack
development with a single language. Therefore, while JavaScript's
origins lie in client-side scripting, its versatility extends to server-
side programming as well.
 Role: HTML provides the structure and content, CSS styles the
presentation, JavaScript adds interactivity, and PHP handles server-
side logic and data processing.
 Integration: JavaScript can be embedded directly within HTML
files or included as external script files. CSS is also included within
HTML files or linked externally. PHP code is typically embedded
within HTML files and executed on the server before being sent to
the client.
 Dynamic vs. Static: JavaScript and PHP allow for dynamic content
generation, while HTML and CSS primarily define static content
and presentation.

4.3. JavaScript variables


JavaScript variables are containers for storing data values. Unlike other
programming languages, JavaScript is dynamically typed, meaning you
don't have to declare the data type of a variable when you create it. Here's
a detailed discussion of JavaScript variables:

Declaration and Initialization:


208
 var: The traditional way of declaring variables in JavaScript. e.g:
var x; // Declaration
x = 10; // Initialization

let y; // Declaration
y = 'Hello'; // Initialization
 let: Introduced in ES6, let allows block-scoped variables that can be
reassigned. e.g:
 const: Also introduced in ES6, const declares variables with a
constant (unchanging) value. They must be initialized when
declared and cannot be reassigned. Example:
const PI = 3.14; // Declaration and initialization

Dynamic Typing:

 JavaScript variables can hold values of any data type, and the data
type of a variable can change at runtime. Example:
var dynamicVar;
dynamicVar = 10; // Number
dynamicVar = 'Hello'; // String
dynamicVar = true; // Boolean

Naming Conventions:

 Variables can include letters, digits, underscores, and dollar signs.


They must begin with a letter, underscore, or dollar sign (not a

209
digit).
 Variable names are case-sensitive.

var myVariable;
var firstName;
var numStudents;
 It's recommended to use camelCase for variable names to improve
readability. Example:

Best Practices:

 Use const for variables that won't be reassigned.


 Use let for variables that may be reassigned.
 Avoid using var due to its function scope and hoisting behavior.
 Always declare variables before using them to avoid
unexpected behavior. JavaScript Datatypes
JavaScript supports several data types, which can be broadly
categorized into primitive and reference types.

Primitive Data Types:

1. Number: Represents numeric values, including integers and floating-point


numbers.

210
let num = 10;
let floatNum = 3.14;

let str = 'Hello';


2.String: Represents sequences of characters enclosed within single or double
quotes.

let isTrue = true;


let isFalse = false;
2. Boolean: Represents logical values true or false.

3. Undefined: Represents a variable that has been declared but not assigned a
value.

let x;
console.log(x); // Output: undefined

4. Null: Represents an intentional absence of any object value.


let y = null;

5. Symbol: Introduced in ES6, represents unique identifiers.


Symbols are immutable and can be used as property keys in
objects.
const sym = Symbol('description');

Reference Data Types:

1. Object: Represents a collection of key-value pairs where values can be


211
primitive types, other objects, or functions
let obj = {
name: 'John',
age: 30,
isAdmin: false
};

let arr = [1, 2, 3, 4];


2. Array: Represents an ordered collection of elements, indexed by non-
negative integers.
3. Function: Represents a reusable block of code that performs a specific task.
function greet(name) {
return 'Hello, ' + name + '!';
}

let today = new Date();


4. Date: Represents a specific point in time, with methods for working with
dates and times.
5. RegExp: Represents regular expressions, used for pattern matching within
strings.
let pattern = /[a-zA-Z]+/;

212
Special Data Types:

let result = 'Hello' / 2;


console.log(result); // Output: NaN
1. NaN (Not a Number): Represents a value that is not a valid number.
2. Infinity and -Infinity: Represent positive and negative infinity,
respectively.
let positiveInfinity = Infinity;
let negativeInfinity = -Infinity;

JavaScript Operators
JavaScript operators are symbols that perform operations on operands
(values or variables). They can be categorized into several types based on
their functionality. Here's a detailed discussion of JavaScript operators:

Arithmetic Operators:

Arithmetic operators perform mathematical calculations on numeric operands.


 Addition (+): Adds two operands.
 Subtraction (-): Subtracts the second operand from the first.
 Multiplication (*): Multiplies two operands.
 Division (/): Divides the first operand by the second.
 Modulus (%): Returns the remainder of the division of the first operand by
the second.

213
Assignment Operators:

Assignment operators assign values to variables.


 Assignment (=): Assigns the value of the right operand to the left operand.
 Addition Assignment (+=): Adds the value of the right operand
to the left operand and assigns the result to the left operand.
 Subtraction Assignment (-=): Subtracts the value of the right
operand from the left operand and assigns the result to the left
operand.
 Multiplication Assignment (*=): Multiplies the value of the left
operand by the value of the right operand and assigns the result to
the left operand.
 Division Assignment (/=): Divides the value of the left operand
by the value of the right operand and assigns the result to the left
operand.

Comparison Operators:

Comparison operators compare two values and return a Boolean result (true or
false).
 Equal (==): Checks if two operands are equal in value, but not necessarily
in type.
 Strict Equal (===): Checks if two operands are equal in value and type.
 Not Equal (!=): Checks if two operands are not equal in value.
214
 Strict Not Equal (!==): Checks if two operands are not equal in value or
type.
 Greater Than (>): Checks if the left operand is greater than the right
operand.
 Less Than (<): Checks if the left operand is less than the right operand.
 Greater Than or Equal To (>=): Checks if the left operand is
greater than or equal to the right operand.
 Less Than or Equal To (<=): Checks if the left operand is less
than or equal to the right operand.

Logical Operators:

Logical operators perform logical operations on Boolean operands.


 Logical AND (&&): Returns true if both operands are true.
 Logical OR (||): Returns true if at least one of the operands is true.
 Logical NOT (!): Returns true if the operand is false and vice versa.

Unary Operators:

Unary operators operate on a single operand.


 Unary Plus (+): Converts its operand into a number.
 Unary Negation (-): Negates its operand.
 Increment (++): Increases the value of its operand by 1.

215
 Decrement (--): Decreases the value of its operand by 1.

Conditional (Ternary) Operator:

The conditional operator (?:) is the only ternary operator in JavaScript.


 Conditional Operator (?:): Evaluates a condition and returns one
of two expressions based on whether the condition is true or false.
Bitwise Operators:
Bitwise operators perform bitwise operations on integer operands.
 Bitwise AND (&): Performs a bitwise AND operation.
 Bitwise OR (|): Performs a bitwise OR operation.
 Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation.
 Bitwise NOT (~): Inverts the bits of its operand.
 Left Shift (<<): Shifts the bits of the left operand to the left by the
number of positions specified by the right operand.
 Right Shift (>>): Shifts the bits of the left operand to the right by
the number of positions specified by the right operand.

216
 Unsigned Right Shift (>>>): Shifts the bits of the left operand to
the right by the number of positions specified by the right operand,
filling the leftmost positions with zeros.

Java script Control Statements:

JavaScript control statements are statements that enable developers to


control the flow of execution within their programs. They include
conditional statements, loops, and other structures that determine which
statements should be executed under certain conditions. Here's a detailed
discussion of JavaScript control structures:

Conditional Statements:

Conditional statements allow you to execute different blocks of code


based on specified conditions.
if Statement: Executes a block of code if a specified condition is true.
if (condition) {
// code block
}

if...else Statement: Executes one block of code if a specified condition


is true and another block
if (condition) { if it's false.
// code block
} else {
// code block
}

217
if (condition1) {
// code block
} else if (condition2) {
// code block
} else {
// code block
}
if...else if...else Statement: Executes different blocks of code for different
conditions.
switch Statement: Evaluates an expression and executes a block of code
based on matching case labels.
switch (expression) {
case value1:
// code block
break;
case value2:
// code block

218
break;
default:
// code block
}

Loop Statements:

Loop statements allow you to execute a block of code repeatedly as long


as a specified condition is true.

for (initialization; condition; increment) {


// code block
}
 for Loop: Executes a block of code a specified number of times
while Loop: Executes a block of code while a specified condition is true.
while (condition) {
// code block
}

do...while Loop: Executes a block of code once before checking if the


condition isdotrue,
{ then repeats the loop as long as the condition is true.
// code block
} while (condition);

for (variable in object) {


// code block
}
for...in Loop: Iterates over the enumerable properties of an object
for...of Loop: Iterates over iterable objects such as arrays, strings, and
collections.
219
for (variable of iterable) {
// code block
}

Other Control Structures:

 break Statement: Terminates the current loop or switch


statement and transfers control to the statement immediately
following the loop or switch.
 continue Statement: Skips the current iteration of a loop and
continues with the next iteration.
 return Statement: Exits the current function and returns a value to the
caller.
 try...catch Statement: Executes a block of code and catches any
exceptions that occur within that block.
 throw Statement: Throws an exception explicitly.

220
Lesson 3: Functions
 Objective: To teach students how to define and use functions in JavaScript.

Java script functions

JavaScript functions are blocks of code designed to perform a specific


task or calculate a value. They are a fundamental building block of
JavaScript programming and can be used to organize and reuse code
efficiently. Here's a detailed discussion of JavaScript functions:

i. Function Declaration:

A function declaration defines a named function using the function


keyword. It typically consists of:

 The function keyword followed by the function name.


 Optional parameters enclosed in parentheses.
 The function body enclosed in curly braces.
 Optionally, a return statement to specify the value that the
function should return. e.g.
function greet(name) {
return 'Hello, ' + name + '!';
}

221
ii. Function Expression:

A function expression defines a function as part of a larger expression,


such as assigning it to a variable. It's often used when a function is
assigned to a variable, passed as an argument to another function, or used
as an immediately-invoked function expression (IIFE). e.g:

let greet = function(name) {


return 'Hello, ' + name + '!';
};

iii. Arrow Function:

Introduced in ES6, arrow functions provide a concise syntax for writing


anonymous functions. They are especially useful for short, single-
expression functions and maintain the this context from the enclosing
scope. e.g:

222
let greet = (name) => {
return 'Hello, ' + name + '!';
};

iv. Anonymous Function:

An anonymous function is a function without a name. It's often used in


function expressions or as callback functions.

let greet = function(name) {


return 'Hello, ' + name + '!';
};

v. Function Parameters:

Functions can accept parameters, which are variables that represent


values passed to the function when it is called. Parameters are listed
within the parentheses of the function declaration.

function greet(name) {
return 'Hello, ' + name + '!';
}
console.log(greet('John')); // Output: Hello, John!

Return Statement:

The return statement is used to specify the value that a function


223
should return. It ends the function's execution and returns the specified
value to the caller.

function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Output: 8

vi. Function Invocation:

Functions are invoked (called) using their name followed by


parentheses containing any arguments. This triggers the execution of
the function's code.

function greet(name) {
return 'Hello, ' + name + '!';

224
}
console.log(greet('Alice')); // Output: Hello, Alice!

vii. Function Scope:

Variables declared inside a function are scoped to that function and


are not accessible from outside. This is known as function scope.

function test() {
let x = 10;
console.log(x); // Output: 10
}
console.log(x); // Error: x is not defined

viii. Function Hoisting:

Function declarations are hoisted to the top of their containing scope,


allowing them to be called before they are declared.

console.log(add(2, 3)); // Output: 5


function add(a, b) {
return a + b;
}

ix. Recursive Function:

A recursive function is a function that calls itself, often used for tasks
that can be broken down into smaller, similar subtasks. It's crucial to
have a base case to prevent infinite recursion.
225
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120

x. Callback Function:

A callback function is a function passed as an argument to another


function, which is then invoked inside the outer function. This is often
used in asynchronous programming and event handling.

226
function process(callback) {
callback();
}
function greet() {
console.log('Hello!');
}
process(greet); // Output: Hello!

Function Parameters and Arguments:

Parameters are the variables listed inside the parentheses of a function


declaration, while arguments are the values passed to the function when
it is invoked. Parameters and arguments enable the passing of data into
functions.

function add(a, b) {
return a + b;
}
console.log(add(3, 4)); // Arguments: 3, 4 | Output: 7

JavaScript Scope of functions


The scope of a function in JavaScript refers to the accessibility and
visibility of variables and functions within that function. Understanding
function scope is crucial for writing maintainable and predictable code.
Here's a detailed discussion of function scope in JavaScript:

Global Scope:

Variables declared outside of any function have global scope, meaning


227
they can be accessed from anywhere in the code, including within
functions.
let globalVar = 'I am global';

function test() {
console.log(globalVar); // Output: I am global
}

test();

Local Scope:

Variables declared inside a function have local scope, meaning they are
accessible only within that function. They are not visible outside of the
function.

228
function test() {
let localVar = 'I am local';
console.log(localVar); // Output: I am local
}

test();
console.log(localVar); // Error: localVar is not defined

Function Scope:

JavaScript uses function scope, meaning that var within a function are
variables declared with scoped to that function.
They are not visible outside of the function.

function test() {
var localVar = 'I am function-scoped';
console.log(localVar); // Output: I am function-scoped
}

test();
console.log(localVar); // Error: localVar is not defined

Block Scope (with let and const):

Introduced in an allow for block-scoped variables. Variables declared


ES6, d with

let const let


or const within a block (such as within curly braces {}) are scoped to that block
and are not

229
if (true) {
let blockVar = 'I am block-scoped';
console.log(blockVar); // Output: I am block-scoped
}

console.log(blockVar); // Error: blockVar is not defined


visible outside of it.

Lexical Scope:

JavaScript has lexical scope, meaning that the visibility of variables is


determined by their location in the source code. Functions can access
variables defined in their outer scope, but not vice versa.
function outer() {
let outerVar = 'I am outer';

function inner() {

230
console.log(outerVar); // Output: I am outer
}

inner();
}

outer();
console.log(outerVar); // Error: outerVar is not defined

Closure:

A closure is a combination of a function and the lexical environment


within which that function was declared. Closures allow functions to
retain access to variables from their enclosing scope even after the outer
function has finished executing.

function outer() {
let outerVar = 'I am outer';

function inner() {
console.log(outerVar); // Output: I am outer
}

return inner;
}

let closureFunc = outer();


closureFunc();

231
Summary Questions

Introduction to Web Development and Web Protocols:

1. What is the fundamental difference between client-side and server-side


scripting?
2. Explain the role of HTTP in web development and how it
facilitates communication between clients and servers.
3. What is DNS (Domain Name System) and how does it work
in the context of web development?
4. Define SSL/TLS and explain its importance in securing web
communication.
5. Describe the purpose of HTTP headers and provide examples of common
header fields.
6. What is the key difference between HTTP and HTTPS, and why
is HTTPS considered more secure?
7. Explain the significance of RESTful APIs in web development and
give examples of how they are used.
8. What is a cookie in web development, and how is it used to store user data?
9. Differentiate between stateful and stateless communication
in web development, providing examples of each.
10. Discuss the role of web standards bodies like W3C and
WHATWG in shaping the landscape of web development.

232
HTML:

1. What is HTML and what is its role in web development?


2. Differentiate between HTML elements and HTML attributes,
providing examples of each.
3. Explain the purpose of semantic HTML and provide examples of semantic
elements.
4. What is the key difference between HTML4 and HTML5?
5. Describe the structure of an HTML document, including the essential
elements.
6. What is the purpose of the <div> and <span> elements in
HTML, and how do they differ?
7. Explain the significance of the <meta> tag in HTML and provide examples
of its usage.
8. Discuss the role of HTML forms in web development and
provide examples of form elements.
9. What is the HTML5 canvas element, and how is it used in web
development?
10. Describe the purpose of HTML entities and provide examples of commonly
used entities.

CSS:

1. What is CSS, and what is its role in web development?


233
2. Differentiate between inline, internal, and external CSS, providing
examples of each.
3. Explain the box model in CSS and how it influences the layout
of elements on a web page.
4. Describe the difference between classes and IDs in CSS, and when you
would use each.
5. What are CSS selectors, and how are they used to target HTML elements
for styling?

234
6. Discuss the purpose of CSS preprocessors like Sass
and LESS, and provide examples of their features.
7. Explain the concept of CSS specificity and how it
determines which styles apply to an element.
8. Describe the difference between absolute and relative
positioning in CSS.
9. What are CSS frameworks, and how do they simplify the
process of styling web pages?
10. Discuss the role of media queries in responsive web
design and provide examples of their usage.

JavaScript:

1. What is JavaScript, and what is its role in web development?


2. Explain the difference between JavaScript and Java.
3. Describe the purpose of variables in
JavaScript and provide examples of variable
declarations.
4. What are data types in JavaScript, and how are they
classified?
5. Discuss the concept of scope in JavaScript and how it affects
variable accessibility.
6. Explain the difference between == and === operators in

Tinsae D@2024 Internet and web design


JavaScript.
7. Describe the purpose of functions in JavaScript
and provide examples of function declarations
and expressions.
8. What are JavaScript events, and how are they used to create
interactive web pages?
9. Discuss the role of AJAX in web
development and how it enables
asynchronous communication with servers.
10. Explain the concept of closures in JavaScript and provide
examples of their usage.

Tinsae D@2024 Internet and web design

You might also like