You are on page 1of 101

Unit I

What is a Browser?
A browser is a software program that is used to explore, retrieve, and display the information available on the
World Wide Web. This information may be in the form of pictures, web pages, videos, and other files that all are
connected via hyperlinks and categorized with the help of URLs (Uniform Resource Identifiers). For example, you
are viewing this page by using a browser.

A browser is a client program as it runs on a user computer or mobile device and contacts the webserver for the
information requested by the user. The web server sends the data back to the browser that displays the results on
internet supported devices. On behalf of the users, the browser sends requests to web servers all over the internet
by using HTTP (Hypertext Transfer Protocol). A browser requires a smartphone, computer, or tablet and
internet to work.
History of Web Browser
o The WorldWideWeb was the first web browser. It was created by W3C Director Tim Berners-Lee
in 1990. Later, it was renamed Nexus to avoid confusion caused by the actual World Wide Web.
o The Lynx browser was a text-based browser, which was invented in 1992. It was not able to display the
graphical content.
o Although, the first graphical user interface browser was NCSA Mosaic. It was the first most popular
browser in the world, which was introduced in 1993.
o In 1994, there were some improvements occurred in Mosaic and came to Netscape Navigator.
o In 1995, Microsoft introduced the Internet Explorer It was the first web browser developed by Microsoft.
o A research project started on Opera in 1994. Later, it was publicly introduced in 1996.
o Apple's Safari browser was introduced in 2003. It was specifically released for Macintosh computers.
o In 2004, Mozilla introduced Firefox as Netscape Navigator.
o In 2007, a browser Mobile Safari was released as Apple mobile web browser.
o The popular browser Google Chrome was launched in 2008.
o The fast-growing mobile-based browser Opera Mini was released in 2011.
o The Microsoft Edge browser was launched in 2015.

Features of Web Browser


Most Web browsers offer common features such as:
1. Refresh button: Refresh button allows the website to reload the contents of the web pages. Most of the
web browsers store local copies of visited pages to enhance the performance by using a caching
mechanism. Sometimes, it stops you from seeing the updated information; in this case, by clicking on the
refresh button, you can see the updated information.
2. Stop button: It is used to cancel the communication of the web browser with the server and stops loading
the page content. For example, if any malicious site enters the browser accidentally, it helps to save from it
by clicking on the stop button.
3. Home button: It provides users the option to bring up the predefined home page of the website.
4. Web address bar: It allows the users to enter a web address in the address bar and visit the website.
5. Tabbed browsing: It provides users the option to open multiple websites on a single window. It helps
users to read different websites at the same time. For example, when you search for anything on the
browser, it provides you a list of search results for your query. You can open all the results by right-
clicking on each link, staying on the same page.
6. Bookmarks: It allows the users to select particular website to save it for the later retrieval of information,
which is predefined by the users.
What is the URL (Uniform Resource Locator)?
A uniform resource locator is the address of a resource on the internet or the World Wide Web. It is also known
as a web address or uniform resource identifier (URI). For example, https: www.javatpoint.com, which is the
URL or web address for the javatpoint
website. A URL represents the address of a resource, including the protocol used to access it.
A URL includes the following information:
o It uses the protocol to access the resource.
o It defines the location of a server by IP address or the domain name.
o It includes a fragment identifier, which is optional.
o It contains the location of the resource in the directory of the server.
Component of a Web browser

The primary components of a browser are shown in the below image:

1. User Interface: The user interface is an area where the user can use several options like address bar, back
and forward button, menu, bookmarking, and many other options to interact with the browser.
2. Browser Engine: It connects the UI (User Interface) and the rendering engine as a bridge. It queries and
manipulates the rendering engine based on inputs from several user interfaces.
3. Rendering Engine: It is responsible for displaying the requested content on the browser screen. It
translates the HTML, XML files, and images, which are formatted by using the CSS. It generates the
layout of the content and displays it on the browser screen. Although it can also display the other types of
content by using different types of plugins or extensions. such as:
o Internet Explorer uses Trident
o Chrome & Opera 15+ use Blink
o Chrome (iPhone) & Safari use Webkit
o Firefox & other Mozilla browsers use Gecko
4. Networking: It retrieves the URLs by using internet protocols like HTTP or FTP. It is responsible for
maintaining all aspects of Internet communication and security. Furthermore, it may be used to cache a
retrieved document to reduce network traffic.
5. JavaScript Interpreter: As the name suggests, JavaScript Interpreter translates and executes the
JavaScript code, which is included in a website. The translated results are sent to the rendering engine to
display results on the device screen.
6. UI Backend: It is used to draw basic combo boxes and Windows (widgets). It specifies a generic
interface, which is not platform-specific.
7. Data Storage: The data storage is a persistence layer that is used by the browser to store all sorts of
information locally, like cookies. A browser also supports different storage mechanisms such as
IndexedDB, WebSQL, localStorage, and FileSystem. It is a database stored on the local drive of your
computer where the browser is installed. It handles user data like cache, bookmarks, cookies, and
preferences.
How does a browser work?
When a user enters a web address or URL in the search bar like javatpoint.com, the request is passed to a domain
name servers (DNS). All of these requests are routed via several routers and switches.
The domain name servers hold a list of system names and their corresponding IP addresses. Thus, when you type
something in the browser search bar, it gets converted into a number that determines the computers to which the
search results are to be displayed.
The browser acts as a part of the client-server model. A browser is a client program that sends the request to the
server in response to the user search queries by using Hypertext Transfer Protocol or HTTP. When the server
receives the request, it collects information about the requested document and forwards the information back to the
browser. Thereafter, the browser translates and displays the information on the user device.
Popular Types of Browsers
Firefox
Firefox is a very popular web browser. One of the great things about Firefox is that it is supported on all different
OSs. Firefox is also open source which makes its support group a very large community of open source developers.
Firefox is also known for its vast range of plugins/add-ons that let the user customize in a variety of ways. Firefox is a
product of the Mozilla Foundation. The latest version of Firefox is Firefox 3. Some of Firefox’s most prominant
features include: tabbed browsing, a spell checker, incremental find, live bookmarking, a download manager, and an
integrated search system that uses the user’s favorite search engine.
Internet Explorer
Internet Explorer (IE - created by Microsoft) is a very prominant web browser for the Windows OS. IE is the most
popular web browser. It comes pre-installed on all Windows computers. The latest version of IE is IE7 with IE8 in
beta. IE was designed to view a broad range of web pages and to provide certain features within the OS.IE almost
fully supports HTML 4.01, CSS Level 1, XML 1.0, and DOM Level 1. It has introduced a number of proprietary
extensions to many of the standards. This has resulted in a number of web pages that can only be viewed properly
using IE.
Microsoft Edge:
Microsoft Edge is a web browser that comes pre-installed with Windows 10 operating system and Windows
Server 2016. It was introduced to replace the Internet Explorer Web browser, and its code name was Spartan. It
offers various types of features such as freestyle writing over Web page displays, refined search, and presentations
for e-books and other reading resources.
Microsoft Edge was developed under the Spartan codename Project. In April 2015, Microsoft changed the project
Spartan name as Microsoft Edge. Although Internet Explorer and Edge are included with Windows 10, Edge act as
a default browser. It combines new web technology evaluations and enhances the speed of browsing.
Google Chrome:
It is an open-source and the most popular internet browser that is used for accessing the information available on
the World Wide Web. It was developed by Google on 11 December 2008 for Windows, Linux, Mac OS X,
Android, and iOS operating systems. It uses sandboxing-based approach to provide Web security. Furthermore, it
also supports web standards like HTML5 and CSS (cascading style sheet).
Google Chrome was the first web browser that has a feature to combine the search box and address bar, that was
adopted by most competitors. In 2010, Google introduced the Chrome Web Store, where users can buy and install
Web-based applications.

Opera:
An Opera web browser was first conceived at Telenor company in 1994, later bought by the Opera Software on 1
April 1995. It was designed for desktop and mobile interfaces, but it is more popular now for mobile phones. It is
based on Chromium, and it uses the blink layout engine. An opera mini was released for smartphones on 10
August 2005 that could run standard web browsers. It can be downloaded from the google play store or Apple play
store.
Apple Safari:
Safari is an internet browser available for the Macintosh, and Windows operating systems included the iPhone,
iPad, and iPod Touch. It was developed by Apple, Inc. on 30 June 2003. It is the default browser for the operating
system in its products, such as OS X for the MacBook and Mac computers and iOS for the iPad and iPhone mobile
devices. It is at number four in the browser market after Microsoft Internet Explorer, Mozilla Firefox, and Google
Chrome. It uses the WebKit engine, which is used for rendering fonts, displays graphics, determining page layout,
and running JavaScript.
Web Servers

Web pages are a collection of data, including images, text files, hyperlinks, database files etc., all located
on some computer (also known as server space) on the Internet. A web server is dedicated software that
runs on the server-side. When any user requests their web browser to run any web page, the webserver
places all the data materials together into an organized web page and forwards them back to the web
browser with the help of the Internet. Therefore, we can conclude that: -
A web server is a dedicated computer responsible for running websites sitting out on those computers somewhere
on the Internet. They are specialized programs that circulate web pages as summoned by the user. The primary
objective of any web server is to collect, process and provide web pages to the users.

This intercommunication of a web server with a web browser is done with the help of a protocol
named HTTP (Hypertext Transfer Protocol). These stored web pages mostly use static content,
containing HTML documents, images, style sheets, text files, etc. However, web servers can serve
static as well as dynamic contents. Web Servers also assists in emailing services and storing files.
Therefore it also uses SMTP (Simple Mail Transfer Protocol) and FTP (File Transfer Protocol) protocols
to support the respective services. Web servers are mainly used in web hosting or hosting the website's
data and running web-based applications.

The hardware of the web servers are connected to the Internet that manages the data exchange facility
within different connected devices. In contrast, the software of web server software is responsible for
controlling how a user accesses delivered files. Typically, web server management is an ideal example of
the client/server model. Therefore, it is compulsory for all computers that host websites (whether
with state or dynamic web page content) to have web server software.

How do web servers work?


The term web server can denote server hardware or server software, or in most cases, both hardware
and software might be working together.

1. On the hardware side, a web server is defined as a computer that stores software and another website raw
data, such as HTML files, images, text documents, and JavaScript files. The hardware of the web servers
are connected to the web and supports the data exchange with different devices connected to the Internet.
2. On the software side, a web server includes server software accessed through website domain names. It
controls how web users access the web files and ensures the supply of website content to the end-user. The
web server contains several components, including an HTTP server.

Whenever any web browser, such as Google Chrome, Microsoft Edge or Firefox, requests for a web page hosted
on a web server, the browser will process the request forward with the help of HTTP. At the server end, when it
receives the request, the HTTP server will accept the request and immediately start looking for the requested data
and forwards it back to the web browser via HTTP.

Let's discover the step-by-step process of what happens whenever a web browser approaches the web server and
requests a web file or file. Follow the below steps:

1. First, any web user is required to type the URL of the web page in the address bar of your web browser.
2. With the help of the URL, your web browser will fetch the IP address of your domain name either by
converting the URL via DNS (Domain Name System) or by looking for the IP in cache memory. The IP
address will direct your browser to the web server.
3. After making the connection, the web browser will request for the web page from the web server with
the help of an HTTP request.
4. As soon as the web server receives this request, it immediately responds by sending back the requested
page or file to the web browser HTTP.
5. If the web page requested by the browser does not exist or if there occurs some error in the process,
the web server will return an error message.
6. If there occurs no error, the browser will successfully display the webpage.

NOTE: A single web server can host multiple domains as well.


Examples of web server uses
Web servers are mostly used for:
o sending and receiving mails on Internet by using SMTP (Simple Mail transfer Protocol);
o fetching requests for File Transfer Protocol (FTP) files; and
o designing, developing, and publishing websites.
Many Web servers, even the basic one, also support the server-side scripting technique. Server-side scripting is a
web development method used to employ scripts on a web server that produces a customized response for each
user. This technique operates on the server machine and consists of an extensive feature set, including database
access. The server-side scripting process will have various scripting languages
such ASP, PHP, Java, JavaScript, Python, ruby and many more. This technique also enables the HTML files to be
created dynamically.
Static web servers vs. Dynamic web servers:
A web server can be used to store, process or deliver either static or dynamic web pages. Let's
understands the definition of static and dynamic web servers with the help of their difference table given
below:
S.NO. Static Web Servers Dynamic Web Servers

1 Static web servers refer to the servers, Dynamic web servers refer to the servers
which serve only the static content i.e., the where the content of the page can be updated
content is fixed and being shown as it is. and altered.

2 A static web server includes a computer A dynamic web server also includes a
and the HTTP (Hyper Text Transfer computer with plenty of other software, unlike
Protocol) software. an application server and database model.

3 It is called static; the web pages content It is called dynamic because the application
won't change unless the user manually server is used to update the web pages files at
changes it, and the server will deliver web the server-side, and due to which, it can
files as is to the web browser. change on every call requested by the web
browser.

4 Static web servers take less time to load the The Dynamic web server can only produce the
data. data when it is requested from the database.
Therefore, it is time consuming and more
complicated when compared to static web
servers.

Web server software available in the market


Though there are various web servers found in today's market, but the commonly used one are as follows:

S.NO Web Server Description


1. Apache HTTP Server
This web server is developed by Apache Software Foundation. It is an open-source,
accessible web server available for almost all operating systems, including Windows,
MACOS, Linus, FreeBSD, etc. Apache is one of the most popular web servers used around
the globe.

2. Microsoft Internet Information Services (IIS)


IIS is a high-performance web server that is developed by Microsoft only for Microsoft
platforms. This webs server is tightly integrated with Microsoft operating system; therefore, it
is not open-sourced.

3. Nginx
Nginx is an open-source web server commonly used by administrators as it supports light
resource application and scalability.

4. Lighttpd
Lighttpd, also known as lighty, is a free, open-source web server with the FreeBSD operating
system. This web server is fast, secure and consumes much less CPU power. It can also run
on the commonly used operating system, unlike Windows, Mac OS X, Linus.

5. Sun Java System Web Server


Sun Java is a free web server developed by Sun Microsystems well equipped for a medium
and large website that can run on Windows, Linux and Unix. Moreover, this web server
supports several languages, scripts and technologies essential for Web 2.0, unlike JSP, Java
Servlets, PHP, Python, HTML, etc. Though Sun Java is free, it is not an open-source web
server.

Web server security Methods


Though there are various security techniques available in the market that a user can implement to have a safe web
server experience, below given are some examples of security practices that can include processes:

1. A reverse proxy is a proxy server that is accessible to the clients, therefore hiding the internal server. It
acts as an intermediary as wherever any user makes requests to the web server for any data or file, the
proxy server seizes those requests and then communicates with the webserver.
2. Access restriction is a technique that limits the web host's access to infrastructure machines or using
Secure Socket Shell (SSH);
3. Keeping web servers mended and updated, as it benefits to ensure the web server isn't vulnerable to
exposures;
4. Network monitoring is a security practice that ensures that no unauthorized activity is going on the web
server; and
5. Using a firewall and SSL safeguards the web server as firewalls can supervise HTTP request traffic hile
a Secure Sockets Layer (SSL) supports securing the data.

Client side and server side Processing:


Client side and server side are web development terms that describe where application code runs. Web developers
will also refer to this distinction as the frontend vs. the backend, although client-side/server-side and
frontend/backend aren't quite the same. In a serverless architecture
, the serverless vendor hosts and assigns resources to all server-side processes, and the processes scale up as
application usage increases.
What is the client-server model?
Much of the Internet is based on the client-server model. In this model, user devices communicate via a network
with centrally located servers to get the data they need, instead of communicating with each other. End user
devices such as laptops, smartphones, and desktop computers are considered to be 'clients' of the servers, as if they
were customers obtaining services from a company. Client devices send requests to the servers for webpages or
applications, and the servers serve up responses.
The client-server model is used because servers are typically more powerful and more reliable than user devices.
They also are constantly maintained and kept in controlled environments to make sure they're always on and
available; although individual servers may go down, there are usually other servers backing them up. Meanwhile,
users can turn their devices on and off, or lose or break their devices, and it should not impact Internet service for
other users.

Servers can serve multiple client devices at once, and each client device sends requests to multiple servers in the
course of accessing and browsing the Internet.

Multiple clients and servers interact:

Each client will communicate with multiple servers, and vice versa.

Suppose a user is browsing the Internet and types 'netflix.com' into their browser bar. This results in a request
to DNS servers for the IP address of netflix.com, and the DNS servers respond to this request by serving the IP
address to the browser. Next, the user's browser makes a request to Netflix servers (using the IP address) for the
content that appears on the page, such as the movie thumbnail images, the Netflix logo, and the search bar. Netflix
servers deliver this to the browser, and the browser loads the page on the client device.

What does client side mean?


In web development, 'client side' refers to everything in a web application that is displayed or takes place on the
client (end user device). This includes what the user sees, such as text, images, and the rest of the UI, along with
any actions that an application performs within the user's browser.
Markup languages like HTML and CSS are interpreted by the browser on the client side. In addition, many
contemporary developers are including client-side processes in their application architecture and moving away
from doing everything on the server side; business logic for dynamic webpages*, for instance, usually runs client
side in a modern web application. Client-side processes are almost always written in JavaScript.
In the netflix.com example above, the HTML, CSS, and JavaScript that dictate how the Netflix main page appears
to the user are interpreted by the browser on the client side. The page can also respond to 'events': For instance, if
the user's mouse hovers over one of the movie thumbnail images, the image expands and adjacent thumbnails
move slightly to one side to make room for the larger image. This is an example of a client-side process; the code
within the webpage itself responds to the user's mouse and initiates this action without communicating with the
server.
The client side is also known as the frontend, although these two terms do not mean precisely the same thing.
Client-side refers solely to the location where processes run, while frontend refers to the kinds of processes that run
client-side.
*A dynamic webpage is a webpage that does not display the same content for all users and changes based on user
input. The Facebook homepage is a dynamic page; the Facebook login page is for the most part static.

What does server side mean?


Much like with client side, 'server side' means everything that happens on the server, instead of on the client. In the
past, nearly all business logic ran on the server side, and this included rendering dynamic webpages, interacting
with databases, identity authentication, and push notifications.
The problem with hosting all of these processes on the server side is that each request involving one of them has to
travel all the way from the client to the server, every time. This introduces a great deal of latency. For this reason,
contemporary applications run more code on the client side; one use case is rendering dynamic webpages in real
time by running scripts within the browser that make changes to the content a user sees.
Like with 'frontend' and 'client-side,' backend is also a term for the processes that take place on the server, although
backend only refers to the types of processes and server-side refers to the location where processes run.

Differences between client-side and server-side


Client-side

 Does not need interaction with the server


 Runs on the user’s computer
 Reduces load on the server’s proccessing unit
 Languages used: HTML, CSS, JavaScript

Server-side

 Requires interaction with the server


 Runs on the web server
 Allows the server to provide dynamic websites tailored to the user. Increases the processing load on server.
 Languages used: PHP, ASP.net, Python

Web Standards:
Web standards are defined as technologies that are used in building websites. Web Standards consist of
technical documents known as specifications, which provide detailed information on how web
technology should work. These documents are really helpful for engineers in making web applications in
a more efficient manner for the users.
History of Web Standards:
The web came into existence when the US military created a network for communication in the 1960s
which was known as ARPANET. ARPANET uses a packet switching method for transmitting
information and it was the first network to use TCP/IP model. After two decades means in 1980, the
concept of transmission of data among different nodes through linking was given by Tim Berners-Lee.
In the year 1990, Tim Berners-Lee made all the necessary arrangements to implement the first model of
the web. It consists of HTTP protocols, HTML for creating web pages and a web browser to view web
pages, and lastly an HTTP server. This is how the web started.
Need for Web Standards:
After the creation of the web, it was accessible by people by using a computer system, at that time only a
handful of systems were there to access the web but with the rise of technology the way people access
the web changed completely. Now people use different types of devices like mobile phones, tablets,
laptops, desktops, etc. There are even more devices like interfaces provided in vehicles for navigation
and smart speakers using speech. Moreover, screen sizes are also different when accessing the web and
different operating systems are also available along with a number of web browsers. All of this has made
it quite different for everyone to access the same web in different manners on different devices.
 Hence it becomes a need to make certain standards while developing websites so that those websites
work smoothly on all devices with different configurations. Web standards form the foundation of rules
and regulations for the developers for developing websites.
Therefore in 1994, World Wide Web Consortium also known as W3C was founded by Tim Berners-Lee. W3C
organization collaborated with many different IT organizations to work on making the standards/governing rules
for web development.

Components of Web Standards


 W3C recommendations for HTML, CSS, and also for different image formats to be used in websites.
 Living Standards provided by Web Hypertext Application Technology Working Group (WHATWG),
these standards consist of Document Object Model Standard, URL Standard, Encoding Standards, etc.
 JSON standards are given by ECMA International.
 Recommendations of the International Organization for Standardization (ISO).
 World Wide Web Consortium (W3C)
 The credit for maintaining and creating new web standards goes to World Wide Web Consortium (W3C)
which is considered the main organization. A number of standards have been defined by W3C which
includes different languages that are used in making websites like HTML, CSS, JavaScript, etc.
 Any website will be considered to follow the given web if that website or web page has correct HTML
and CSS. These languages also need to comply with semantic and accessibility procedures.
HTML - HyperText Markup Language
HTML is the publishing language of the World Wide Web developed by Tim Berners-Lee while at CERN. HTML
has been developed with the vision that all manner of devices should be able to use information on the Web: PCs
with graphics displays of varying resolution and color depths, mobile phones, hand held devices, devices for
speech for output and input, computers with high or low bandwidth, and so on. HTML has been extended in a
number of ways since its inception
HTML 2.0 was developed in 1994 to codify common practice so that it would work across different browsers and
platforms. HTML 3.0 proposed much richer versions of HTML however it never reached consensus and led to
HTML 3.2 in 1996.
HTML 4 extends HTML with mechanisms for style sheets, scripting, frames, embedding objects, improved
support for right to left and mixed direction text, richer tables, and enhancements to forms, offering improved
accessibility for people with disabilities.
HTML 4.01 is a revision of HTML 4.0 that corrects errors and makes some changes since the previous revision.
HTML5 is the new kid on the block. All the cool kids want to play with HTML5 however "HTML5 is currently
under development, as the next major revision of the HTML standard. Like its immediate predecessors, HTML
4.01 and XHTML 1.1, HTML5 is a standard for structuring and presenting content on the World Wide Web. The
new standard incorporates features like video playback and drag-and-drop that have been previously dependent on
third-party browser plug-ins."
XML 1.0 - Extensible Markup Language
XML is a publishing language like HTML, but instead of having a single, fixed set of elements, it allows you to
define your own - or use a set made by someone else. Some applications of XML, such as XHTML and MathML,
have already become W3C Recommendations.

Style sheet standards, such as CSS and XSL, offer a variety of options for specifying how XML elements are to be
rendered. Standards-compliant support for direct rendering of XML is spotty in browsers, so for presenting
information to humans, HTML (or XHTML) with CSS-driven styling is the way to go. XML is mostly used for
machine-to-machine communication today.

XHTML - Extensible Hypertext Markup Language


XHTML 1.0 is a reformulation of HTML as an XML application. XHTML 1.0 can be seen as ideologically
coming from HTML 4.01, and being technically stricter because of XML’s influence.
XHTML will display in your browser identically to the equivalent HTML. You might want to use XHTML if there
is any chance you’re going to need to reprocess your content, for example to send it to a PDA; XML’s stricter
syntax rules make automatic processing of XHTML much easier and cheaper than ordinary HTML.
Ideologically, XHTML 1.0 inherits the following general concepts from HTML 4.01:

 That presentation and document formatting should be separated via style sheets
 That documents should be made accessible
 That documents should be internationalized
By doing this, your work will be extremely structured because there are virtually no presentational attributes in
XHTML. The separation of structure and presentation is complete here, and all of your presentation work will go
in a style sheet.
CSS - Cascading Style Sheets
Cascading Style Sheets (CSS) is a mechanism for changing the appearance of HTML or XML elements, by
assigning styles to elements.

Stylesheets can be used to consistently define the appearance of an entire site. Following the introduction of CSS,
the W3C recommended that layout-specific features in HTML be phased out and replaced by stylesheets, creating
a simpler and more structural World Wide Web.

Unit II
HTML Basics:
HTML stands for Hypertext Markup Language, and it is the most widely used language to write Web Pages.
 Hypertext refers to the way in which Web pages (HTML documents) are linked together. Thus, the link
available on a webpage is called Hypertext.
 As its name suggests, HTML is a Markup Language which means you use HTML to simply "mark-up" a
text document with tags that tell a Web browser how to structure it to display.
Originally, HTML was developed with the intent of defining the structure of documents like headings, paragraphs,
lists, and so forth to facilitate the sharing of scientific information between researchers.
Now, HTML is being widely used to format web pages with the help of different tags available in HTML
language.

Basic HTML Document


In its simplest form, following is an example of an HTML document −
The <!DOCTYPE> Declaration
The <!DOCTYPE> declaration tag is used by the web browser to understand the version of the HTML used in the
document. Current version of HTML is 5 and it makes use of the following declaration −

<!DOCTYPE html>
There are many other declaration types which can be used in HTML document depending on what version of
HTML is being used. We will see more details on this while discussing <!DOCTYPE...> tag along with other
HTML tags.
<!DOCTYPE html>
 <html> : Every HTML code must be enclosed between basic HTML tags. It begins with <html> and ends
with </html> tag.
 <head>: The head tag comes next which contains all the header information of the web page or documents
like the title of the page and other miscellaneous information. This information is enclosed within the head
tag which opens with <head> and ends with </head>. The contents will of this tag will be explained in the
later sections of the course.
 <title>: We can mention the title of a web page using the <title> tag. This is header information and hence
is mentioned within the header tags. The tag begins with <title> and ends with </title>.
 <body>: Next step is the most important of all the tags we have learned so far. The body tag contains the
actual body of the page which will be visible to all the users. This opens with <body> and ends
with </body>. All content enclosed within this tag will be shown on the web page be it writings or images
or audio or videos or even links. We will see later in the section how using various tags we may insert
mentioned contents into our web pages.
Example: This example illustrates the HTML basic structure.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
HTML Tags
HTML tags are like keywords which defines that how web browser will format and display the content. With the
help of tags, a web browser can distinguish between an HTML content and a simple content. HTML tags contain
three main parts: opening tag, content and closing tag. But some HTML tags are unclosed tags.
When a web browser reads an HTML document, browser reads it from top to bottom and left to right. HTML tags
are used to create HTML documents and render their properties. Each HTML tags have different properties.
An HTML file must have some essential tags so that web browser can differentiate between a simple text and
HTML text. You can use as many tags you want as per your code requirement.
o All HTML tags must enclosed within < > these brackets.
o Every tag in HTML perform different tasks.
o If you have used an open tag <tag>, then you must use a close tag </tag> (except some tags)

Syntax

<tag> content </tag>

Note: HTML Tags are always written in lowercase letters. The basic HTML tags are given below:

HTML Heading
A HTML heading or HTML h tag can be defined as a title or a subtitle which you want to display on the webpage.
When you place the text within the heading tags <h1>.........</h1>, it is displayed on the browser in the bold format
and size of the text depends on the number of heading.
There are six different HTML headings which are defined with the <h1> to <h6> tags, from highest level h1 (main
heading) to the least level h6 (least important heading).
h1 is the largest heading tag and h6 is the smallest one. So h1 is used for most important heading and h6 is used for
least important.
Example
Live Demo
<!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>
Paragraph Tag
The <p> tag offers a way to structure your text into different paragraphs. Each paragraph of text should
go in between an opening <p> and a closing </p> tag as shown below in the example −
Example
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Paragraph Example</title>
</head>

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

</html>
Line Break Tag
Whenever you use the <br /> element, anything following it starts from the next line. This tag is an example of
an empty element, where you do not need opening and closing tags, as there is nothing to go in between them.
The <br /> tag has a space between the characters br and the forward slash. If you omit this space, older browsers
will have trouble rendering the line break, while if you miss the forward slash character and just use <br> it is not
valid in XHTML.
Example
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Line Break Example</title>
</head>

<body>
<p>Hello<br />
You delivered your assignment ontime.<br />
Thanks<br />
Mahnaz</p>
</body>
</html>
Centering Content
You can use <center> tag to put any content in the center of the page or any table cell.
Example
<body>
<p>This text is not in the center.</p>

<center>
<p>This text is in the center.</p>
</center>
</body>
Horizontal Lines
Horizontal lines are used to visually break-up sections of a document. The <hr> tag creates a line from the current
position in the document to the right margin and breaks the line accordingly.
For example, you may want to give a line between two paragraphs as in the given example below −
Example
Live Demo
<!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>

HTML Formatting
HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format
text without using CSS. There are many formatting tags in HTML. These tags are used to make text bold,
italicized, or underlined.
1) Bold Text
HTML<b> and <strong> formatting elements
The HTML <b> element is a physical tag which display text in bold font, without any logical importance. If you
write anything within <b>............</b> element, is shown in bold letters.
example:
<p> <b>Write Your First Paragraph in bold text.</b></p>
The HTML <strong> tag is a logical tag, which displays the content in bold font and informs the browser about its
logical importance. If you write anything between <strong>???????. </strong>, is shown important text.
example:
<p><strong>This is an important content</strong>, and this is normal content</p>
2) Italic Text
HTML <i> and <em> formatting elements
The HTML <i> element is physical element, which display the enclosed content in italic font, without any added
importance. If you write anything within <i>............</i> element, is shown in italic letters.
See this example:
<p> <i>Write Your First Paragraph in italic text.</i></p>
3) Underlined Text
If you write anything within <u>.........</u> element, is shown in underlined text.
See this example:
<p> <u>Write Your First Paragraph in underlined text.</u></p>
4) HTML Marked formatting
If you want to mark or highlight a text, you should write the content within <mark>.........</mark>.
See this example:
<h2> I want to put a <mark> Mark</mark> on your face</h2>
5) Strike Text
Anything written within <strike>.......................</strike> element is displayed with strikethrough. It is a thin line
which cross the statement.
See this example:
<p> <strike>Write Your First Paragraph with strikethrough</strike>.</p>
6) Superscript Text
If you put the content within <sup>..............</sup> element, is shown in superscript; means it is displayed half a
character's height above the other characters.
See this example:
<p>Hello <sup>Write Your First Paragraph in superscript.</sup></p>
7) Subscript Text
If you put the content within <sub>..............</sub> element, is shown in subscript ; means it is displayed half a
character's height below the other characters.
See this example:
<p>Hello <sub>Write Your First Paragraph in subscript.</sub></p>
8)HTML Anchor
The HTML anchor tag defines a hyperlink that links one page to another page. It can create hyperlink to other
web page as well as files, location, or any URL. The "href" attribute is the most important attribute of the HTML a
tag. and which links to destination page or URL.
href attribute of HTML anchor tag
The href attribute is used to define the address of the file to be linked. In other words, it points out the destination
page.
The syntax of HTML anchor tag is given below.
<a href = "..........."> Link Text </a>
1. EXAMPLE: <a href="second.html">Click for Second Page</a>
If we want to open that link to another page then we can use target attribute of <a> tag. With the help of this link
will be open in next page.
Example:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Click on <a href="https://www.javatpoint.com/" target="_blank"> this-
link </a>to go on home page of JavaTpoint.</p>
</body>
</html>
The target attribute can only use with href attribute in anchor tag.
If we will not use target attribute then link will open in same page.
HTML Image
HTML img tag is used to display image on the web page. HTML img tag is an empty tag that contains attributes
only, closing tags are not used in HTML image element.
Let's see an example of HTML image.
<h2>HTML Image Example</h2>
<img src="good_morning.jpg" alt="Good Morning Friends"/>
Attributes of HTML img tag
The src and alt are important attributes of HTML img tag. All attributes of HTML image tag are given below.
1) src
It is a necessary attribute that describes the source or path of the image. It instructs the browser where to look for
the image on the server.
The location of image may be on the same directory or another server.
2) alt
The alt attribute defines an alternate text for the image, if it can't be displayed. The value of the alt attribute
describe the image in words. The alt attribute is considered good for SEO prospective.
3) width
It is an optional attribute which is used to specify the width to display the image. It is not recommended now. You
should apply CSS in place of width attribute.
4) height
It h3 the height of the image. The HTML height attribute also supports iframe, image and object elements. It is not
recommended now. You should apply CSS in place of height attribute.

Use of height and width attribute with img tag


You have learnt about how to insert an image in your web page, now if we want to give some height and width to
display image according to our requirement, then we can set it with height and width attributes of image.
Example:
<img src="animal.jpg" height="180" width="300" alt="animal image">
Use of alt attribute

We can use alt attribute with tag. It will display an alternative text in case if image cannot be displayed on
browser. Following is the example for alt attribute:
<img src="animal.png" height="180" width="300" alt="animal image">
How to get image from another directory/folder?
To insert an image in your web, that image must be present in your same folder where you have put the
HTML file. But if in some case image is available in some other directory then you can access the image
like this:
1. <img src="E:/images/animal.png" height="180" width="300" alt="animal image">
In above statement we have put image in local disk E------>images folder------>animal.png.
Note: If src URL will be incorrect or misspell then it will not display your image on web page, so try to put
correct URL.
Use <img> tag as a link
We can also link an image with other page or we can use an image as a link. To do this, put <img> tag
inside the <a> tag.
Example:
<a href="https://www.javatpoint.com/what-is-robotics"><img src="robot.jpg" height="100" width="100"></a>
HTML figure tag
HTML <figure> tag is used to mark up a photo in the document on a web page.
As we know image tag is already available in HTML to display the pictures on web pages. But HTML 5 <figure>
tag is used to handle the group of diagrams, photos, code listing etc. with some embedded content. You can also
add a caption for the photo with the help of <figcaption> tag.
HTML figure is new a new tag introduced in HTML5.

HTML figure tag example


<p>The Taj Mahal is widely recognized as "the jewel of Muslim art in India and
one of the universally admired masterpieces of the world's heritage". It is regarded
by many as the finest example of Mughal architecture, a style that combines elements
from Islamic, Persian, Ottoman, Turkish and Indian architectural styles.</p>
<figure>
<img src="https://static.javatpoint.com/htmlpages/images/tajmahal.jpg" alt="Taj Mahal"/>
</figure>
HTML figcaption tag
The <figcaption> element is used to provide a caption to an image.
It is an optional tag and can appear before or after the content within the <figure> tag.
Only one <figcaption> element can be nested within a <figure> tag although the <figure> element itself may
contain multiple other elements like <img> or <code>.
The <figcaption> element is used with <figure> element and it can be placed as the first or last child of the
<figure> element.

HTML figure tag example


<figure>
<img src="https://static.javatpoint.com/htmlpages/images/tajmahal.jpg" alt="Taj Mahal"/>
<figcaption>Fig.1.1 - A front view of the great Taj Mahal in Agra.</figcaption>
</figure>
HTML Elements
An HTML file is made of elements. These elements are responsible for creating web pages and define
content in that webpage. An element in HTML usually consist of a start tag <tag name>, close tag </tag
name> and content inserted between them. Technically, an element is a collection of start tag,
attributes, end tag, content between them.
Note: Some elements does not have end tag and content, these elements are termed as empty elements or self-
closing element or void elements.
Such as:
<p> Hello world!!! </p>
Example
<!DOCTYPE html>
<html>
<head>
<title>WebPage</title>
</head>
<body>
<h1>This is my first web page</h1>
<h2> How it looks?</h2>
<p>It looks Nice!!!!!</p>
</body>
</html>
All the content written between body elements are visible on web page.

Void element: All the elements in HTML do not require to have start tag and end tag, some elements does not
have content and end tag such elements are known as Void elements or empty elements. These elements are also
called as unpaired tag.
Some Void elements are <br> (represents a line break) , <hr>(represents a horizontal line), etc.
Nested HTML Elements: HTML can be nested, which means an element can contain another element.

Block-level and Inline HTML elements


For the default display and styling purpose in HTML, all the elements are divided into two categories:
o Block-level element
o Inline element

Block-level element:
o These are the elements, which structure main part of web page, by dividing a page into coherent blocks.
o A block-level element always start with new line and takes the full width of web page, from left to right.
o These elements can contain block-level as well as inline elements.
Following are the block-level elements in HTML.
<address>, <article>, <aside>, <blockquote>, <canvas>, <dd>, <div>, <dl>, <dt>, <fieldset>, <figcaption>,
<figure>, <footer>, <form>, <h1>-<h6>, <header>, <hr>, <li>, <main>, <nav>, <noscript>, <ol>, <output>, <p>,
<pre>, <section>, <table>, <tfoot>, <ul> and <video>.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div style="background-color: lightblue">This is first div</div>
<div style="background-color: lightgreen">This is second div</div>
<p style="background-color: pink">This is a block level element</p>
</body>
</html>
in the above example we have used tag, which defines a section in a web page, and takes full width of page.We
have used style attribute which is used to styling the HTML content, and the background color are showing
that it's a block level element.
Inline elements:
o Inline elements are those elements, which differentiate the part of a given text and provide it a particular
function.
o These elements does not start with new line and take width as per requirement.
o The Inline elements are mostly used with other elements.

<a>, <abbr>, <acronym>, <b>, <bdo>, <big>, <br>, <button>, <cite>, <code>, <dfn>, <em>, <i>, <img>,
<input>, <kbd>, <label>, <map>, <object>, <q>, <samp>, <script>, <select>, <small>, <span>, <strong>, <sub>,
<sup>, <textarea>, <time>, <tt>, <var>.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a href="https://www.javatpoint.com/html-tutorial">Click on link</a>
<span style="background-color: lightblue">this is inline element</span>
<p>This will take width of text only</p>
</body>
</html>
<div> This is div </div> This element is used to provide a section in web
section page.

HTML Attribute
o HTML attributes are special words which provide additional information about the elements or attributes
are the modifier of the HTML element.
o Each element or tag can have attributes, which defines the behaviour of that element.
o Attributes should always be applied with start tag.
o The Attribute should always be applied with its name and value pair.
o The Attributes name and values are case sensitive, and it is recommended by W3C that it should be written
in Lowercase only.
o You can add multiple attributes in one HTML element, but need to give space between two attributes.

Syntax
1. <element attribute_name="value">content</element>

Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> This is Style attribute</h1>
<p style="height: 50px; color: blue">It will add style property in element</p>
<p style="color: red">It will change the color of content</p>
</body>
</html>
Explanation of above example:
<p style="height: 50px; color: blue">It will add style property in element</p>
In the above statement, we have used paragraph tags in which we have applied style attribute. This attribute is used
for applying CSS property on any HTML element. It provides height to paragraph element of 50px and turns it
colour to blue.
<p style="color: red">It will change the color of content</p>
In the above statement we have again used style attribute in paragraph tag, which turns its colour red.
Note: There are some commonly used attributes are given below, and the complete list and explanation of all
attributes are given in HTML attributes List.
The title attribute in HTML
Description: The title attribute is used as text tooltip in most of the browsers. It display its text when user move
the cursor over a link or any text. You can use it with any text or link to show the description about that link or
text. In our example, we are taking this with paragraph tag and heading tag.
Example
With <h1> tag:
<h1 title="This is heading tag">Example of title attribute</h1>
With <p> tag:
<p title="This is paragraph tag">Move the cursor over the heading and paragraph, and you will see a
description as a tooltip</p>
The href attribute in HTML
Description: The href attribute is the main attribute of <a> anchor tag. This attribute gives the link address which
is specified in that link. The href attribute provides the hyperlink, and if it is blank, then it will remain in
same page.
Example
With link address:
<a href="https://www.javatpoint.com/html-anchor">This is a link</a>
The src Attribute
The src attribute is one of the important and required attribute of <img> element. It is source for the image which
is required to display on browser. This attribute can contain image in same directory or another directory. The
image name or source should be correct else browser will not display the image.
Example
<img src="whitepeacock.jpg" height="400" width="600">
Note: The above example also have height and width attribute, which define the height and width of image on web
page.
<a href="https://www.javatpoint.com">A link to HTML.</a>
<a href='https://www.javatpoint.com'>A link to HTML.</a>
HTML Semantics
In any language, it is essential to understand the meaning of words during communication. And if this is a
computer communication then it becomes more critical. So HTML5 provides more semantic elements which make
easy understanding of the code.
Hence Semantics defines the meaning of words and phrases, i.e.
Semantic elements= elements with a meaning. Semantic elements have a simple and clear meaning for both, the
browser and the developer.
For example:
In HTML4 we have seen <div>, <span> etc. are which are non-semantic elements. They don't tell anything about
its content.
On the other hand, <form>, <table>, and <article> etc. are semantic elements because they clearly define their
content.
HTML5 semantic elements are supported by all major browsers.
Why to use semantic elements?
In HTML4, developers have to use their own id/class names to style elements: header, top, bottom, footer, menu,
navigation, main, container, content, article, sidebar, topnav, etc.
This is so difficult for search engines to identify the correct web page content. Now in HTML5 elements (<header>
<footer> <nav> <section> <article>), this will become easier. It now allows data to be shared and reused across
applications, enterprises, and communities."
Semantic elements can increase the accessibility of your website, and also helps to create a better website structure.
Semantic Elements in HTML

Index Semantic Description


Tag

1. <article> Defines an article

2. <aside> Defines content aside from the page content

3. <details> Defines additional details that the user can view or hide

4. <figcaption> Defines a caption for a <figure> element

5. <figure> Specifies self-contained content, like illustrations, diagrams, photos,


code listings, etc.

6. <footer> Defines a footer for a document or section

7. <header> Specifies a header for a document or section

8. <main> Specifies the main content of a document


9. <mark> Defines marked/highlighted text

10. <nav> Defines navigation links

11. <section> Defines a section in a document

12. <summary> Defines a visible heading for a <details> element

13. <time> Defines a date/time

Some important semantic elements in HTML


HTML <article> Element

HTML <article> element defines article content within a document, page, application, or a website. It can be used
to represent a forum post, a magazine, a newspaper article, or a big story.
Example:
<article>
<h2>Today's highlights</h2>
<p>First story</p>
<p>Second story</p>
<p>Third story</p>
</article>
HTML <aside> Element
The <aside> element represent the content which is indirectly giving information to the main content of the page. It
is frequently represented as a sidebar.
Example:
<body>
<h2>My last year memories</h2>
<p>I have visited Paris with my friends last month. This was the memorable journey and i wish to go there again.</p>
<aside>
<h4>Paris</h4>
<p>Paris, France's capital, is a major European city and a global center for art, fashion, gastronomy and culture</p>

</aside>
</body>
HTML <section> Element
The <section> element is used to represent the standalone section within an HTML document. A page can have
various sections and each section can contain any content, but headings for each section is not mandatory.
Example:
<h2>Web designing Tutorial</h2>
<section>
<h3>HTML</h3>
<p>HTML is an acronym which stands for Hyper Text Markup Language which is used for creating web pages and
web applications.</p>
</section>
<section>
<h3>CSS</h3>
<p>CSS stands for Cascading Style Sheets. It is a style sheet language which is used to describe the look and format
ting of a document written in markup language. It provides an additional feature to HTML.</p>
</section>
Nesting <article> tag in <section> tag or Vice Versa?
We know that the<article> element specifies independent, self-contained content and the <section> element
defines section in a document.
In HTML, we can use <section> elements within <article> elements, and <article> elements within <section>
elements.
We can also use <section> elements within <section> elements, and <article> elements within <article> elements.
For example:
In a newspaper, the sport <article> in the sport section, may have a technical section in each <article>.

HTML <nav> Element


The HTML <nav> element is used to define a set of navigation links.
Example:
<!DOCTYPE html>
<html>
<body>
<nav>
<a href="https://www.javatpoint.com/html-tutorial">HTML</a> |
<a href="https://www.javatpoint.com/java-tutorial">Java</a> |
<a href="https://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="https://www.javatpoint.com/css-tutorial">CSS</a>
</nav>
</body>
</html>
HTML <footer> Element
The <footer> tag defines the footer of an HTML document or page.
Example:
<footer>
<p>© Copyright 2019. All rights reserved. </p>
</footer>
HTML5
provides details of all 40+ HTML tags including audio, video, header, footer, data, datalist, article etc. This
HTML tutorial is designed for beginners and professionals.
HTML5 is a next version of HTML. Here, you will get some brand new features which will make HTML
much easier. These new introducing features make your website layout clearer to both website designers and
users. There are some elements like <header>, <footer>, <nav> and <article> that define the layout of a
website.

Why use HTML5


It is enriched with advance features which makes it easy and interactive for designer/developer and users.
It allows you to play a video and audio file.
It allows you to draw on a canvas.
It facilitate you to design better forms and build web applications that work offline.
It provides you advance features for that you would normally have to write JavaScript to do.
The most important reason to use HTML 5 is, we believe it is not going anywhere. It will be here to serve for a
long time according to W3C recommendation.

The new features that were added in HTML5 that make it better than HTML:

1.Intro of audio and video:


Audio and Video tags are the two major addition to HTML5. It allows developers to embed a video or audio
on their website. HTML5 video can use CSS and CSS3 to style the video tag. You can change the border,
opacity, reflections, gradients, transitions, transformations, and even animations. HTML5 makes adding video
super-fast and without having to build a video player. This saves time for the developer and offers the client a
superior and more affordable solution.
2. Vector Graphics:

This is a new addition to the revised version which has hugely impacted the use of Adobe Flash in websites.
It can be used to draw graphics with various shapes and colors via scripting usually JS. Vector graphics are
scalable, easy to create and edit. It also supports interactivity and animation. Having a smaller file size makes
transferring and loading graphics much faster on the web. That’s the reason why many people prefer to use
vector graphics.
Example:
<svg id = "svgelem" height = "200" xmlns = "http://www.abc.org/2000/svg">
<circle id = "redcircle" cx = "50" cy = "50" r = "50" fill = "red" />
</svg>
3.Header and Footer:
With these new tags, there is no longer a need to identify the two elements with a <div> tag. Footer is
placed at the end of the web page while Header is placed at the start of the web page. By using <header> and
<footer> HTML5 elements, the browser will know what to load first and what to load later.
The header can contain-
 One or more heading elements (<h1> – <h6>)
 Logo or icon
 Authorship information
Footer can contain-
 Authorship information
 Copyright information
 Contact information
 Back to top links
4. Figure and Figcaption
HTML5 allows to use a <figure> element to mark up a photo in a document, and a <figcaption> element to
define a caption for the photo. The <figcaption> tag defines a caption for a <figure> element. This tag provides
a container for content that is equivalent to a figure. It can be used to group a caption with one or more images, a
block of code, or other content.
5. Nav tag: The <nav> tag defines a set of navigation links. It is used for the part of an internet site that
links to different pages at the website. The hyperlinks can be organized through a number of approaches.
Common examples of the nav elements are menus, tables, contents, and indexes. This element makes it much
easier to create a navigation menu, creates a neat horizontal menu of text links, and helps screen reading
software to correctly identify primary navigation areas in the document.
6. Progress tag: The progress tag is used to check the progress of a task during the execution. Progress tag
can be used with the conjunction of JavaScript.
<h1>The progress element</h1>
<label for="file">Downloading progress:</label>
<progress id="file" value="32" max="100"> 32% </progress>
7. Placeholder Attribute: The placeholder attribute specifies a short hint that describes the expected
value of an input field/text area. The short hint is displayed in the field before the user enters a value.
8. Email attribute: When the input type in the form set as email, then the browser gets the instruction
from the code to write a valid format email. The input email id is automatically validated to check the
format of the email id is correct or not.
9. Storage: In the case of HTML, we can use the browser as the temporary storage whereas, in the case of
HTML5, application cache, web SQL database, and web storage is used.
10. Ease of use: While HTML5 does have risks like constant updates, it is generally easy to keep up with
the changes & updates because of simpler syntax as compared to other versions of HTML.

HTML 5 Example
Let's see a simple example of HTML5.
<!DOCTYPE>
<html>
<body>
<h1>Write Your First Heading</h1>
<p>Write Your First Paragraph.</p>
</body>
</html>
What are the media element tags introduced by HTML5 ?
HTML5 introduced 5 most popular media element tags i.e. <audio>, <video>, <source>, <embed>,
<track>. These media element tags changed the entire development using HTML.
In this article, you will get to know about these five media element tags briefly.
Media Tags:
 <audio>: It is an inline element that is used to embed sound files into a web page.
 <video>: It is used to embed video files into a web page.
 <source>: It is used to attach multimedia files like audio, video, and pictures.
 <embed>: It is used for embedding external applications which are generally multimedia content like audio
or video into an HTML document.
 <track>: It specifies text tracks for media components audio and video.
Advantage of Media tag:
 Plugins are no longer required
 Speed – anything naturally integrated into a browser will be rendered and executed in a faster fashion than
imported third-party
 Native (built-in) controls are provided by the browser.
 Accessibilities (keyboard, mouse) are built-in automatically
 <audio> Tag: It is a useful tag if you want to add audio such as songs, or any sound files into your
webpage.
HTML audio tag is used to define sounds such as music and other audio clips. Currently there are three supported
file format for HTML 5 audio tag.
 mp3
 wav
 ogg
Syntax:
<audio>
<source src="sample.mp3" type="audio/mpeg">
</audio>
Example: In this example, we will use <audio> tag.
<audio> Tag: It is a useful tag if you want to add audio such as songs, or any sound files into your
webpage.
Syntax:
<audio>
<source src="sample.mp3" type="audio/mpeg">
</audio>
Example: In this example, we will use <audio> tag.
<audio controls>
<source src="koyal.mp3" type="audio/mpeg">
Your browser does not support the html audio tag.
</audio>

Attributes of HTML Audio Tag


There is given a list of HTML audio tag.

Attribute Description

controls It defines the audio controls which is displayed with play/pause buttons.

autoplay It specifies that the audio will start playing as soon as it is ready.

loop It specifies that the audio file will start over again, every time when it is
completed.

muted It is used to mute the audio output.


preload It specifies the author view to upload audio file when the page loads.

src It specifies the source URL of the audio file.

HTML Audio Tag Attribute Example


Here we are going to use controls, autoplay, loop and src attributes of HTML audio tag.
<audio controls autoplay loop>
<source src="koyal.mp3" type="audio/mpeg"></audio>
HTML Video Tag
HTML 5 supports <video> tag also. The HTML video tag is used for streaming video files such as a
movie clip, song clip on the web page.
Currently, there are three video formats supported for HTML video tag:
1. mp4
2. webM
3. ogg
HTML Video Tag Example
Let's see the code to play mp4 file using HTML video tag.
<video controls>
<source src="movie.mp4" type="video/mp4">
Your browser does not support the html video tag.
</video>
Let's see the example to play ogg file using HTML video tag.
<video controls>
<source src="movie.ogg" type="video/ogg">
Your browser does not support the html video tag.
</video>

Attributes of HTML Video Tag

Attribute Description

controls It defines the video controls which is displayed with play/pause buttons.

height It is used to set the height of the video player.

width It is used to set the width of the video player.

poster It specifies the image which is displayed on the screen when the video is not
played.

autoplay It specifies that the video will start playing as soon as it is ready.

loop It specifies that the video file will start over again, every time when it is
completed.

muted It is used to mute the video output.

preload It specifies the author view to upload video file when the page loads.

src It specifies the source URL of the video file.


HTML Video Tag Attribute Example
Let's see the example of video tag in HTML where are using height, width, autoplay, controls and loop attributes.
<video width="320" height="240" controls autoplay loop>
<source src="movie.mp4" type="video/mp4">
Your browser does not support the html video tag.
</video>
HTML Form
An HTML form is a section of a document which contains controls such as text fields, password fields,
checkboxes, radio buttons, submit button, menus etc.
An HTML form facilitates the user to enter data that is to be sent to the server for processing such as name, email
address, password, phone number, etc. .
Why use HTML Form
HTML forms are required if you want to collect some data from of the site visitor.
For example: If a user want to purchase some items on internet, he/she must fill the form such as shipping addr
HTML Form Syntax
<form action="server url" method="get|post">
//input controls e.g. textfield, textarea, radiobutton, button
</form>
HTML Form Tags
Let's see the list of HTML 5 form tags.

Tag Description

<form> It defines an HTML form to enter inputs by the used side.

<input> It defines an input control.

<textare It defines a multi-line input control.


a>

<label> It defines a label for an input element.

<fieldset It groups the related element in a form.


>

<legend It defines a caption for a <fieldset> element.


>

<select> It defines a drop-down list.

<optgrou It defines a group of related options in a drop-down list.


p>

<option> It defines an option in a drop-down list.

<button> It defines a clickable button.

HTML 5 Form Tags

Let's see the list of HTML 5 form tags.

Tag Description

<datalist> It specifies a list of pre-defined options for input control.


<keygen> It defines a key-pair generator field for forms.

<output> It defines the result of a calculation.

HTML <form> element


The HTML <form> element provide a document section to take input from user. It provides various interactive
controls for submitting information to web server such as text field, text area, password field, etc.
Note: The <form> element does not itself create a form but it is container to contain all required form
elements, such as <input>, <label>, etc.
HTML <input> element
The HTML <input> element is fundamental form element. It is used to create form fields, to take input from user.
We can apply different input filed to gather different information form user. Following is the example to show the
simple text input.
HTML TextField Control
The type="text" attribute of input tag creates textfield control also known as single line textfield control.
The name attribute is optional, but it is required for the server side component such as JSP, ASP, PHP
etc.
HTML <textarea> tag in form
The <textarea> tag in HTML is used to insert multiple-line text in a form. The size of <textarea> can be specify
either using "rows" or "cols" attribute or by CSS.
Label Tag in Form
It is considered better to have label in form. As it makes the code parser/browser/user friendly.
If you click on the label tag, it will focus on the text control. To do so, you need to have for attribute in
label tag that must be same as id attribute of input tag.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Form in HTML</title>
</head>
<body>
<form>
First Name: <input type="text" name="firstname"/> <br/>
Last Name: <input type="text" name="lastname"/> <br/>
Enter your address:<br>
<textarea rows="2" cols="20"></textarea>
<label for="password">Password: </label>
<input type="password" id="password" name="password"/> <br/> </form>
</body>
</html>
HTML 5 Email Field Control
The email field in new in HTML 5. It validates the text for correct email address. You must use @ and . in this
field.
<form>
<label for="email">Email: </label>
<input type="email" id="email" name="email"/> <br/>
</form>
Radio Button Control
The radio button is used to select one option from multiple options. It is used for selection of gender, quiz
questions etc.If you use one name for all the radio buttons, only one radio button can be selected at a time.
Using radio buttons for multiple options, you can only choose a single option at a time.
Example:
<form>
<label for="gender">Gender: </label>
<input type="radio" id="gender" name="gender" value="male"/>Male
<input type="radio" id="gender" name="gender" value="female"/>Female <br/>
</form>
Checkbox Control
The checkbox control is used to check multiple options from given checkboxes.
Note: These are similar to radio button except it can choose multiple options at a time and radio button can
select one button at a time, and its display.
<form>
Hobby:<br>
<input type="checkbox" id="cricket" name="cricket" value="cricket"/>
<label for="cricket">Cricket</label> <br>
<input type="checkbox" id="football" name="football" value="football"/>
<label for="football">Football</label> <br>
<input type="checkbox" id="hockey" name="hockey" value="hockey"/>
<label for="hockey">Hockey</label>
</form>
Submit button control
HTML <input type="submit"> are used to add a submit button on web page. When user clicks on submit button,
then form get submit to the server.

Syntax:

<input type="submit" value="submit">


The type = submit , specifying that it is a submit button
The value attribute can be anything which we write on button on web page.
The name attribute can be omit here.
Example:
<form>
<label for="name">Enter name</label><br>
<input type="text" id="name" name="name"><br>
<label for="pass">Enter Password</label><br>
<input type="Password" id="pass" name="pass"><br>
<input type="submit" value="submit">
</form>
HTML <fieldset> element:
The <fieldset> element in HTML is used to group the related information of a form. This element is used with
<legend> element which provide caption for the grouped elements.
Example:
<form>
<fieldset>
<legend>User Information:</legend>
<label for="name">Enter name</label><br>
<input type="text" id="name" name="name"><br>
<label for="pass">Enter Password</label><br>
<input type="Password" id="pass" name="pass"><br>
<input type="submit" value="submit">
</fieldset>
lt;/form>
HTML Form Example
Following is the example for a simple form of registration.
<!DOCTYPE html>
<html>
<head>
<title>Form in HTML</title>
</head>
<body>
<h2>Registration form</h2>
<form>
<fieldset>
<legend>User personal information</legend>
<label>Enter your full name</label><br>
<input type="text" name="name"><br>
<label>Enter your email</label><br>
<input type="email" name="email"><br>
<label>Enter your password</label><br>
<input type="password" name="pass"><br>
<label>confirm your password</label><br>
<input type="password" name="pass"><br>
<br><label>Enter your gender</label><br>
<input type="radio" id="gender" name="gender" value="male"/>Male <br>
<input type="radio" id="gender" name="gender" value="female"/>Female <br/> <input typ
e="radio" id="gender" name="gender" value="others"/>others <br/>
<br>Enter your Address:<br>
<textarea></textarea><br>
<input type="submit" value="sign-up">
</fieldset>
</form>
</body>
</html>
HTML Table Tag
HTML <table> tag is used to display data in tabular form (row * column). There can be many columns in a
row.We can create a table to display data in tabular form, using <table> element, with the help of <tr> , <td>, and
<th> elements.
In Each table, table row is defined by <tr> tag, table header is defined by <th>, and table data is defined by <td>
tags.HTML tables are used to manage the layout of the page e.g. header section, navigation bar, body content,
footer section etc. But it is recommended to use div tag over table to manage the layout of the page .
Syntax:
<table> …………..</table>
HTML <tr> tag is used to define the rows in the table. The <tr> tag can consist one or more <th> head cells and
<td> data cells to define a single row of HTML table.The <tr> tag must be a direct child of <table> element or it
can be nested child of <thead>, <tbody>, and <tfoot> elements.
Syntax: <tr>. . . </tr>

HTML <td> tag is used to specify the cells of an HTML table which contain data of the table. The <td> tag must
be the child element of <tr> (table row) tag. Each table row can contain multiple <td> data elements.
The grouped <td> elements of a <tr> tag renders as a single row in the table. The content of the <td>
elements is regular and left-aligned in the table by default.
Syntax:<td>. …. </td>
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML tr tag</title>
<style>
table{
border-collapse: collapse;
margin-left: 350px;
}
th,td{
padding: 25px;}
th{
background-color: #005cb9;}
td{
background-color:#98f5ff;}
</style>
</head>
<body>
<h2>Example of table tag</h2>
<table border="1">
<caption><b>Top Three performers of Winter Olympic Medals</b></caption>
<tr>
<th>Rank</th>
<th>Country</th>
<th>Total medals</th>
</tr>
<tr>
<td>1</td>
<td>Norway</td>
<td>329</td>
</tr>
<tr>
<td>2</td>
<td>United State</td>
<td>282</td>
</tr>
<tr>
<td>3</td>
<td>Germany</td>
<td>228</td>
</tr>
</table>
</body>
</html>
HTML <th> tag
In an HTML table there are two types of cells:
o Header cell - It contains the header information (created using <th> element)
o Data Cells - It contains the main data of the table (created using <td> element).
HTML <th> tag is used to define the header cells of an HTML table. The header cell renders as bold and centered
by default on the browser, but you can change its default style using CSS properties.
The <th> tag must be used as a child element of the <tr> element within <table> element. The size of the table is
auto-adjustable as per the content size.

Attribute Value Description

abbr text It defines the abbreviated version of content of the header cell. (Not
Supported in HTML5)

align Left,right,center It specifies the alignment of the content of the header cell. (Not
justify,char Supported in HTML5)

axis category_name It Categorizes header Cells(Not Supported in HTML5)


bgcolor rgb(x,x,x),#xxxxxx It sets the background color of the header cell. (Not Supported in
Color_name HTML5)

char character It specifies the alignment of the content of the header cell to the
character. (Not Supported in HTML5)

charoff number It specifies the number of characters the header cell content will be
aligned from the character specified by the char attribute. (Not
Supported in HTML5)

colspan number It determines the number of columns a header cell should span.

headers header_id It determines a space-separated list of header cells which contains


information of the cells is related.

height % It determines the height of a table header cell. (Not Supported in


pixels HTML5)

nowrap nowrap If it sets then content inside the header cell should not wrap. (Not
Supported in HTML5)

rowspan number It determines the number of rows a cell should span.

scope Col,colgroup,row It specifies the cells that the header element relates to. (Not
rowgroup Supported in HTML5)

valign Top,middle,bottom It determines the vertical alignment of the cell content. (Not
baseline Supported in HTML5)

width % ,pixels It determines the width of the header cell.(Not Supported in


HTML5)

HTML <tbody> tag


HTML <tbody> tag is used to group the table rows (<tr>) together, which indicates that this is body part of a table
(<table>).
The <tbody> tag must be a child of <table> element.
The <tbody> is used along with <thead> and <tfoot> which shows the different part of the table that are table head,
table body, and table footer, however, it does not affect the layout of the table.
These elements can be used for providing semantic information which can be helpful in accessibility purpose, or
rendering the header at top and footer at the bottom while printing a large table.

Example:<!DOCTYPE html>
<html>
<head>
<title>HTML tbody tag</title>
<style>
body{
margin-left: 195px;" }
</style>
</head>
<body>
<h2>Example of the tbody tag</h2>
<table border="1" bgcolor="#98f5ff">
<thead>
<tr>
<th>EmpId</th>
<th>Name</th>
<th>Email-Id</th>
</tr>
</thead>
<tbody>
<tr>
<td>121</td>
<td>John</td>
<td>john123@gmail.com</td>
</tr>
<tr>
<td>122</td>
<td>William </td>
<td>william56@gmail.com</td>
</tr>
<tr>
<td>123</td>
<td>Amit</td>
<td>amitk98@gmail.com</td>
</tr>
</tbody>
</table>
</body>
</html>
HTML <thead> tag
HTML <thead> elements is used to define header of an HTML table. The <thead> tag is used along with <tbody>
and <tfoot> tags which defines table header, table body, and table footer in an HTML table.The <thead> tag must
be child of <table> element, and it must be used before any <tbody>, <tr>, or <tfoot> elements.The <thead> tag
should contain at least one row <tr> element inside it.

Syntax:<thead>
<tr>
</tr>
lt;/thead>
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML thead Tag</title>
<style>
table{
border-collapse: collapse;
margin: 15px;}
thead{
background-color:#005cb9;}
tbody{
background-color: #d4caca;}
th,td{
padding: 12px;}
</style>
</head>
<body>
<h2>Example of thead tag</h2>
<table border="1">
<caption>Population of India</caption>
<thead>
<tr>
<th>Year</th>
<th>Population</th>
</tr>
</thead>
<tbody>
<tr>
<td>2015</td>
<td>1,309,053,980</td>
</tr>
<tr>
<td>2016</td>
<td>1,324,171,354</td>
</tr>
<tr>
<td>2017</td>
<td>1,339,180,127</td>
</tr>
<tr>
<td>2018</td>
<td>1,354,051,854</td>
</tr>
</tbody>
</table>
</body>
</html>
HTML <tfoot> tag
HTML <tfoot> tag is used to define the set of rows which represents footer of an HTML table. The <tfoot> tag
must contain one or more <tr> element.The <tfoot> tag is used as a child element of HTML table (<table>) along
with <thead> and <tbody> elements, where <thead> defines table header and <tbody> defines the table body
Syntax:
<tfoot>
<tr></tr>
<tr></tr>
lt;/tfoot>
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML tfoot Tag</title>
<style>
table{
border-collapse: collapse;
}
thead,tfoot{
background-color:#3f87a6;
}
tbody{
background-color:#97ffff; }
</style>
</head>
<body>
<h1>Example of tfoot tag</h1>
<table border="1" >
<thead>
<tr>
<th>Items</th>
<th>Quantity</th>
<th>Expenditure</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Total</th>
<th>90</th>
<th>4175</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Books</td>
<td>5</td>
<td>1500</td>
</tr>
<tr>
<td>Drawing-Paper</td>
<td>50</td>
<td>800</td>
</tr>
<tr>
<td>Marker</td>
<td>35</td>
<td>1875</td>
</tr>
</tbody>
</table>
</body>
</html>
HTML <caption> tag
HTML <caption> tag is used to add a caption or title of an HTML table. It should be used inside the <table>
element and just after the <table> start tag. A table may contain only one <caption> element.
Syntax: <caption>Table title...</caption>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Caption Tag</title>
<style>
table, td, th {
border: 3px solid gray;
border-collapse: collapse;}
</style>
</head>
<body>
<h2>Example of Caption tag</h2>
<table width="800">
<caption>Employee Details</caption>
<thead>
<tr>
<th>Sr. No.</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.</td>
<td>Ankit Pandey</td>
<td>ankit2@gmail.com</td>
</tr>
<tr>
<td>2.</td>
<td>Ashvini Kumar</td>
<td>ashvini@gmail.com</td>
</tr>
<tr>
<td>3.</td>
<td>Swati Sharma</td>
<td>swati8@gmail.com</td>
</tr>
</tbody>
</table>
</body>
</html>
HTML Lists
HTML Lists are used to specify lists of information. All lists may contain one or more list elements. There are
three different types of HTML lists:
1. Ordered List or Numbered List (ol)
2. Unordered List or Bulleted List (ul)
3. Description List or Definition List (dl)
Note: We can create a list inside another list, which will be termed as nested List.
HTML Ordered List | HTML Numbered List
HTML Ordered List or Numbered List displays elements in numbered format. The HTML ol tag is used for
ordered list. We can use ordered list to represent items either in numerical order format or alphabetical order
format, or any format where an order is emphasized. There can be different types of numbered list:
o Numeric Number (1, 2, 3)
o Capital Roman Number (I II III)
o Small Romal Number (i ii iii)
o Capital Alphabet (A B C)
o Small Alphabet (a b c)
To represent different ordered lists, there are 5 types of attributes in <ol> tag.

Type Description

Type "1" This is the default type. In this type, the list items are numbered with numbers.

Type "I" In this type, the list items are numbered with upper case roman numbers.

Type "i" In this type, the list items are numbered with lower case roman numbers.
Type "A" In this type, the list items are numbered with upper case letters.

Type "a" In this type, the list items are numbered with lower case letters.

HTML Ordered List Example


Let's see the example of HTML ordered list that displays 4 topics in numbered list. Here we are not defining
type="1" because it is the default type.
the example to display list in roman number uppercase.
<ol type="I">
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ol>
Reversed Attribute:
1. This is a Boolean attribute of HTML <ol> tag, and it is new in HTML5 version. If you use the reversed
attribute with
2. tag then it will numbered the list in descending order (7, 6, 5, 4......1).
Example:
<ol reversed>
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ol>
HTML Unordered List | HTML Bulleted List
HTML Unordered List or Bulleted List displays elements in bulleted format . We can use unordered list where
we do not need to display items in any particular order. The HTML ul tag is used for the unordered list. There can
be 4 types of bulleted list:
o disc
o circle
o square
o none
To represent different ordered lists, there are 4 types of attributes in <ul> tag.

Type Description

Type "disc" This is the default style. In this style, the list items are marked with bullets.

Type "circle" In this style, the list items are marked with circles.

Type "square" In this style, the list items are marked with squares.

Type "none" In this style, the list items are not marked .

HTML Unordered List Example


ul type="circle"
<ul type="circle">
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ul>
HTML <var> tag
HTML <var> tag is a phrase tag which is used to define the variable for a mathematical equation, or in the
programming context.
The content within <var> tag renders in italic font in most of the browsers, but it can be overridden using
appropriate CSS.
Following are some related elements of <var> tag, which can also be used for the same context:
o <code>: To determine the computer programming code.
o <kbd>: To determine the keyboard input.
o <samp>: To determine the sample output.
Synta var>........</var>
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML var tag</title>
</head>
<body>
<h2>Example of var tag</h2>
<p>Following is equation for distributive law</p>
<p><var>a</var>(<var>b</var>+<var>c</var>)=<var>ab</var>+<var>ac</var></p>
</body>
</html>
HTML Description List | HTML Definition List
HTML Description List or Definition List displays elements in definition form like in dictionary. The <dl>, <dt>
and <dd> tags are used to define description list.
The 3 HTML description list tags are given below:
1. <dl> tag defines the description list.
2. <dt> tag defines data term.
3. <dd> tag defines data definition (description).
<dl>
<dt>HTML</dt>
<dd>is a markup language</dd>
<dt>Java</dt>
<dd>is a programming language and platform</dd>
<dt>JavaScript</dt>
<dd>is a scripting language</dd>
<dt>SQL</dt>
<dd>is a query language</dd>
</dl>

CSS
Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of
making web pages presentable. 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, as well as a variety of other effects. CSS is easy to learn and understand but
it provides a 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 the 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 the 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 cellphones or for printing.
 Global web standards – Now HTML attributes are being deprecated and it is being recommended to
use CSS. So it’s a good idea to start using CSS in all the HTML pages to make them compatible with
future browsers.

Cascading Style Sheets level 1 (CSS1) came out of W3C as a recommendation in December 1996. This
version describes the CSS language as well as a simple visual formatting model for all the HTML tags.
CSS2 became a W3C recommendation in May 1998 and builds on CSS1. This version adds support for
media-specific style sheets e.g. printers and aural devices, downloadable fonts, element positioning and
tables.
CSS Syntax

 The selector points to the HTML element you want to style.


 The declaration block contains one or more declarations separated by semicolons.
 Each declaration includes a CSS property name and a value, separated by a colon.
 Multiple CSS declarations are separated with semicolons, and declaration blocks are surrounded by curly
braces.

Example1:
p{
color: red;
text-align: center;
}
Example Explained
 p is a selector in CSS (it points to the HTML element you want to style: <p>).
 color is a property, and red is the property value
 text-align is a property, and center is the property value

Example 2:
<body style="text-align: center;">
<h2 style="color: red;">Welcome to My page</h2>
<p style="color: blue; font-size: 25px; font-
style: italic ;">This is a great website to learn technologies in very simple way. </p>
</body>

Three ways to apply CSS


To use CSS with HTML document, there are three ways:

o Inline CSS: Define CSS properties using style attribute in the HTML elements.
o Internal or Embedded CSS: Define CSS using <style> tag in <head> section.
o External CSS: Define all CSS property in a separate .css file, and then include the file with
HTML file using tag in section.

Inline CSS:
Inline CSS is used to apply CSS in a single element. It can apply style uniquely in each element.

To apply inline CSS, you need to use style attribute within HTML element. We can use as many
properties as we want, but each property should be separated by a semicolon (;).

Example:
<h3 style="color: red;
font-style: italic;
text-align: center;
font-size: 50px;
padding-top: 25px;">Learning HTML using Inline CSS</h3>

Internal CSS:
An Internal stylesheets contains the CSS properties for a webpage in <head> section of HTML
document. To use Internal CSS, we can use class and id attributes.

We can use internal CSS to apply a style for a single HTML page.

Example:
<!DOCTYPE html>
<html>
<head>
<style>
/*Internal CSS using element name*/
body{background-color:lavender;
text-align: center;}
h2{font-style: italic;
font-size: 30px;
color: #f08080;}
p{font-size: 20px;}
/*Internal CSS using class name*/
.blue{color: blue;}
.red{color: red;}
.green{color: green;}
</style>
</head>
<body>
<h2>Learning HTML with internal CSS</h2>
<p class="blue">This is a blue color paragraph</p>
<p class="red">This is a red color paragraph</p>
<p class="green">This is a green color paragraph</p>
</body>
</html>
External CSS:
An external CSS contains a separate CSS file which only contains style code using the class name, id
name, tag name, etc. We can use this CSS file in any HTML file by including it in HTML file using
<link> tag.

If we have multiple HTML pages for an application and which use similar CSS, then we can use external
CSS.

There are two files need to create to apply external CSS

o First, create the HTML file


o Create a CSS file and save it using the .css extension (This file only will only contain the styling
code.)
o Link the CSS file in your HTML file using tag in header section of HTML document.

Example:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>Learning HTML with External CSS</h2>
<p class="blue">This is a blue color paragraph</p>
<p class="red">This is a red color paragraph</p>
<p class="green">This is a green color paragraph</p>
</body>
</html>
body{
background-color:lavender;
text-align: center;
}
h2{
font-style: italic;
size: 30px;
color: #f08080;
}
p{
font-size: 20px;
}

.blue{
color: blue;
}
.red{
color: red;
}
.green{
color: green;
}
Commonly used CSS properties:

Properties-name Syntax Description

background-color background-color:red; It defines the background color of that element.

color color: lightgreen; It defines the color of text of an element

padding padding: 20px; It defines the space between content and the border.

margin margin: 30px; margin-left: It creates space around an element.

font-family font-family: cursive; Font-family defines a font for a particular element.

Font-size font-size: 50px; Font-size defines a font size for a particular


element.

text-align text-align: left; It is used to align the text in a selected position.

Basic CSS Selector


CSS selectors are used to select the content you want to style. Selectors are the part of CSS rule set. CSS
selectors select HTML elements according to its id, class, type, attribute etc.

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
 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 the value either red or
#F1F1F1 etc.
CSS Style Rule Syntax as follows:
selector { property: value }
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 the 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.

There are several different types of selectors in CSS.

1. CSS Element Selector


2. CSS Id Selector
3. CSS Class Selector
4. CSS Universal Selector
5. CSS Group Selector
1) CSS Element Selector
The element selector selects the HTML element by name.

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; }
2) CSS Id Selector
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; } This rule renders the content in
black for only
elements with id attribute set to black. The true power of id selectors is when they are used as the
foundation for descendant selectors. For example: #black h2 { color: #000000; } In this example, all level
2 headings will be displayed in black color when those headings will lie within tags having id attribute
set to black.
3. CSS Class Selector

3) CSS Class Selector


The class selector selects HTML elements with a specific class attribute. It is used with a period character
. (full stop symbol) followed by the class name.
Note: A class name should not be started with a number.
Let's take an example with a class "center".
<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is blue and center-aligned.</h1>
<p class="center">This paragraph is blue and center-aligned.</p>
</body>
</html>

4) CSS Universal Selector


The universal selector is used as a wildcard character. It selects all the elements on the pages.

<!DOCTYPE html>
<html>
<head>
<style>
*{
color: green;
font-size: 20px;
}
</style>
</head>
<body>
<h2>This is heading</h2>
<p>This style will be applied on every paragraph.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>

5) CSS Group Selector


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 class selectors together as shown below: #content, #footer,
#supplement { position: absolute; left: 510px; width: 200px; }

h1,h2,p {
text-align: center;
color: blue;
}

Example of group selectors


<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1>Hello Javatpoint.com</h1>
<h2>Hello Javatpoint.com (In smaller font)</h2>
<p>This is a paragraph.</p>
</body>
</html>
CSS Advance selectors and Combinators
CSS Combinators clarifies the relationship between two selectors, whereas the selectors in CSS are used
to select the content for styling.

There can be more than one simple selector in a CSS selector, and between these selectors, we can
include a combinator. Combinators combine the selectors to provide them a useful relationship and the
position of content in the document.
There are four types of combinators in CSS that are listed as follows:
1. General sibling selector (~)
2. Adjacent sibling selector (+)
3. Child selector (>)
4. Descendant selector (space)
5.
1.General Sibling Selector (~)
It uses the tlide (~) sign as the separator between the elements. It selects the elements that follow the
elements of first selector, and both of them are the children of the same parent. It can be used for
selecting the group of elements that share the common parent element.
It is useful when we have to select the siblings of an element even if they are not adjacent directly.
Syntax
element ~ element {
/*style properties*/
}
Suppose we have to select all <p> elements that are the siblings of <div> element, then we can write it
as:
div ~ p {
/*style properties*/
}

The figure given below helps us to understand the General sibling selector (~).

In this figure, the blocks with the green color are the selected blocks affected after using the general
sibling selector.
Example
In this example we are selecting the <p> elements that come after the <h1>. There is a <div> element
which will not get selected and the paragraph element inside the div will also not get selected. But
those <p> elements that come after the <div> will be affected.
This example will illustrate the use of a General sibling selector (~).
<!DOCTYPE html>
<html>
<head>
<title>General Sibling Selector</title>
<style>
body{
text-align: center;
}
h1 ~ p{
color: blue;
font-size: 25px;
font-weight: bold;
text-align: center;
}
div {
font-size: 32px;
}
</style>
</head>
<body>
<h1>General sibling selector (~) property</h1>
<p>It is the first paragraph element which will get effected.</p>
<div> It is the div element
<p> It is the paragraph under the div element </p>
</div>
<p>It is the paragraph element after the div</p>
<p>It is the paragraph element which will also get affected</p>
</body>
</html>

2.Adjacent Sibling Selector (+)


It uses the plus (+) sign as the separator between the elements. It matches the second element only when
the element immediately follows the first element, and both of them are the children of the same parent.
This sibling selector selects the adjacent element, or we can say that the element which is next to the
specified tag.
It only selects the element which is just next to the specified first element.
Syntax
element + element {
/*style properties*/
}
If we have to select the paragraph that comes immediately after another paragraph, then by using the
adjacent selector, it will be written as follows:
p+p{
/*style properties*/
}
Example
In this example we are selecting the <p> element that comes immediately after the <p> element. There is
an <div> element that will not be selected, and the paragraph element after the div will also not be
selected. But the <p> element that comes just next to the third paragraph will be affected.
3.Child Selector (>)
It uses the greater than (>) sign as the separator between the elements. It selects the direct descendant of
the parent. This combinator only matches the elements that are the immediate child in the document tree.
It is stricter as compared to the descendant selector because it selects the second selector only when the
first selector is its parent.
The parent element must always be placed at the left of the ">". If we remove the greater
than (>) symbol that designates this as a child combinator, then it will become the descendant selector.
Syntax
element > element {
/*style properties*/
}
If we have to select the paragraph elements that are the children of <div> element then by using the child selector,
it will be written as follows:
div > p {
/*style properties*/
}

4.Descendant Selector (space)


It uses the space as the separator between the elements. The CSS descendant selector is used to match the
descendant elements of a particular element and represent it using a single space. The word descendant
indicates nested anywhere in the DOM tree. It can be a direct child or deeper than five levels, but it will
still be referred to as a descendant.
It combines two selectors in which the first selector represents an ancestor (parent, parent's parent, etc.),
and the second selector represents descendants. The elements matched by the second selector are selected
if they have an ancestor element that matches the first selector.
Syntax
element element {
/*style properties*/
}
If we have to select the paragraph elements that are the children of an <div> element, then by using the
descendant selector, it will be written as follows:
div p {
/*style properties*/
}

CSS pseudo-classes
A pseudo-class can be defined as a keyword which is combined to a selector that defines the special state
of the selected elements. It is added to the selector for adding an effect to the existing elements based on
their states. For example, The ":hover" is used for adding special effects to an element when the user
moves the cursor over the element.

The names of the pseudo-class are not case-sensitive.

Syntax

A pseudo-class starts with a colon (:). Let's see its syntax.

1. selector: pseudo-class {
2. property: value;
3. }

Although there are various CSS pseudo-classes, here we are going to discuss some of the most commonly
used pseudo-classes. The widely used CSS classes are tabulated as follows:

pseudo-class Description

:active IIt is used to add style to an active element.


1. Example : a:active{
2. color: yellow;
3. }

:hover IIt adds special effects to an element when the user moves the mouse pointer over the element.
1. a:visited{
2. color: red;
3. }

:link IIt adds style to the unvisited link.

:visited IIt adds style to a visited link.


1. a:visited{
2. color: red;
3. }

:lang IIt is used to define a language to use in a specified element.


1. text-align:center;
2. }
3. p:lang(fr)
4. {
5. font-family:Verdana;
6. color:blue; }

:focus IIt selects the element which is focused by the user currently.
1. input:focus{
2. border:5px solid lightblue;
3. box-shadow:10px 10px 10px black;
4. color: blue;
5. width:300px;
6. }

:first-child It adds special effects to an element, which is the first child of another element.
1. <style>
2. h1:first-child {
3. text-indent: 200px;
4. color:blue;
5. }
6. </style>

Let's discuss the above pseudo-classes, along with an example.

:hover pseudo-class
This pseudo-class adds a special style to an element when the user moves the cursor over it. If you want
to make it effective, it must be applied after the ":link" and ":visited" pseudo-classes.

Example

<html>
<head>
<style>
body{
text-align:center;
}
h1:hover{
color:red;
}
h2:hover{
color:blue;
}
</style>
</head>

<body>
<h1>Hello world </h1>
<h2>This is an example of :hover pseudo class</h2>
</body>
</html>

CSS classes and pseudo-classes


The classes in CSS can be combined with pseudo-classes. We can write it as-

Syntax

selector.class: pseudo-class {
property: value;
}

We can understand it with the following example.

Example

<!DOCTYPE html>
<html>
<head>
<style>
body{
text-align:center;
}
div.hello:hover {
color: red;
font-size:40px;
}
</style>
</head>
<body>
<h1>CSS Classes and pseudo-classes</h1>
<h2>Move your cursor to the below text</h2>
<div class="hello">Hello World</p>

</body>
</html>
CSS Pseudo-elements
A pseudo-class can be defined as a keyword which is combined to a selector that defines the special state
of the selected elements. Unlike the pseudo-classes, the pseudo-elements are used to style the specific
part of an element, whereas the pseudo-classes are used to style the element.

As an example, a pseudo-element can be used to style the first letter or the first line of an element. The
pseudo-elements can also be used to insert the content after or before an element.

Syntax

Pseudo-element has a simple syntax which is given as follows:

selector::pseudo-element {
property: value;
}

We have used the double colon notation (::pseudo-element) in the syntax. In CSS3, the double colon
replaced the single colon notation for pseudo-elements. It was an attempt from W3C to differentiate
between the pseudo-elements and pseudo-classes. So, it is recommended to use double colon notation
(::pseudo-element) instead of using single-colon notation (:).

In CSS1 and CSS2, there is the use of a single colon (:) syntax for both pseudo-elements and pseudo-
classes. The single colon syntax is valid for pseudo-elements in CSS1 and CSS2 for backward
compatibility.

Although there are several CSS pseudo-elements, we are discussing some of the most commonly used.
The widely used CSS pseudo-elements are tabulated as follows:

pseudo-element Description

::first-letter (:first-letter) It selects the first letter of the text.

::first-line (:first-line) It styles the first line of the text.

::before (:before) It is used to add something before the element's content.

::after (:after) It is used to add something after the element's content.

::selection It is used to select the area of an element that is selected by the user.

The ::first-letter pseudo-element


As its name implies, it affects the first letter of the text. It can be applied only to block-level elements.
Instead of supporting all CSS properties, it supports some of the CSS properties that are given below.

o Color properties (such as color)


o Font properties (such as font-style, font-family, font-size, font-color, and many more).
o Margin properties (such as margin-top, margin-right, margin-bottom, and margin-left).
o Border properties (like border-top, border-right, border-bottom, border-left, border-color, border-
width, and many more).
o Padding properties (such as padding-top, padding-right, padding-bottom, and padding-left).
o Background properties (such as background-color, background-repeat, background-image, and
background-position).
o Text related properties (such as text-shadow, text-transform, text-decoration, etc.).
o Other properties are vertical-align (only when the float is 'none') word-spacing, line-height, line-
spacing, etc.

<style>
body{
text-align: center;
}
h1::first-letter {
font-family: Lucida Calligraphy;
font-size: 3cm;
color: red;
text-shadow: 5px 8px 9px green;
}
h1{
color: blue;
}
</style>

The ::first-line pseudo-element


It is similar to the ::first-letter pseudo-element, but it affects the entire line. It adds the special effects to
the first line of the text. It supports the following CSS properties:

o Color properties (such as color)


o Font properties (such as font-style, font-family, font-size, font-color, and many more).
o Background properties (such as background-color, background-repeat, background-image, and
background-position).
o Other properties are word-spacing, letter-spacing, line-height, vertical-align, text-transform, text-
decoration.

<style>
body{
text-align: center;
}
h1::first-line {
font-family: Lucida Calligraphy;
font-size: 1cm;
color: red;
text-shadow: 5px 8px 9px green;
}
</style>
The ::before pseudo-element
It allows us to add something before the element's content. It is used to add something before the specific
part of an element. Generally, it is used with the content property.
We can also add the regular strings or images before the content using this pseudo-element.
Example
<html>
<head>
<style>
body{
text-align: center;
}
h1::before {
content: "'Hello World.'";
color: red;
}
</style>
</head>
<body>
<h1>Welcome to the javaTpoint.com. </h1>
<h2> This is an example of ::before pseudo-element. </h2>
<h3> In the first line the "Hello World" has added by using the pseudo-element ::before </h3>
</body>
</html>

The ::after pseudo-element


It works similar to ::before pseudo-element, but it inserts the content after the content of the element. It
is used to add something after the specific part of an element. Generally, it is used with the content
property.

It also allows us to add regular strings or images after the content.

Example

<html>
<head>
<style>
body{
text-align: center;
}
h1::after {
content: "'Welcome to the javaTpoint.com.'";
color: red;
}
</style>
</head>
<body>
<h1> Hello World. </h1>
<h2> This is an example of ::after pseudo-element. </h2>
<h3> In the first line the "Welcome to the javaTpoint.com." has added by using the pseudo-element ::after </h3>
</body>
</html>

CSS classes and pseudo-element


The pseudo-elements can be combined with CSS classes to style the specific element having that class.
The syntax of combining the CSS classes with the pseudo-elements is given below.
Syntax
It can be written as:
selector.class::pseudo-element {
property: value
}
Example

This example will affect the first letter of those <h1> elements that have class="example" rather than
affecting the all <h1> elements.

<html>
<head>
<style>
body{
text-align: center;
}
h1.example::first-letter {
color: red;
font-size: 2cm;
font-family: Lucida Calligraphy;
}
</style>
</head>
<body>
<h1 class="example"> Hello World. </h1>
<h1> Welcome to the javaTpoint.com. </h1>
<h3> This is an example of pseudo-element with CSS classes.</h3>
</body>
</html>

CSS Box Model


The components that can be depicted on the web page consist of one or more than one rectangular box.

A CSS box model is a compartment that includes numerous assets, such as edge, border, padding and
material. It is used to develop the design and structure of a web page. It can be used as a set of tools to
personalize the layout of different components. According to the CSS box model, the web browser
supplies each element as a square prism.

The following diagram illustrates how the CSS properties


of width, height, padding, border and margin dictate that how much space an attribute will occupy on a
web page.
The CSS box model contains the different properties in CSS. These are listed below.

o Border
o Margin
o Padding
o Content

Now, we are going to determine the properties one by one in detail.

Border Field

It is a region between the padding-box and the margin. Its proportions are determined by the width and
height of the boundary.

Margin Field

This segment consists of the area between the boundary and the edge of the border.

The proportion of the margin region is equal to the margin-box width and height. It is better to separate
the product from its neighbor nodes.

Padding Field

This field requires the padding of the component. In essence, this area is the space around the subject area
and inside the border-box. The height and the width of the padding box decide its proportions.

Content Field

Material such as text, photographs, or other digital media is included in this area.
It is constrained by the information edge, and its proportions are dictated by the width and height of the
content enclosure.

Elements of the width and height


Typically, when you assign the width and height of an attribute using the CSS width and height assets, it
means you just positioned the height and width of the subject areas of that component. The additional
height and width of the unit box is based on a range of influences.

The specific area that an element box may occupy on a web page is measured as follows-

Size of the Properties of CSS


box

Height height + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-


bottom

Width width + padding-left + padding-right + border-left + border-right + margin-left + margin-right

Example 1
Here, to explain the CSS box model, we have an instance.

<!DOCTYPE html>
<head>
<title>CSS Box Model</title>
<style>
.main
{
font-size:30px;
font-weight:bold;
Text-align:center;
}
.gfg
{ margin-left:50px;
border:50px solid Purple;
width:300px;
height:200px;
text-align:center;
padding:50px;
}
.gfg1
{
font-size:40px;
font-weight:bold;
color:black;
margin-top:60px;
background-color:purple;
}
.gfg2
{
font-size:20px;
font-weight:bold;
background-color:white;
}
</style>
</head>
<body>
<div class = "main">CSS Box-Model Property</div>
<div class = "gfg">
<div class = "gfg1">JavaTpoint</div>
<div class = "gfg2">A best portal for learn Technologies</div>
</div>
</body>
</html>

Setting the Padding Size of an HTML Element With CSS


Next, let’s increase the padding size to study how it changes the display of the <div> element. Add the
following highlighted line to your CSS rule in your styles.css file to set the padding to 25 pixels:
[label styles.css]
.yellow-div {
background-color:yellow;
width: 500px;
padding:25px;
}
Save the styles.css file and reload the index.html file in your browser. The size of the yellow box should
have expanded to allow for 25 pixels of space between the text content and the perimeter of the box:
You can change the size of the padding by adjusting the padding value size. You can also change the
padding size of specific sides of the element by using the following properties: padding-left, padding-
right, padding-top, padding-bottom. For example, try replacing the declaration padding:25px; in
your styles.css file with the highlighted snippet below:
[label styles.css]
.yellow-div {
background-color:yellow;
width: 500px;
padding-left:25px;
padding-right: 50px;
padding-top: 100px;
padding-bottom: 25px;
}
Save the styles.css file and load the index.html file in your browser

Adjusting the Border Size, Color, and Style of an HTML Element


With CSS
Let’s now practice setting values for the border of an HTML element. The border property lets you set
the size, the color, and the style (such as solid, dashed, dotted, inset, and outset) of an HTML element. These
three values are set by assigning them to the border property like so:

selector {
border: size style color;
}

Try adding the following highlighted declaration to add a solid black border that is five pixels wide:

styles.css
.yellow-div {
background-color:yellow;
width: 500px;
padding: 25px;
border: 5px solid black;
}
(You may want to erase your different padding declarations from the previous tutorial section and replace
them with the single padding:25px; declaration to keep the ruleset manageable). Save the styles.css file and
reload index.html in your browser to inspect the changes. Your yellow box should now have a border with
the values you set in the CSS rule:

You can try changing the values to study how they change the display of the element in the browser. Like with
padding, you can also specify the border side you’d like to adjust with the properties border-right, border-
left, border-top, border-bottom.

Setting Margin Size of an HTML Element With CSS


Next, let’s try adjusting the size of the margins of an element with CSS. In this exercise, we’ll give the
margins a very large value so that it is easy to see how margin size is displayed in the browser. Add the
following highlighted declaration to your ruleset in your styles.css file to set the margin to 100 pixels:
.yellow-div {
background-color:yellow;
width: 500px;
padding: 25px;
border: 5px solid black;
margin:100px;
}
Save the styles.css file and reload index.html in your browser to inspect the changes. The yellow box should
have moved 100 pixels down and 100 pixels to the right to allow for the 100 pixels of margin space
between its border and the edges of the viewport:
Like the padding and border, the sizes of specific sides of the margin can be set using margin-left, margin-
right, margin-top, and margin-bottom.
Before moving on, add another <div> container to the page to study how the margin affects the position of
nearby content. Without erasing anything, add the additional CSS ruleset to your

.blue-div {
height:100px;
width:100px;
background-color: blue;
}
Save the file and return to your index.html file. Without erasing anything, add the following <div> element
to your file and assign it the blue-div class:
Layout and Positioning: Display Property?
The display property specifies the display behavior (the type of rendering box) of an
element. In HTML, the default display property value is taken from the HTML
specifications or from the browser/user default style sheet.

It simply means that every HTML element has a display value attached with by
default. For example- <div>, <h1>-<h6>, <p>,<form>, <header>, <footer> and <section> has a
display value of 'block'.
On the other hand <span> and <a> has a display value of 'inline' and <img> has a
display value of 'inline-block'

In this article, we will discuss 4 types of display value: 1. Block, 2. Inline 3. Inline-
Block and 4. None.
 Block - The element generates a block element box, generating line breaks both before and after the
element when in the normal flow. In simple terms, a block-level element will take maximum space that is
available and also will form in its own line.
<style>
p{
display: block;
}
</style>

 Inline- behaves exactly the opposite of 'block'. Inline takes the minimum space (shown by the background
color of light gray) that is required by the content and will not form in its own line.
The inline elements are:
<span>
<a>
<em>
<b> etc.
1. Example :
<style>
p{
display: inline;
}
</style>

Inline-block - For the 'inline-block' element we can specify the dimensions of the elements such as width and
height. 'inline-block' behave just like an 'inline' element with the benefit of specifying the width and a height.
A great example of this is an <img> element.
We can not specify the dimensions with an 'inline' element.
<style>
p{
display: inline-block;
}
</style>
None - Turns off the display of an element so that it has no effect on the layout (the document is rendered as
though the element did not exist). All descendant elements also have their display turned off.
CSS Float
The CSS float property is a positioning property. It is used to push an element to the left or right,
allowing other element to wrap around it. It is generally used with images and layouts.

To understand its purpose and origin, let's take a look to its print display. In the print display, image is set
into the page such that text wraps around it as needed.

Its web layout is also just similar to print layout.

How it works
Elements are floated only horizontally. So it is possible only to float elements left or right, not up or
down.

1. A floated element may be moved as far to the left or the right as possible. Simply, it means that a floated
element can display at extreme left or extreme right.
2. The elements after the floating element will flow around it.
3. The elements before the floating element will not be affected.
4. If the image floated to the right, the texts flow around it, to the left and if the image floated to the left, the
text flows around it, to the right.

CSS Float Properties

Property Description Values

clear The clear property is used to avoid elements after the floating elements which left, right, both, none,
flow around it. inherit

float It specifies whether the box should float or not. left, right, none, inherit

CSS Float Property Values

Value Description
none It specifies that the element is not floated, and will be displayed just where it occurs in the text. this is a
default value.

left It is used to float the element to the left.

right It is used to float the element to the right.

initial It sets the property to its initial value.

inherit It is used to inherit this property from its parent element.

CSS Float Property Example


Let's see a simple example to understand the CSS float property.

<!DOCTYPE html>
<html>
<head>
<style>
img {
float: right;
}
</style>
</head>
<body>
<p>The following paragraph contains an image with style
<b>float:right</b>. The result is that the image will float to the right in the paragraph.</p>
<img src="good-morning.jpg" alt="Good Morning Friends"/>
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
</p>
</body>
</html>

CSS Position
The CSS position property is used to set position for an element. it is also used to place an element
behind another and also useful for scripted animation effect.

You can position an element using the top, bottom, left and right properties. These properties can be used
only after position property is set first. A position element's computed position property is relative,
absolute, fixed or sticky.

Let's have a look at following CSS positioning:


1. CSS Static Positioning
2. CSS Fixed Positioning
3. CSS Relative Positioning
4. CSS Absolute Positioning

1) CSS Static Positioning


This is a by default position for HTML elements. It always positions an element according to the normal
flow of the page. It is not affected by the top, bottom, left and right properties.

2) CSS Fixed Positioning


The fixed positioning property helps to put the text fixed on the browser. This fixed test is positioned
relative to the browser window, and doesn't move even you scroll the window.

<style>
p.pos_fixed {
position: fixed;
top: 50px;
right: 5px;
color: blue;
}
</style>

3) CSS Relative Positioning


The relative positioning property is used to set the element relative to its normal position.

<style>
h2.pos_left {
position: relative;
left: -30px;
}
h2.pos_right {
position: relative;
left: 30px;
}
</style>

4) CSS Absolute Positioning


The absolute positioning is used to position an element relative to the first parent element that has a
position other than static. If no such element is found, the containing block is HTML.
<style>
h2 {
position: absolute;
left: 150px;
top: 250px;
}
</style>
With the absolute positioning, you can place an element anywhere on a page.

All CSS Position Properties

No. property description values

1) bottom It is used to set the bottom margin auto, length, %, inherit


edge for a positioned box.

2) clip It is used to clip an absolutely shape, auto, inherit


positioned element.

3) cursor It is used to specify the type of url, auto, crosshair, default, pointer, move, e-
cursors to be displayed. resize, ne-resize, nw-resize, n-resize, se-resize,
sw-resize, s-resize, w-resize, text, wait, help

4) left It sets a left margin edge for a auto, length, %, inherit


positioned box.

5) overflow This property is used to define what auto, hidden, scroll, visible, inherit
happens if content overflow an
element's box.

6) position It is used to specify the type of absolute, fixed, relative, static, inherit
positioning for an element.

7) right It is used to set a right margin edge auto, length, %, inherit


for a positioned box.

8) top It is used to set a top margin edge auto, length, %, inherit


for a positioned box.

9) z-index It is used to set stack order of an number, auto, inherit


element.

CSS Flexbox
CSS3 Flexible boxes also known as CSS Flexbox, is a new layout mode in CSS3.

The CSS3 flexbox is used to make the elements behave predictably when they are used with different
screen sizes and different display devices. It provides a more efficient way to layout, align and distribute
space among items in the container.
It is mainly used to make CSS3 capable to change its item?s width and height to best fit for all available
spaces. It is preferred over block model.

The CSS3 flexbox contains flex containers and flex items.

Flex container:The flex container specifies the properties of the parent. It is declared by setting the
display property of an element to either flex or inline-flex.

Flex items:The flex items specify properties of the children. There may be one or more flex items inside
a flex container.

Note:Flexbox specifies how flex items are set inside a flex container. It sets the flex items inside a flex
container along a flex line. By default, there is only one flex line per flex container. Everything outside a
flex container and inside a flex item is considered as usual.

Let's take an example to show three flex items within a flex container. By default, they are set along the
horizontal flex line, from left to right:

CSS3 Flexbox Properties


Following is a list of CSS3 Flexbox properties:

property description

display it is used to specify the type of box used for an html element.

flex- it is used to specify the direction of the flexible items inside a flex container.
direction

justify- it is used to align the flex items horizontally when the items do not use all available space on
content the main-axis.

align-items it is used to align the flex items vertically when the items do not use all available space on the
cross-axis.

flex-wrap it specifies whether the flex items should wrap or not, if there is not enough room for them on
one flex line.
align-content it is used to modify the behavior of the flex-wrap property. it is similar to align-items, but
instead of aligning flex items, it aligns flex lines.

flex-flow it specifies a shorthand property for flex-direction and flex-wrap.

order it specifies the order of a flexible item relative to the rest of the flex items inside the same
container.

align-self it is used on flex items. it overrides the container's align-items property.

flex it specifies the length of a flex item, relative to the rest of the flex items inside the same
container.

Example:

<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<style>
.flex-container {
display: -webkit-flex;
display: flex;
width: 400px;
height: 200px;
background-color: lightpink;
}
.flex-item {
background-color: brown;
width: 100px;
height: 100px;
margin: 10px;
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item">flex item 1</div>
<div class="flex-item">flex item 2</div>
<div class="flex-item">flex item 3</div>
</div>
</body>
</html>

CSS flex-grow property


The CSS flex-grow property specifies how much space a flex item should take if there is available space.
The remaining space can be defined as the flex container size minus the size of all flex items together.

This property defines how much an item will grow inside the container as compared to the other items. It
can be defined as the ability of an item to grow as compared to the other items of the container.
For example, if we set flex-grow to 1 for all items, each item will set to an equal size in the container.
But if we give any of the items a value of 2, then the corresponding item will take up space twice than the
others.

It sets the flex grow factor (a number that determines how much the flex-item will grow) of a flex-item.
This CSS property is used to increase the size of the flex-item. It only works on the flex-items, so if the
container's item is not a flex-item, the flex-grow property will not affect the corresponding item.
Generally, this CSS property is used with the other flex properties that are flex-shrink and flex-basis and
usually defined by the flex shorthand to ensure that all values are set.

Syntax
1. flex-grow: number| initial | inherit;

Values
number: It is the positive number that determines the flex-grow factor. Its default value is 0 and does not
allow the negative value. When it sets to zero, the item will not grow, even if there is a space available.
The element will take the space it requires.

initial: It sets this property to its default value.

inherit: It inherits this property from its parent element.

Example
In this example, there are two containers, and we set the flex-grow: 0; for all items of the first container
and flex-grow: 1; for all items of the second container. We can see the items with the flex-grow: 0; takes
the space they require, and the items with flex-grow: 1; takes the remaining space with equal size.

<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: -webkit-flex;
display: flex;
background-color: green;
}
.flex-item {
background-color: lightgreen;
text-align: center;
font-size: 25px;
width: 100px;
height: 100px;
padding-top: 20px;
margin: 5px;
}
</style>
</head>
<body>
<h1> flex-grow: 0; </h1>

<div class="container">
<div class="flex-item" style = "flex-grow: 0;"> flex-item 1 </div>
<div class="flex-item" style = "flex-grow: 0;"> flex-item 2 </div>
<div class="flex-item" style = "flex-grow: 0;"> flex-item 3 </div>
</div>
<h1> flex-grow: 1; </h1>
<div class="container">
<div class="flex-item" style = "flex-grow: 1;"> flex-item 1 </div>
<div class="flex-item" style = "flex-grow: 1;"> flex-item 2 </div>
<div class="flex-item" style = "flex-grow: 1;"> flex-item 3 </div>
</div>

</div>
</body>
</html>

CSS flex-shrink property


The CSS flex-shrink property specifies how much an item will shrink than the other items of the
container. It sets the flex shrink factor (a number that determines how much the flex item will shrink) of a
flex-item.

We can distribute the negative space among the flex-items such that some of the items take up more
negative space than others. It can be done by setting the value of flex-shrink property to 2. So, the flex-
item with the flex-shrink: 2; will shrink twice than the flex-shrink: 1; i.e., it takes up twice as much
negative space than others. The higher the flex-shrink value causes the item to shrink more than the
others.

When distributing the negative space, the flex shrink factor is multiplied with the flex-basis. The flex-
basis is the initial size of the item.

It only works on the flex-items, so if the item in the container is not a flex-item, the flex-shrink property
will not affect the corresponding item. Generally, this CSS property is used with the other flex properties
that are flex-grow and flex-basis and usually defined by the flex shorthand to ensure that all values are
set.

1. flex-shrink: number| initial | inherit;


Values
number: It is the positive number that determines the flex shrink factor. Its default value is 1, which
indicates that items don't shrink by default. It does not allow negative value. This value specifies how
much the item will shrink compared to the other flexible items.
initial: It sets this property to its default value.
inherit: It inherits this property from its parent element.
Example
In this example, there are two containers, each having five flex-items. The width and height of the
containers are 400px and 100px.
In the first container, we apply the flex-shrink: 5; to the third item, flex-shrink: initial; to the fourth
item, and flex-shrink: inherit; to the fifth item.
In the second container, we apply the flex-shrink: 8; to the second item, flex-shrink: 10; to the third
item, and flex-shrink: 6; to the fourth item.
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 400px;
height: 100px;
border: 5px solid red;
display: flex;
background-color: blue;
margin: 30px;
}
.flex-item{
background-color: lightblue;
font-size: 25px;
margin: 5px;
flex-grow: 1;
flex-shrink: 1;
flex-basis: 100px;
}

</style>
</head>
<body>

<h1> Example of the flex-shrink property </h1>


<div class="container">
<div class = "flex-item"></div>
<div class = "flex-item"></div>
<div class = "flex-item" style = "flex-shrink: 5;"> 5 </div>
<div class = "flex-item" style = "flex-shrink: initial;"> initial </div>
<div class = "flex-item" style = "flex-shrink: inherit;"> inherit </div>
</div>
<div class="container">
<div class = "flex-item"></div>
<div class = "flex-item" style = "flex-shrink: 8;"> 8 </div>
<div class = "flex-item" style = "flex-shrink: 10;"> 10 </div>
<div class = "flex-item" style = "flex-shrink: 6;"> 6 </div>
<div class = "flex-item"></div>
</div>

</body>
</html>

CSS Layout
CSS layout is easy to design. We can use CSS layout to design our web page such as home page, contact
us, about us etc.

There are 3 ways to design layout of a web page:

1. HTML Div with CSS: fast and widely used now.


2. HTML Table: slow and less preferred.
3. HTML Frameset: deprecated now.

A CSS layout can have header, footer, left pane, right pane and body part. Let's see a simple example
of CSS layout.

CSS layout example


<!DOCTYPE html>
<html>
<head>
<style>
.header{margin:-8px -8px 0px;background-image:linear-gradient(145deg,#7379ff,#b524ef);color:white;text-
align:center;padding:10px;}
.container{width:100%}
.left{width:15%;float:left;}
.body{width:65%;float:left;background-color:pink;padding:5px;}
.right{width:15%;float:left;}
.footer{margin:-8px;clear:both;background-image:linear-gradient(145deg,#7379ff,#b524ef);color:white;text-
align:center;padding:10px;}
</style>
</head>
<body>
<div class="header"><h2>JavaTpoint</h2></div>

<div class="container">
<div class="left">
<p>Left Page</p>
</div>
<div class="body">
<h1>Body Page</h1>
<p>Page Content goes here</p><p>Page Content goes here</p><p>Page Content goes here</p>
<p>Page Content goes here</p><p>Page Content goes here</p><p>Page Content goes here</p>
<p>Page Content goes here</p><p>Page Content goes here</p><p>Page Content goes here</p>
<p>Page Content goes here</p><p>Page Content goes here</p><p>Page Content goes here</p>
<p>Page Content goes here</p>
</div>
<div class="right">
<p>Right Page</p>
</div>
</div>

<div class="footer">
<p>Footer</p>
</div>

</body>
</html>

CSS Grid
A grid can be defined as an intersecting set of horizontal lines and vertical lines. CSS Grid layout divides
a page into major regions. It defines the relationship between the parts of a control built
from HTML primitives in terms of layer, position, and size. Grid property offers a grid-based layout
system having rows and columns. It makes the designing of web pages easy without positioning and
floating.
Similar to the table, it enables a user to align the elements into rows and columns. But compare to tables,
it is easy to design layout with the CSS grid. We can define columns and rows on the grid by using grid-
template-rows and grid-template-columns properties.
The CSS grid property is supported in browsers such as Google Chrome, Internet Explorer, Firefox,
Safari, and Opera.

Grid Container
We can define the grid container by setting the display property to grid or inline-grid on an element.
Grid container contains grid items that are placed inside rows and columns.
Let's see a simple example of a grid in CSS.
Example
<!DOCTYPE html>
<html>

<head>

<style>
.main {
display: grid;
grid: auto auto / auto auto auto auto;
grid-gap: 10px;
background-color: black;
padding: 10px;
}

.num {
background-color: grey;
text-align: center;
color: white;
padding: 10px 10px;
font-size: 30px;
}
</style>
</head>

<body>
<div class="main">
<div class="num">One</div>
<div class="num">Two</div>
<div class="num">Three</div>
<div class="num">Four</div>
<div class="num">Five</div>
<div class="num">Six</div>
<div class="num">Seven</div>
<div class="num">Eight</div>
</div>

</body>

</html>
properties:
o grid-template-columns: It is used to specify the size of the columns.
o grid-template-rows: It is used to specify the row size.
o grid-template-areas: It is used to specify the grid layout by using the named items.
o grid-auto-rows: It is used to specify the automatic size of the rows.
o grid-auto-columns: It is used to specify the automatic size of the columns.
o grid-auto-flow: It is used to specify how to place auto-placed items and the automatic row size.

The justify-content property


It is used to align the entire grid within the container. It includes values such as:
o space-evenly: It provides equal space in between or around the columns.
o space-around: It provides equal space around the columns.
o space-between: It gives an equal amount of space between the columns.
o center: It is used to align the grid in the middle of the container.
o start: It is used to align the grid at the beginning of the container.
o end: It is used to align the grid at the end of the container.
The align-content property
It is used to align the entire grid within the container vertically.
Note: It is noted that the total height of the grid should be less than the height of the container for any effect
of the align-content property.
The values of the align-content property are the same as the values of the justify-content property.
<style>
.grid-container1 {
display: grid;
justify-content: space-evenly;
grid-template-columns: 50px 50px 50px; /*Make the grid smaller than the container*/
grid-gap: 10px;
background-color: #2196F3;
padding: 10px;
}

.grid-container2 {
display: grid;
justify-content: space-around;
grid-template-columns: 50px 50px 50px; /*Make the grid smaller than the container*/
grid-gap: 10px;
background-color: red;
padding: 10px;
}

.grid-container3 {
display: grid;
justify-content: space-between;
grid-template-columns: 50px 50px 50px; /*Make the grid smaller than the container*/
grid-gap: 10px;
background-color: green;
padding: 10px;
}

.grid-container4 {
display: grid;
justify-content: end;
grid-template-columns: 50px 50px 50px; /*Make the grid smaller than the container*/
grid-gap: 10px;
background-color: violet;
padding: 10px;
}
</style>
<body>

<b>CONTAINER WITH SPACE-EVENLY VALUE</b>


<div class="grid-container1">
<div class='num'>1</div>
<div class='num'>2</div>
<div class='num'>3</div>
</div>

<b>CONTAINER WITH SPACE-AROUND VALUE</b>


<div class="grid-container2">
<div class='num'>1</div>
<div class='num'>2</div>
<div class='num'>3</div>
</div>

<b>CONTAINER WITH SPACE-BETWEEN VALUE</b>


<div class="grid-container3">
<div class='num'>1</div>
<div class='num'>2</div>
<div class='num'>3</div>
</div>

<b>CONTAINER WITH END VALUE</b>


<div class="grid-container4">
<div class='num'>1</div>
<div class='num'>2</div>
<div class='num'>3</div>
</div>

</body>
Unit III
Advance HTML and CSS Techniques

HTML table advanced features and accessibility


Advanced features of HTML tables — such as captions/summaries and grouping your rows into table
head, body and footer sections — as well as looking at the accessibility of tables for visually impaired
users.

Adding a <caption>,<thead>,<tfoot>,<tbody>are the advance features in html table

Caption: You can give your table a caption by putting it inside a <caption> element and nesting that inside
the <table> element. You should put it just below the opening <table> tag.
<table>
<caption>
Dinosaurs in the Jurassic period
</caption>


</table>
As your tables get a bit more complex in structure, it is useful to give them more structural definition. One clear
way to do this is by using <thead>, <tfoot>, and <tbody>, which allow you to mark up a header, footer, and body
section for the table.
To use them:

 The <thead> element must wrap the part of the table that is the header — this is usually the first
row containing the column headings, but this is not necessarily always the case. If you are
using <col>/<colgroup> element, the table header should come just below those.
 The <tfoot> element needs to wrap the part of the table that is the footer — this might be a final
row with items in the previous rows summed, for example. You can include the table footer right
at the bottom of the table as you'd expect, or just below the table header (the browser will still
render it at the bottom of the table).
 The <tbody> element needs to wrap the other parts of the table content that aren't in the table
header or footer. It will appear below the table header or sometimes footer, depending on how
you decided to structure it.

tbody {
font-size: 95%;
font-style: italic;
}

tfoot {
font-weight: bold;
}
Nesting Tables
It is possible to nest a table inside another one, as long as you include the complete structure, including
the <table> element. This is generally not really advised, as it makes the markup more confusing and less
accessible to screen reader users, and in many cases you might as well just insert extra
cells/rows/columns into the existing table. It is however sometimes necessary, for example if you want to
import content easily from other sources.

The following markup shows a simple nested table:

<table id="table1">
<tr>
<th>title1</th>
<th>title2</th>
<th>title3</th>
</tr>
<tr>
<td id="nested">
<table id="table2">
<tr>
<td>cell1</td>
<td>cell2</td>
<td>cell3</td>
</tr>
</table>
</td>
<td>cell2</td>
<td>cell3</td>
</tr>
<tr>
<td>cell4</td>
<td>cell5</td>
<td>cell6</td>
</tr>
</table>

HTML Multimedia
Multimedia on the web is sound, music, videos, movies, and animations

Multimedia comes in many different formats. It can be almost anything you can hear or see, like images,
music, sound, videos, records, films, animations, and more.

Web pages often contain multimedia elements of different types and formats.

Multimedia Formats
Multimedia elements (like audio or video) are stored in media files.

The most common way to discover the type of a file, is to look at the file extension.

Multimedia files have formats and different extensions like: .wav, .mp3, .mp4, .mpg, .wmv, and .avi.

ommon Video Formats


There are many video formats out there.

The MP4, WebM, and Ogg formats are supported by HTML.

The MP4 format is recommended by YouTube.

MP3 is the best format for compressed recorded music. The term MP3 has become synonymous with digital
music.
Only MP3, WAV, and Ogg audio are supported by the HTML standard.
Video: The HTML <video> element is used to show a video on a web page.
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

The controls attribute adds video controls, like play, pause, and volume.

It is a good idea to always include width and height attributes. If height and width are not set, the page might
flicker while the video loads.

The <source> element allows you to specify alternative video files which the browser may choose from. The
browser will use the first recognized format.

The text between the <video> and </video> tags will only be displayed in browsers that do not support
the <video> element.

HTML Video Tags


Tag Description

<video> Defines a video or movie

<source> Defines multiple media resources for media elements, such as <video> and <audio>

<track> Defines text tracks in media players

HTML Audio
The HTML <audio> element is used to play an audio file on a web page.

The HTML <audio> Element


To play an audio file in HTML, use the <audio> element:
Example
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
HTML Audio - How It Works
The controls attribute adds audio controls, like play, pause, and volume.
The <source> element allows you to specify alternative audio files which the browser may choose from. The
browser will use the first recognized format.
The text between the <audio> and </audio> tags will only be displayed in browsers that do not support
the <audio> element.
To start an audio file automatically, use the autoplay attribute:
Example
<audio controls autoplay>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

HTML Audio Tags


Tag Description

<audio> Defines sound content

<source> Defines multiple media resources for media elements, such as <video> and <audio>

HTML Responsive web Design


Responsive web design is used to make your web page look appropriate, good, and well placed on all
devices (desktop, tablet, smartphone etc.)

Responsive Web Design comprises two words i.e., responsive and web design. Responsive
means to respond and web design means to design website. Therefore, responsive web design
generally means website that respond to or resize or adjust itself depending upon screen size it
is being seen through. It automatically adjusts to fit user’s screen whether it’s desktop, laptop,
mobile, tablet, etc. It only uses one layout for web page and it can be done either using CSS
and HTML or CSS3 and HTML5.
When to use it?
Responsive web design is a way by which website that contain flexible layout that
automatically scale its content and elements according to screen size on which it is viewed. It
simply resizes, shrink, enlarge, hide web pages so that it can look better on all type of devices
and does not have to zoom and pan to see any content on website. But still some people get
confused in deciding when to use responsive web design. Below given are some points to clear
this confusion:
 Responsive web design is best for small to large scale business or company that want to
grow their business. For growth and success, they need to update their existing website and
get it converted into responsive website that not only help one to rank higher in search
engine, but also offer better user experience to visitors.
 Responsive web design is best for new business that wants to build a new brand site and get
ahead to other competitors. They need to create a responsive web design because of
responsive design reach more audience, stay in touch with customers through mobile,
increase conversions, etc.
 Responsive web design is best for service-based industries because it includes creative UX
and UI design and is made up of images and text. Images and graphics are also clear and
crisp when viewed on mobile device.
 Responsive web design is also best for companies that have less or tight budget and limited
resources because responsive design is budget friendly. One has to invest their money and
effort only in one rather because of its flexibility.
 Responsive web design owes its adaptability to its main components: fluid Grids, flexible
images, and CSS media queries:

Fluid Grid
In print, publishers determine the size of what is displayed (and where) in absolute
measures. When the internet arrived, this trend continued, and designers defined websites in
pixel sizes.

The "p" in “720p” and “1080p” stands for “progressive scan,” and the number refers to the height
dimensions of the image in pixels.

For responsive design, the absolute size method doesn't work because devices vary in size.
Therefore, responsive design uses relative sizes.
In this image, you can see that the fixed version of the content has the same width regardless of the
device, whereas in the fluid version, the content fills the available screen space of the device.

 2. Flexible Images

 Images must scale and adapt to fit different screen sizes. Flexibility is achieved by setting the
maximum width of an image to 100% of its parent container. As the container resizes, the
image scales proportionally to fit within it. Using CSS properties like max-width: 100%; or
height: auto, images can dynamically adjust. Flexibility prevents images from overflowing or
getting cropped on smaller screens. They remain visually appealing and aligned within the
responsive layout.

Responsive Images
Images which can be scaled nicely to fit any browser size are known as responsive images.
How to make Image Responsive?
By using the width property
Set the CSS width property to 100% to make the image responsive and scale up and down.

Example

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Responsive Image</h2>
<p>When we set the CSS width property to 100%, it makes the image responsive.
Resize the browser window to see the effect.</p>
<img src="img_girl.jpg" style="width:100%;">( change image)
</body>
</html>

Change images according to the browser width


By using the HTML <picture> element, you can set two or more imagesaccording to the browser width.
It will change the picture when you change the browser-size. i.e. desktop and phone.
Example

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Change Images Depending on Browser Width</h2>
<p>Resize the browser width and the image will change at 600px and 1500px.</p>
<picture>
<source srcset="img_smallflower.jpg" media="(max-width: 600px)">(Change image)
<source srcset="img_flowers.jpg" media="(max-width: 1500px)">(Change image)
<source srcset="flowers.jpg">
<img src="img_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>
</body>
</html>

Responsive Text-size
We can make the text size responsive by using the "uv" unit. It means viewport-width. By using this, we
can make the text size to follow the browserwindow screen.

Example

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h1 style="font-size:10vw;">Here size is 10vw.</h1>
<p style="font-size:6vw;">Here size is 6vw.</p>
<p style="font-size:4vw;">Here size is 4vw.</p>
<p>Resize the browser window to see how the text size changes.</p>
</body>
</html>

3. CSS Media Queries

CSS (Cascading Style Sheets) media queries are a way to apply different styles to a website
based on the characteristics of the device or screen it is being viewed on. Think of media
queries as a set of rules that check specific conditions, such as screen width, height,
resolution, or device type. These conditions help determine the layout and presentation of the
website.

CSS Media query is a W3C recommendation and a CSS3 module which is used to adapt to conditions
such as screen resolution (e.g. Smartphone screen vs. computer screen).

o The media query technique first used in CSS3.


o It became a W3C recommendation in June 2012.
o It is an extension of media dependent stylesheets used in different media types (i.e. screen and print) found
in CSS2.
o The most commonly used media feature is "width".
o It uses the @media rule to include a block of CSS properties only if a certain condition is true.
Recommended Media features for Media queries
Following is a list of media features recommended for media queries by W3C.

Feature Value Min/Max Description

color integer yes It specifies the number of bits per


color component.

color-index integer yes It specifies the number of entries


in the color lookup table.

device-aspect-ratio integer/integer yes It specifies the aspect ratio of the


device.

device-height length yes It specifies the height of the output


device.

device-width length yes It specifies the width of the output


device.

grid integer no It is true for a grid-based device.

height length yes It specifies the height of the


rendering surface.

monochrome integer yes It specifies the number of bits per


pixel in a monochrome frame
buffer.

resolution resolution ("dpi" or yes It specifies the resolution of the


"dpcm") display screen.

scan "progressive" or no It specifies scanning process of


"interlaced" "tv" media types.

width length yes It specifies the width of the


rendering surface.

Responsive Web Design Principles


The following responsive web design best practices, aka principles, will ensure flexibility and
provide satisfying UX regardless of the device your website is approached from:

1. Start With Smallest Screens

This principle, also known as the “mobile-first” approach, involves designing the website primarily
for mobile devices before considering larger screens. By beginning the responsive web design
process with mobile devices, you ensure the website is optimized for smaller screens and limited
resources such as bandwidth and processing power.

Starting with the smallest screens prioritizes simplicity, efficiency, and a streamlined UX. You can choose
and present essential content and features in a limited space. This will avoid cluttering the UI and get a
focused and user-friendly design. Once the mobile version is complete, expand and enhance the design for
larger screens.

2. Enhance Visual Hierarchy

Visual hierarchy is essential to designing responsive websites because screen space varies across
different devices. Enhancing it ensures that users can easily navigate and understand the content
regardless of their device. It helps create a cohesive and engaging UX, improving usability and
overall satisfaction.

3. Create Fluid Grids and Flexible Images

Implementing a fluid grid allows the content to dynamically resize and rearrange to fit different
devices. It ensures that the website maintains a consistent structure and readability, regardless of the
screen size. Elements within the grid can scale and reposition, providing a seamless and optimized
UX.

Flexible images resize proportionally, maintaining their aspect ratio as the screen width changes,
without distortion or cropping. To achieve flexibility, designers use CSS techniques.

For example, setting the maximum width of the image to 100% ensures that it scales down
proportionally to fit within its container. The height is adjusted automatically to maintain the aspect
ratio, preventing images from appearing stretched or skewed.

4. Select Appropriate Typography

Typography is equally important for readability and website aesthetics. In responsive web design,
you must select fonts that work well on different devices, screen sizes, and resolutions. Here is some
valuable advice for typography selection:

 Ensure the chosen typefaces and font sizes are legible on various screen sizes, especially
smaller devices like smartphones.
 Adjust the line length to ensure comfortable reading. Long lines of text can be challenging to
read, especially on smaller screens.

5. Include Content-Centric Breakpoints


When designing a responsive website, making all types of content (different text lengths and
multimedia content) look good on every screen is challenging. That is why design should prioritize
the content, not the device.

To achieve this, determine breakpoints (the specific “points” where the content and design adjust to
provide satisfying UX), focusing on the content that will be displayed. Using content -centric
breakpoints will ensure the layout adapts well to different screens and effectively presents all types
of content.

6. Don’t Hide Content

In the past, there was a misconception that certain content should be hidden for mobile devices.
However, this approach has changed because people now use mobile devices in various contexts and
rely on them as their primary source of internet access.

Therefore, do not hide content for mobile users. Instead, focus on finding ways to present it in a
user-friendly manner that makes it accessible and user-friendly across all devices. Displaying
content prioritizing UX for all screen sizes ensures users can access all the information they need,
regardless of their device.

7. Prioritize Accessibility

A responsive website should provide equal access and usability for all users, including those with
disabilities or impairments. Ensure your web design includes keyboard accessibility, screen reader
compatibility, color contrast, well-structured content, and accessible forms.

8. Test Responsiveness
Testing responsiveness ensures the website adapts and performs well across various devices and
screen sizes. To check you did a good job, use responsive testing tools or conduct manual testing
using different devices to access your website.
CSS Transition
The CSS transitions are effects that are added to change the element gradually from one style to another,
without using flash or JavaScript.
You should specify two things to create CSS transition.
o The CSS property on which you want to add an effect.
o The time duration of the effect.
Let's take an example which defines transition effect on width property and duration of 3 seconds.
<!DOCTYPE html>
<html>
<head>
<style>
div{
width: 100px;
height: 100px;
background: orange;
-webkit-transition: width 1s; /* For Safari 3.1 to 6.0 */
transition: width 1s;
}
div:hover {
width: 300px; }
</style>
</head>
<body>
<div></div>
<p>Move the cursor over the div element above, to see the transition effect.</p>
</body>
</html>

CSS Multiple Transition Effect


It is used to add transition effect for more than one CSS property. If you want to add transition effect on
more than one property, separate those properties with a comma.

Let's take an example. Here, the transition effects on width, height and transformation.

<!DOCTYPE html>
<html>
<head>
<style>
div {
padding:15px;
width: 150px;
height: 100px;
background: violet;
-webkit-transition: width 2s, height 2s, -webkit-transform 2s; /* For Safari 3.1 to 6.0 */
transition: width 2s, height 2s, transform 2s;
}
div:hover {
width: 300px;
height: 200px;
-webkit-transform: rotate(360deg); /* Chrome, Safari, Opera */
transform: rotate(360deg);
}
</style>
</head>
<body>
<div><b>JavaTpoint.com</b><p> (Move your cursor on me to see the effect)</p></div>
</body>
</html>

CSS Animation
CSS Animation property is used to create animation on the webpage. It can be used as a replacement of
animation created by Flash and JavaScript.

CSS3 @keyframes Rule


The animation is created in the @keyframe rule. It is used to control the intermediate steps in
a CSS animation sequence.

What animation does


An animation makes an element change gradually from one style to another. You can add as many as
properties you want to add. You can also specify the changes in percentage.0% specify the start of the
animation and 100% specify its completion.

How CSS animation works


When the animation is created in the @keyframe rule, it must be bound with selector; otherwise the
animation will have no effect.

The animation could be bound to the selector by specifying at least these two properties:

o The name of the animation


o The duration of the animation

CSS animation properties

Property Description

@keyframes It is used to specify the animation.

animation This is a shorthand property, used for setting all the properties, except the animation-
play-state and the animation-fill- mode property.

animation-delay It specifies when the animation will start.

animation-direction It specifies if or not the animation should play in reserve on alternate cycle.

animation-duration It specifies the time duration taken by the animation to complete one cycle.

animation-fill-mode it specifies the static style of the element. (when the animation is not playing)

animation-iteration- It specifies the number of times the animation should be played.


count

animation-play-state It specifies if the animation is running or paused.

animation-name It specifies the name of @keyframes animation.

animation-timing- It specifies the speed curve of the animation.


function

CSS animation example: Moving Rectangle


Let's take another example to display animation with percentage value.

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. div {
6. width: 100px;
7. height: 100px;
8. background: red;
9. position: relative;
10. -webkit-animation: myfirst 5s; /* Chrome, Safari, Opera */
11. animation: myfirst 5s;
12. }
13. /* Chrome, Safari, Opera */
14. @-webkit-keyframes myfirst {
15. 0% {background:red; left:0px; top:0px;}
16. 25% {background:yellow; left:300px; top:0px;}
17. 50% {background:blue; left:200px; top:300px;}
18. 75% {background:green; left:0px; top:200px;}
19. 100% {background:red; left:0px; top:0px;}
20. }
21. /* Standard syntax */
22. @keyframes myfirst {
23. 0% {background:red; left:0px; top:0px;}
24. 25% {background:yellow; left:300px; top:0px;}
25. 50% {background:blue; left:300px; top:200px;}
26. 75% {background:green; left:0px; top:200px;}
27. 100% {background:red; left:0px; top:0px;}
28. }
29. </style>
30. </head>
31. <body>
32. <p><b>Note:</b> The Internet Explorer 9 and its earlier versions don't support this example.</p>
33. <div></div>
34. </body>
35. </html>

CSS Transforms
CSS3 supports transform property. This transform property facilitates you to translate, rotate, scale, and
skews elements.

Transformation is an effect that is used to change shape, size and position.

There are two type of transformation i.e. 2D and 3D transformation supported in CSS3.

CSS 2D Transforms
The CSS 2D transforms are used to re-change the structure of the element as translate, rotate, scale and
skew etc.
Following is a list of 2D transforms methods:
o translate(x,y): It is used to transform the element along X-axis and Y-axis.
o translateX(n): It is used to transform the element along X-axis.
o translateY(n): It is used to transform the element along Y-axis.
o rotate(): It is used to rotate the element on the basis of an angle.
o scale(x,y): It is used to change the width and height of an element.
o scaleX(n): It is used to change the width of an element.
o scaleY(n): It is used to change the height of an element.
o skewX(): It specifies the skew transforms along with X-axis.
o skewY():It specifies the skew transforms along with Y-axis.
o matrix(): It specifies matrix transforms.
The translate() method
The CSS translate() method is used to move an element from its current position according to the given
parameters i.e. X-axis and Y-axis.
Let's take an example to translate a
element 50 pixels right, and 100 pixels down from its current position.
See this example:
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<style>
div {
width: 300px;
height: 100px;
background-color: lightgreen;
border: 1px solid black;
-ms-transform: translate(100px,80px); /* IE 9 */
-webkit-transform: translate(100px,80px); /* Safari */
transform: translate(100px,80px); /* Standard syntax */
}
</style>
</head>
<body>
<div>
This div element is translated 50 pixels right, and 100 pixels down from its current position by using translate (
) method.
</div>
</body>
</html>
The rotate() method
The CSS rotate() method is used to rotate an element clockwise or anti-clockwise according to the given
degree.
<style>
div {
width: 300px;
height: 100px;
background-color: lightpink;
border: 1px solid black;
}
div#myDiv {
-ms-transform: rotate(30deg); /* IE 9 */
-webkit-transform: rotate(30deg); /* Safari */
transform: rotate(30deg); /* Standard syntax */
}
</style>
The scale() method
The CSS scale() method is used to increase or decrease the size of an element according to the given
width and height.
<style>
div {
margin: 150px;
width: 200px;
height: 100px;
background-color: lightpink;
border: 1px solid black;
border: 1px solid black;
-ms-transform: scale(2.5,2); /* IE 9 */
-webkit-transform: scale(2.5,2); /* Safari */
transform: scale(2.5,2); /* Standard syntax */
}
</style>
CSS Gradient
CSS gradient is used to display smooth transition within two or more specified colors.
Why CSS Gradient
These are the following reasons to use CSS gradient.
o You don't have to use images to display transition effects.
o The download time and bandwidth usage can also be reduced.
o It provides better look to the element when zoomed, because the gradient is generated by the browser.
There are two types of gradient in CSS3.
1. Linear gradients
2. Radial gradients

1) CSS Linear Gradient


The CSS3 linear gradient goes up/down/left/right and diagonally. To create a CSS3 linear gradient, you
must have to define two or more color stops. The color stops are the colors which are used to create a
smooth transition. Starting point and direction can also be added along with the gradient effect.
1. background: linear-gradient (direction, color-stop1, color-stop2.....);
(i) CSS Linear Gradient: (Top to Bottom)
(ii) CSS Linear Gradient: (Left to Right)
(iii) CSS Linear Gradient: (Diagonal)
Top to Bottom Linear Gradient is the default linear gradient. Let's take an example of linear gradient that
starts from top. It starts red and transitions to green.

<!DOCTYPE html>
<html>
<head>
<style>
#grad1 {
height: 100px;
background: -webkit-linear-gradient(red, green); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(red, green); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(red, green); /* For Firefox 3.6 to 15 */
background: linear-gradient(red, green); /* Standard syntax (must be last) */ }
</style>
</head>
<body>
<h3>Linear Gradient - Top to Bottom</h3>
<p>This linear gradient starts at the top. It starts red, transitioning to green:</p>
<div id="grad1"></div>
</body>
</html>
2) CSS Radial Gradient
You must have to define at least two color stops to create a radial gradient. It is defined by its center.
1. background: radial-gradient(shape size at position, start-color, ..., last-color);
(i) CSS Radial Gradient: (Evenly Spaced Color Stops)
Evenly spaced color stops is a by default radial gradient. Its by default shape is eclipse, size is farthest-
carner, and position is center.
<!DOCTYPE html>
<html>
<head>
<style>
#grad1 {
height: 150px;
width: 200px;
background: -webkit-radial-gradient(blue, green, red); /* Safari 5.1 to 6.0 */
background: -o-radial-gradient(blue, green, red); /* For Opera 11.6 to 12.0 */
background: -moz-radial-gradient(blue, green, red); /* For Firefox 3.6 to 15 */
background: radial-gradient(blue, green, red); /* Standard syntax (must be last) */
}
</style>
</head>
<body>
<h3>Radial Gradient - Evenly Spaced Color Stops</h3>
<div id="grad1"></div>
</body>
</html>
Unit IV
What is JavaScript
JavaScript (js) is a light-weight object-oriented programming language which is used by several websites
for scripting the webpages. It is an interpreted, full-fledged programming language that enables dynamic
interactivity on websites when applied to an HTML document. It was introduced in the year 1995 for
adding programs to the webpages in the Netscape Navigator browser. Since then, it has been adopted by
all other graphical web browsers. With JavaScript, users can build modern web applications to interact
directly without reloading the page every time. The traditional website uses js to provide several forms of
interactivity and simplicity.

Although, JavaScript has no connectivity with Java programming language. The name was suggested and
provided in the times when Java was gaining popularity in the market. In addition to web browsers,
databases such as CouchDB and MongoDB uses JavaScript as their scripting and query language.

Features of JavaScript
There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured
programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the
operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than using classes for
inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.

History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence. In the year 1994, Netscape was founded
by Marc Andreessen. He realized that the web needed to become more dynamic. Thus, a 'glue language' was
believed to be provided to HTML to make web designing easy for designers and part-time programmers.
Consequently, in 1995, the company recruited Brendan Eich intending to implement and embed Scheme
programming language to the browser. But, before Brendan could start, the company merged with Sun
Microsystems for adding Java into its Navigator so that it could compete with Microsoft over the web
technologies and platforms. Now, two languages were there: Java and the scripting language. Further, Netscape
decided to give a similar name to the scripting language as Java's. It led to 'Javascript'. Finally, in May 1995, Marc
Andreessen coined the first code of Javascript named 'Mocha'. Later, the marketing team replaced the name with
'LiveScript'. But, due to trademark reasons and certain other reasons, in December 1995, the language was finally
renamed to 'JavaScript'. From then, JavaScript came into existence.

Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt
dialog box),
o Displaying clocks etc.

JavaScript Example
<script>
document.write("Hello JavaScript by JavaScript");
</script>
JavaScript Basics:
The JavaScript comments are meaningful way to deliver message. It is used to add information about the code,
warnings or suggestions so that end user can easily interpret the code
There are two types of comments in JavaScript.
1. Single-line Comment
2. Multi-line Comment
It is represented by double forward slashes (//). It can be used before and after the statement.
Let’s see the example of single-line comment i.e. added before the statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>

JavaScript Multi line Comment


It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash. For example:
/* your code here */

JavaScript Variable
1. JavaScript variable
2. JavaScript Local variable
3. JavaScript Global variable

A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript : local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

var x = 10;
var _value="sonoo";
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
JavaScript local variable
A JavaScript local variable is declared inside block or function. It is accessible within the function or
block only. For example:
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
JavaScript global variable
A JavaScript global variable is accessible from any function. A variable i.e. declared outside the
function or declared with window object is known as global variable. For example:
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>

JavaScript non-primitive Data types


The non-primitive data types are as follows:

Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:

var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.


1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the operands. The following operators
are known as JavaScript arithmetic operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The comparison operators are as
follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators


The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:
Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

JavaScript Assignment Operators


The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators


The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-else.

, Comma Operator allows multiple expressions to be evaluated as single statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or false. There are
three forms of if statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement

JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement is given below.

1. if(expression){
2. //content to be evaluated
3. }
Let’s see the simple example of if statement in javascript.

<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement is
given below.

if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions. The signature of JavaScript if
else if statement is given below.

if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}

JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It
makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop
4. for-in loop

1) JavaScript For loop


The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number
of iteration is known. The syntax of for loop is given below.

for (initialization; condition; increment)


{
code to be executed
}
Let’s see the simple example of for loop in javascript.
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>

2) JavaScript while loop


The JavaScript while loop iterates the elements for the infinite number of times. It should be used if
number of iteration is not known. The syntax of while loop is given below.

while (condition)
{
code to be executed
}

Let’s see the simple example of while loop in javascript.

<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
3.JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of times like while
loop. But, code is executed at least once whether condition is true or false. The syntax of do while
loop is given below.
do{
code to be executed
}while (condition);
Let’s see the simple example of do while loop in javascript.
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
4.The For In Loop
The JavaScript for in statement loops through the properties of an Object:
Syntax
for (key in object) {
// code block to be executed
}
Example
const person = {fname:"John", lname:"Doe", age:25};

let text = "";


for (let x in person) {
text += person[x];
}
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to
reuse the code.

Advantage of JavaScript function


There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to
perform a common task.

JavaScript Function Syntax


The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}
JavaScript Functions can have 0 or more arguments.
JavaScript Function Example
Let’s see the simple example of function in JavaScript that does not has arguments.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
JavaScript Function Arguments
We can call function by passing arguments. Let’s see the example of function that has one argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Function with Return Value
We can call function that returns a value and use it in our program. Let’s see the example of function that
returns value.
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
JavaScript Function Object
In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the
code globally. However, if we call the constructor directly, a function is created dynamically but in an
unsecured way.
Syntax
new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
arg1, arg2, .... , argn - It represents the argument used by function.
functionBody - It represents the function definition.
JavaScript Function Methods
Let's see function methods with description.

Method Description

apply() It is used to call a function contains this value and a single array of arguments.

bind() It is used to create a new function.

call() It is used to call a function contains this value and an argument list.

toString() It returns the result in a form of a string.

JavaScript Function Object Examples


Example 1
Let's see an example to display the sum of given numbers.
1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>

JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.

<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to
provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

JavaScript Array Methods


Let's see the list of JavaScript array methods with their description.

Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copywithin() It copies the part of the given array with its own elements and returns the modified array.

entries() It creates an iterator object and a loop that iterates over each key/value pair.

every() It determines whether all the elements of an array are satisfying the provided function conditions.

flat() It creates a new array carrying sub-array elements concatenated recursively till the specified depth.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another array element.

find() It returns the value of the first element in the given array that satisfies the specified condition.

findIndex() It returns the index value of the first element in the given array that satisfies the specified condition.

forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the index of the first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, then loops through these keys.
of() It creates a new array from a variable number of arguments, holding any type of argument.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduceRight() It executes a provided function for each value from right to left and reduces the array to a single value.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

values() It creates a new iterator object carrying values for each index in the array.

Document Object Model(DOM)


The document object represents the whole html document.
When html document is loaded in the browser, it becomes a document object. It is the root element that
represents the html document. It has properties and methods. By the help of document object, we can add
dynamic content to our web page.
Properties of document object
Let's see the properties of document object that can be accessed and modified
by the document
Methods of document object
We can access and change the contents of document by its methods.
The important methods of document object are as follows:

Method Description

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline character at the end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.

getElementsByTagName() returns all the elements having the given tag name.

getElementsByClassName() returns all the elements having the given class name.

Accessing field value by document object


In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>

<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>

DOM Using JavaScript:


JavaScript can access all the elements in a webpage making use of Document
Object Model (DOM). In fact, the web browser creates a DOM of the webpage
when the page is loaded.
How to use DOM and Events
Using DOM, JavaScript can perform multiple tasks. It can create new elements and
attributes, change the existing elements and attributes and even remove existing
elements and attributes. JavaScript can also react to existing events and create new
events in the page.
getElementById, innerHTML Example
1. getElementById: To access elements and attributes whose id is set.
2. innerHTML: To access the content of an element.
Javascript - document.getElementById() method
The document.getElementById() method returns the element of specified id.
In the previous page, we have used document.form1.name.value to get the value of the input value.
Instead of this, we can use document.getElementById() method to get value of the input text. But we
need to define id for the input field.
Let's see the simple example of document.getElementById() method that prints cube of the given
number.
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>

Javascript - document.getElementsByName() method


The document.getElementsByName() method returns all the element of specified name.

The syntax of the getElementsByName() method is given below:

document.getElementsByName("name")
Here, name is required.

Example of document.getElementsByName() method


In this example, we going to count total number of genders. Here, we are using getElementsByName()
method to get all the genders.
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total Genders">


</form>

2. Javascript - innerHTML
The innerHTML property can be used to write the dynamic html on the html document.

It is used mostly in the web pages to generate the dynamic html such as registration form, comment form,
links etc.

Example of innerHTML property


In this example, we are going to create the html form when user clicks on the button.
In this example, we are dynamically writing the html form inside the div name having the id mylocation.
We are identifing this position by calling the document.getElementById() method.
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows='5' cols='80'></textare
a>
<br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>

JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser. When javascript code is
included in HTML, js react over these events and allow the execution. This process of reacting over the
events is called Event Handling. Thus, js handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.
Some of the HTML events and their event handlers are:
Mouse events:
Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

Keyboard events:

Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Form events:

Event Performed Event Handler Description

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form


blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a form element
AD

Window/Document events

Event Performed Event Handler Description

load onload When the browser finishes the loading of the page

unload onunload When the visitor leaves the current webpage, the browser
unloads it

resize onresize When the visitor resizes the window of the browser

Let's discuss some examples over events and their handlers.

Click Event
1. <html>
2. <head> Javascript Events </head>
3. <body>
4. <script language="Javascript" type="text/Javascript">
5. <!--
6. function clickevent()
7. {
8. document.write("This is JavaTpoint");
9. }
10. //-->
11. </script>
12. <form>
13. <input type="button" onclick="clickevent()" value="Who's this?"/>
14. </form>
15. </body>
16. </html>

JavaScript addEventListener()
The addEventListener() method is used to attach an event handler to a particular element. It does not
override the existing event handlers. Events are said to be an essential part of the JavaScript. A web page
responds according to the event that occurred. Events can be user-generated or generated by API's. An
event listener is a JavaScript's procedure that waits for the occurrence of an event.

The addEventListener() method is an inbuilt function of JavaScript. We can add multiple event handlers
to a particular element without overwriting the existing event handlers.

Syntax
1. element.addEventListener(event, function, useCapture);
Although it has three parameters, the parameters event and function are widely used. The third parameter
is optional to define. The values of this function are defined as follows.

Parameter Values
event: It is a required parameter. It can be defined as a string that specifies the event's name.

Note: Do not use any prefix such as "on" with the parameter value. For example, Use "click" instead of using
"onclick".
function: It is also a required parameter. It is a JavaScript function which responds to the event occur.
useCapture: It is an optional parameter. It is a Boolean type value that specifies whether the event is
executed in the bubbling or capturing phase. Its possible values are true and false. When it is set to true,
the event handler executes in the capturing phase. When it is set to false, the handler executes in the
bubbling phase. Its default value is false.
Let's see some of the illustrations of using the addEventListener() method.
Example
It is a simple example of using the addEventListener() method. We have to click the given HTML
button to see the effect.
<!DOCTYPE html>
<html>
<body>
<p> Example of the addEventListener() method. </p>
<p> Click the following button to see the effect. </p>
<button id = "btn"> Click me </button>
<p id = "para"></p>
<script>
document.getElementById("btn").addEventListener("click", fun);
function fun() {
document.getElementById("para").innerHTML = "Hello World" + "<br>" + "Welcome to the javaTpoint.com
";
}
</script>
</body>
</html>

JavaScript onclick event


The onclick event generally occurs when the user clicks on an element. It allows the programmer to
execute a JavaScript's function when an element gets clicked. This event can be used for validating a
form, warning messages and many more.

Using JavaScript, this event can be dynamically added to any element. It supports all HTML elements
except <html>, <head>, <title>, <style>, <script>, <base>, <iframe>, <bdo>, <br>, <meta>, and <pa
ram>. It means we cannot apply the onclick event on the given tags.
In HTML, we can use the onclick attribute and assign a JavaScript function to it. We can also use the
JavaScript's addEventListener() method and pass a click event to it for greater flexibility.
Syntax
Now, we see the syntax of using the onclick event in HTML and
in javascript (without addEventListener() method or by using the addEventListener() method).
In HTML
<element onclick = "fun()">
In JavaScript
object.onclick = function() { myScript };
In JavaScript by using the addEventListener() method
object.addEventListener("click", myScript);
Let's see how to use onclick event by using some illustrations. Now, we will see the examples of using
the onclick event in HTML, and in JavaScript.
Example - Using onclick attribute in HTML
In this example, we are using the HTML onclick attribute and assigning a JavaScript's function to it.
When the user clicks the given button, the corresponding function will get executed, and an alert dialog
box will be displayed on the screen.
<!DOCTYPE html>
<html>
<head>
<script>
function fun() {
alert("Welcome to the javaTpoint.com");
}
</script>
</head>
<body>
<h3> This is an example of using onclick attribute in HTML. </h3>
<p> Click the following button to see the effect. </p>
<button onclick = "fun()">Click me</button>
</body>
</html>

You might also like