Web Development Learn HTML CSS Javascri - Srinivas Vanamala

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1052

About this Book

About this Book

HTML is a programming language that allows web developers to create


static HTML Page that can be viewed on Web Browser. HTML Language is
basically used for developing web pages. This book will help you understand
the basics of HTML Language and how to put it in practice to build
Websites.

Audience

This tutorial has been designed to meet the requirements of all those readers
who are keen to learn the basics of HTML.

Prerequisites

This book assumes you have no prior knowledge on Programming


knowledge and assume you are at a beginner level.

How to use this Book

This book contains HTML Language Basics, Exercises and Examples which
are part of the PHP Bootcamp Program. This bootcamp has helped many
students to become PHP Full Stack Web Developer in Just 30 days.

>>>Check out more about this program here. ..


Copyright & Disclaimer

Copyright & Disclaimer

© Copyright 2020 by SrinivasIT.com.

All the content and graphics published in this e-book are the property of
SrinivasIT.com. The user of this e-book is prohibited to reuse, retain, copy,
distribute or republish any contents or a part of contents of this e-book in any
manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or
errors. SrinivasIT.com provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this
tutorial. If you discover any errors on our website or in this tutorial, please
notify us at contact@SrinivasIT.com .

Found Typos & Broken Link

If you found any typos and broken links in the course or book, then please
let me know using this email address.
contact@SrinivasIT.com

Support

You can reach me for technical discussions and other support related queries
from here.
support@SrinivasIT.com
Thanks for your support!

Free Courses
Learn HTML in 1 Hour
Learn CSS in 1 Hour
Learn JAVASCRIPT in 1 Hour
Table of Contents

About this Book .......................................................................................... 1


Audience...................................................................................................... 1
Prerequisites ............................................................................................... 1
How to use this Book ................................................................................. 1
Copyright & Disclaimer .............................................................................. 2
Found Typos & Broken Link ...................................................................... 2
Support ........................................................................................................ 2
Free Courses ............................................................................................... 3
1. Web Basics.......................................................................................... 9
1.1 - What is a Protocol? ......................................................................... 9
1.2 - Overview of Internet and Web ...................................................12
1.3 - What is HTTP? ...............................................................................19
1.4 - What is IP Address and DNS .......................................................25
1.5 - Client Side and Server Side .........................................................33
1.6 - Compiler vs Interpreter ...............................................................37
1.7 - Programming vs Markup vs Scripting Languages....................40
2. HTML Basics ..........................................................................................43
2.1 – What is HTML?..............................................................................43
2.2 – Tag, Element and Attribute ........................................................48
2.4 – Setting up the System for Writing HTML ..................................52
2.5 – First HTML Page ...........................................................................57
2.6 – HTML Parts ...................................................................................62
2.7 – HTML Boiler Plate ........................................................................63
3 TEXT ELEMENTS
.....................................................................................71
3.2 – Headings.......................................................................................79
3.3 – Horizontal Lines ...........................................................................81
3.4 – Paragraphs ...................................................................................83
3.5 – Single Line Break .........................................................................87
3.6 – Strong Text ...................................................................................93
3.7 – Emphasis Text ..............................................................................97
3.8 – Underline Text .............................................................................98
3.9 – Italics ...........................................................................................100
3.10 – Code ..........................................................................................101
3.11 – Preformatted Tag ....................................................................103
3.12 – More HTML Text Tags .............................................................105
4 Lists .......................................................................................................108
4.1 – Definition List .............................................................................108
4.2 – Ordered List ...............................................................................111
4.3 – UnOrdered List ..........................................................................114
5 ARTICLES...............................................................................................120
5.1 – Articles ........................................................................................120
6 TABLES ..................................................................................................127
6.1 – Simple Table...............................................................................127
6.2 – Table with Borders ....................................................................131
6.3 – Table with Header and Footer .................................................135
6.4 – Table with RowSpan and ColSpan...........................................141
7 EMBED CONTENTS
..............................................................................147
7.1 – Embed Image .............................................................................148
7.2 – Embed Image with Attributes ..................................................152
7.3 – Embed Image in the Article ......................................................156
7.4 – Embed Audio..............................................................................160
7.5 – Embed Video ..............................................................................164
7.6 – Embed iFrame............................................................................168
7.7 – Embed Links ...............................................................................171
7.8 – Embed Anchor ...........................................................................173
8 FORMS ..................................................................................................180
8.1 – Basic Form Elements.................................................................181
8.2 – Input Box Form Elements.........................................................185
8.4 – Radio Buttons Form Elements .................................................199
8.5 – Checkbox Form Elements.........................................................207
8.6 – TextArea Form Elements ..........................................................216
8.7 – Other Form Elements................................................................225
8.8 – Action GET from Form...............................................................227
8.9 – Action POST from Form ............................................................230
9 META TAGS...........................................................................................235
9.1 – Meta with SEO Tags...................................................................236
9.2 – Meta tags with View Port ..........................................................238
9.3 – Meta tags without View Port ....................................................241
9.5 – Page Auto Redirect ....................................................................242
10 LAYOUTS.............................................................................................246
10.1 – Layout 1 ....................................................................................247
11 ADDITIONAL TAGS
............................................................................253
11.1 – DIV HTML Tag...........................................................................253
11.2 – SPAN HTML Tag .......................................................................257
11.3 – White Space, Special Characters & Case Sensitive..............260
12 HTML Projects....................................................................................266
12.1 – Personal Profile Page..............................................................266

1. WEB BASICS
1. Web Basics
1.1 - What is a Protocol?

Protocol in Simple English


Protocol in plain English means set of rules to communicate. It is kind of rules that need to be
followed to achieve a desired results.
Imagine, if I speak only English Language and you want to communicate with me.
Then the protocol we can use to communicate with each other could be:

1. Body Language
2. Sign Language
3. English Language

They all are called as Protocol. It is the medium thru which we agree to communicate to each other.
So, if you know English then you can communicate with me in English Language and that is our
Protocol to communicate.
Protocol are set of rules to communicate.
How Two Systems Communicate?
Imagine two systems want to communicate with each other and exchange data. How do they
communicate with others? All they know is 0 and 1. That’s where the protocol comes and helps.
Two systems has to first agree on a common protocol. They should know what rules they are going to
follow to communicate with each other.
There should be some kind of instructions that are predefined when followed a communication can be
made.
So, before two computers decide to communicate they agree on a common protocol and based on that
protocol definition they communicate with each other.
Types of Protocols:
There are many types of protocol available today using which two devices communicate with other.
Do this exercise:
Just look around all the devices that communicate with other in your house. Think for a second how
they communicate with other and what protocol they use.
To understand the definition of protocol you need to understand and see how two devices really
communicate with each other.
What kind of rules or instructions they follow to communicate?
Here are some of the examples that shows how the two devices uses a specific protocol to
communicate with each other’s.
Wifi Protocol: This protocol helps connect your mobile phone to your Wifi
Devices and access the Internet.
FTP Protocol: This FTP Protocol can help to access any server’s file system and
perform the file operations on it like Upload, Download, and Delete and Rename the files.
Email Protocol: This is the most common protocol we use every day to send
and receive emails.
Depending on the type of communication, the underlying protocol will change. Each Protocol is
defined to achieve a specific type of result when followed.
So, Protocol is nothing but a set of rules that when followed a specific operation is performed.
Common examples as we have seen above like Wifi Protocol, FTP Protocol and Email Protocol are
used to do a specific Job.
Technical Definition:
Protocol is a set of rules when followed by the system to perform a specific activity.
Protocol can also be defined as set of rules and standards used to communicate between machines.
Communication Protocol can be used to communicate and exchange information between one or more
system connected together.
Example of Communication Protocol are Wifi Protocol, FTP Protocol or Email Protocol.

1.2 - Overview of Internet and Web

What is Internet?
Internet is a network where group of computers connected together with a single wire. Systems
connected in that network are able to communicate with each other and exchange data.
Internet is so powerful because of one things and that is we can communicate to any system in that
network.
We can issue command to any computer in the world when connected to this network – Internet.

Today, we can use Skype, WhatsApp, Send emails, Buy Online and can do many things because all
these computers are connected together in a single network and we can use it to do whatever we want.

This network is often called as Global Network.


Internet is just a way computers are connected to exchange information in one network.
How Internet was discovered?
Federal Government of United States started a project called ARPANET in 1960. The primary purpose
of this project is to build a network of computer using which federal data can be exchanged.
It was secured network and used only in the nation for federal purpose.
Later in 1990s many organization came together to form a network that can be used by everyone
which was Internet.
How data is exchanged in the Internet?
The data in Internet is exchanged with TCP/IP protocol. This is the protocol that every computer uses
to exchange data.
This is like a language that every computer in that network speaks to communicate.

This is a requirement that every computer connected to the global network (internet) must speak
TCP/IP protocol language to communicate.
Many other protocols are build based on this underlying TCP/IP protocol.
Learn more about what is Protocol from here.
What is Web?
Web is not Internet.
If Internet is a way to connect computers together then Web is the way to access those information
over the Internet medium. Web is a method about how to access those information over the internet.

Web is the way information is shared across the internet.


Information is generally represented with text, images, and video, audio and other media types.
World Wide Web (WWW) or Web are actually same thing that helps to access these information.
Web achieves two things:
Access the resource from any computer in the internet
Link those resources.
History of Web
English scientist Tim Berners-Lee invented the World Wide Web in 1989. He built a browser using
which the resource where accessed over the internet and displayed on the browser.

In 1991, it was released to General Public.


From then, all the big companies released their own browsers like Google has Chrome and Windows
released Edge.
How data is exchanged in Web?
Web uses a protocol called as HTTP (Hyper Text Transport Protocol) to access the information from
any computer in the internet.

Hyper Text means a special text which has:


Link to other resources in the Internet.
It can include Video, Images and Sounds.
HTTP is the protocol using which Hyper Text is downloaded from the server and displayed on the
browser.
You will learn more about HTTP from here.
Difference between Internet and Web?
Internet is the way how two computers can communicate with each other.
Web or World Wide Web (WWW) is the method thru which the Hypertext is accessed from the server
and displayed on the browser.
Remember, Web and Internet are not same.
Does anyone Controls the Internet?
No one controls the internet. It is a network where computers are connected with TCP/IP protocol.
You can bring your own computer and connect to the internet. Once your computer is connected to the
internet then our computer can talk to all other computers in that Global Network (Internet).

All the communication in the Internet happens with a defined Protocol (TCP/IP)
How to use these words?
Internet is a network where all the computers are connected together.
Web or WWW is the way information is accessed from the server and displayed on the browser.
Technical Definition
Internet is a global network where systems are connected together and can communicate with each
other.
Web or WWW is the way where hypertext are identified and linked together. Using web, we access
the information and display it on our browser.
Internet uses TCP/IP protocol to communicate.
Web uses HTTP protocol to access specific resources over the Internet.
Web and Internet are not same.
Simply, Internet helps to connect systems together and web helps to extract the information in a
specific way.

1.3 - What is HTTP?

What is HTTP?
HTTP stands for Hyper Text Transfer Protocol.
HTTP is a protocol and main purpose of this protocol is to communicate in web by machines.
Hyper Text means a special text which has:
Link to other resources in the Internet.
It can include Videos, Images and Sounds.

Once this hypertext is stored in the server that is connected to the internet then using the HTTP
protocol this Hyper Text can be exchanged between the computers.
In Short, HTTP carries the Hyper Text between the two computers to establish a communication.

It is a language that two machines speaks to exchange the Hyper Text over the web.
Learn more about what is Internet and Web from here.
How HTTP Works?
The Rule of HTTP is – ASK AND IT IS SERVED.
Hyper Text are available in the system which are connected to the Internet.
Someone needs to make a request to this machine and ask to fetch it. Then once the request is made it
is served by sending the Hyper Text via the Response.
There are two roles involved in the HTTP process. First one is called a Requester and second is called
as Provider.
Requester is the initiator of the request. One who ask for the resource.
Provider serves the request and provide the response to the requester.

So for HTTP protocol to work, Requester has to initiate the request by asking for a specific resource
on that server and then Provider once received the request it will search and send that resource back to
Requester.

If there is no requester then provider does nothing.


Summary:
Someone needs to initiate the request to access those resource on the server. Server will respond and
send that resource back as a Response.
All this is handled by the HTTP protocol.
Understand HTTP from your Browser
To see how request and response works. Try this live example from the chrome browser.
Exercise 1: How to Verify the Request and Response from the Browser
Step 1: Open the Chrome Browser
Open the Chrome Browser.
Step 2: Press CTRL + SHIFT + I to open the Inspect Mode
Once the Browser is open, Then press CTRL + SHIFT + I to open the Inspect Window
Step 3: Click on Network Tab in the Inspect
Click on Network on the Chrome Inspect Window.
Step 4: Type the Link.
Enter the Link in the Browser URL Bar.
https://docs.SrinivasIT.com/
Step 5: Observe the Request and Response in Action
Click on the “sample.txt” file in the Network Tab. This will open up the Request and Response trace.
Now click on “Headers” in the Right hand side tab.
In the Header Tab, Observe the Request information and Response Information.
Technical Definition
HTTP protocol helps to establish the communication between the Web Browser (Client) and the
destination server.
Requester is the initiator of the request. One who ask for the resource. Provider serves the request and
provide the response to the requester.

1.4 - What is IP Address and DNS

How Internet Works?


Internet is a global network where all the devices are connected together with a single wire.
TCP/IP or Internet Protocol (IP) is used to communicate between the systems.
Internet connects billions of computers all around the globe to form network of networks. Every
computer can connect to any computer on the Internet.
Learn more about the Internet from here
What is IP Address?
IP stands for Internet Protocol that is used in the internet to communicate between the systems.
All the Different Devices on the internet have unique addresses.
Like every phone sim has a unique phone number attached to it. Similarly, every computer on the
internet has a unique address.
Every computer needs to have a unique address when connected to internet so that it is easily
identified from the billions of computers.
IP Address is just a number that is unique to a specific network or computer.
It looks like this – 192.87.45.20

IP address has a format where number are separated with “.”.


IP address can also be compared with the email address. You don’t need to know the person or server
location but just sending an email to that email address will be delivered to the right system on the
internet.

What is IPV4 and IPV6?


IPV4 and IPV6 are just how the IP addresses are organized. It is the way to represent the IP address of
a computer.
In IPV4, IP address are represented in number which is 32 bits long.
Eg: 192.87.45.20
In IPV6, IP address are represented in text and numbers format which is 128 bits long.
Eg: 3FF3:F200:8474:JL00:7633:1232:4294: IKLJ

As more computers added to the internet the need to have bigger IP address is solved by IPV6. IPV6
uses text and number combination to come up with more unique address.

Now with IPV6, we can have more unique combination that we can assign to the computer and
identify them in the internet.
Find Your System IP Address
Step 1: Open the Command Prompt
Press Window Button + R (CMD + R) on Windows and Type “cmd”.
Press Enter to open the Command Prompt.

Step 2: Type ipconfig command


Type the command “ipconfig” on the command prompt.
Step 3: Verify the IP Address
Now verify the IPV4 and IPV6 IP address of your machine when connected to Internet.
This is your unique address of your computer.
Search IP Address of Other Systems
Type the Command “ping www.yahoo.com” to find the IP address of Yahoo.com Server in the same
Command Prompt.
So, 124.108.103.103 is the IP address of Yahoo.com server.
What is DNS?
DNS stands for Domain Name System.
DNS is the English name or easy to remember name for your IP address.
The way we store the phone number in Contact List with a Name similarly we store the IP address
with a name in the Domain Naming Servers.

To find out an IP address of Yahoo we typed “ping yahoo.com” and then it shows the IP address of
Yahoo.
Yahoo.com is the Domain Name of the IP address 124.108.103.103
It is plain, simple and easy to remember name that we assign to our IP address which is difficult to
remember.
There are many Domain Name Providers who can help us to buy the domain name for our IP address.
Some of the Domain Name Providers are:
• Namecheap.com
• goDaddy.com
You can buy the Domain Name for little price and need to be renewed every year or else you will lose
that name.
Once you purchase the domain name then that is unique in the internet as well like IP address.
How DNS are registered?
These Domain Name Servers around the world has list of all the domain name and its corresponding
IP address.
Once you purchase a Domain Name from the Domain Name provider and map your IP address with
the Domain Name.

This new mapping is distributed and synced with all the Domain Name Server across the world so that
everyone knows that for this Domain Name this is the IP address.

Once the sync is down then every DNS server can tell what the IP address of your Domain Name is.
That’s why when you map the IP address to the Domain name it will take 24 hours to sync with all the
domain name servers across the world.
How DNS works?
When you type https://SrinivasIT.com/ in the Browser URL window.

The request is first sent to DNS server where your server IP address are searched.
If that DNS server does not know then it will ask around with other DNS server to find the IP address
for that Domain Name.
Once the DNS server finds the IP address then it routes the message to that specific IP address server.
Exercise
Visit the two Domain Name providers and search for the domain name that you like is available or
taken by others.
Technical Definitions:
IP stands for Internet Protocol which is used in communication by the systems in the Internet.
Each system in the Internet has a unique address named as IP Address. Using IP address we can
identify a computer in the internet.
IP address are represented with two types IPV4 and IPV6
IPV4 notation uses numbers separated with “.” which are 32 bits long
IPV6 notation uses numbers + text separated with “:” which are 128 bits long
DNS stands for Domain Name Server.
You buy a Domain Name from the Domain Name Providers and assign Domain name with the IP
address. Every Domain Name are unique and cannot be purchased twice.

1.5 - Client Side and Server Side

How HTTP Works?


Hyper Text Transfer Protocol (HTTP) is a protocol that is used to exchange the Hyper Text between
the two systems over the web.

Requester has to initiate the request to the provider to perform some action at the server. The action
could be to send the data, update the data or search for something.
Provider receives the request and send response to the Requester.
This is the way HTTP protocol works and helps to exchange the information between two systems.
Learn more about how HTTP works from here.
What is Client Side?
Requester generally is the browser that initiate the request to the provider.

So, all the actions that happens at browser or requester side is called as Client Side.
All the actions that takes place at your computer before the request is been made to the provider is
generally referred to as Client Side.
For Example, if your browser executes a code on your computer then we say the code is executed at
client side.
What is Server Side?
Anything that happens at the server is called as Server Side.
Once the request is sent to server or provider then all the operations or steps that server executes as
referred to as Server side.

Server side code executes when the Client makes a request to the server and ask to run that code. The
output of the code is sent back to client by the server.
This way Client and Server Interacts with each other.
What is Client Server Technology?
Client Server Technology is a model or design or concept that is very commonly used to design the
application architecture. The main principle is that Server holds some piece of code or resources with
high end hardware capacity. Client could be anyone like Mobile, Desktop or iWatch.

Client request Server for any operations or resources and Server will execute that command and
returns the output to the client.

This way there could be few powerful servers serving many clients. Also the client does not have to
worry how to implement that code and it just need to request the server and server will respond back
with the output.

Imagine that server does the powerful job and client needs to request server to perform that operation
and send the result.
Many Servers, Architecture and Framework are based on the very common theory
– Client Server Technology.
Technical Definition
HTTP is a protocol that is used to exchange the Hyper Text between the two systems over the web.
Any code that runs on the Browser is called as Client Side. Operations that happens at the Client
devise is also called as Client Side.
If the same thing happens at server then it is called as Server Side.

Client-Server Technology is a model where Server holds the resource and Clients request for that
resource from the server. The resource at the server could executing a code, access to a database,
simply a video file.

1.6 - Compiler vs Interpreter

How Computer Understand Instructions?


Computer does not understand English nor it understand the mouse clicks.
Computer only understands 1 and 0 language. ON or OFF. That’s how the instructions are given to
machine.
Machine Language or Assembly language are the languages that converts the instructions into the
code that machine understands.
But the language that we learn like Java, C or PHP are just plain English and use words like If, then,
switch with some symbols to give instructions.
So, there has to be some kind of conversion from our English Language to Machine Language.
That is the job of Compiler and Interpreter which helps to convert the English language into machine
language that computer can understand.
What is Compiler?
Compiler is a program that read our program and converts them into machine language. Then that
compiled code is executed to give instructions to the machine.
Without compiling our code, we cannot execute our code.

Programming Language like Java and C uses compiler to compile its code into another file that is used
to execute on the system.
What is Interpreter?
Interpreter is a program that executes our code at runtime and pass the instructions to the computer at
the same time.
It does not generate another set of files and execute them but instead it reads our program line by line
and then execute them in the same sequence.
Languages like PHP and Ruby uses Interpreters.
Languages:
1.7 - Programming vs Markup vs Scripting Languages

What is Programming Language?


Languages that needs to be compiled with a compiler are referred as Programming Language.
Programming Languages are very powerful and well defined language that can give powerful
instructions to the computer.
With the programming language, we get the full control of the system and give instructions to do
things that we want to.
Languages like Java, C and C++ are most powerful programming languages.
What is Markup Language?
Markup language is written using the Markups.

Example of Markup:
• <NAME>PHPBOOTCAMP</NAME>
• <SITE>SRINIVASIT.COM</SITE>

It is easy to learn and easy to represent the data using the markup language.
The major disadvantage of markup language is that it cannot control the system nor it is very powerful
in handling a complex logic.
The main purpose of markup language is to represent the data structure. How the data should look like
is defined by the Markup Language.
Languages like HTML, XML are called as Markup Language.
What is Scripting Language?
Languages that uses Interpreter are referred as Scripting Language.
Scripting language does call another program or instructions to do the job done.

That’s why you find that Scripting languages are fun, easy and very simple to work with. The reason is
that heavy coding is done in another program and the language is made simple to call those functions.

Languages like JavaScript, Python and PHP are Scripting Language.

2. HTML BASICS
2. HTML Basics
2.1 – What is HTML?

What is Hyper Text?


Hyper Text means a special text which has:
Link to other resources in the Internet.
It can include Videos, Images and Sounds.
The most important part of HyperText is the ability to link other resources on the server which can be
accessed via the link.
Hypertext are displayed on the computer screen mostly Browser like Chrome from Google, Edge from
Microsoft and Firefox.
Learn more about the Hypertext from here.
How Web Works?
The main purpose of Web or World Wide Web (WWW) is to exchange information from one
computer to another computer.
WWW is the way of connecting all the documents and displaying them on the browser.
Web uses HTTP protocol to transfer the information over the Internet.
Hypertext are transferred from one computer to another via the HTTP protocol and displayed on the
browser.
This how Web Works:
You Type the Website name in the Browser. Eg. www.wpfreelancer.com
Browser sends the request to DNS Server.
DNS Server search for IP address for this Domain Name.
Once the IP Address is found it then connects to the specific server in the Internet.
Server receives the request via the HTTP protocol.
Server will then search for the requested HyperText and send it back to the browser.
Browser will receive the hypertext and display it on the computer screen.
What is the purpose of Markup Language?
HyperText are typically exchanged between the servers to enable the communication between the
machines.
But to make this HyperText convert into a language so that we can write the language in such a
manner that we can get a specific task done.

Markup Language is used to represent how to organize the data. This kind of language focus more on
how the data should be used and define the purpose of the data.
In Order to organize the HyperText that is sitting all over the computer into human understandable
format a Markup Language was required.

HTML solves this problem of Marking up the required data from the server in such a manner that we
understand the purpose of it.

For Example, We have a video file saved on the server. Now we want to tell everyone what is the
purpose of this video and also some description of the Video when someone access this content.
Packing this information into a sample markup language could be like this
<title>How to Lose Weight in 10 Days</title>
<description>Quick and Easy way to lose weight without going to gym</description>
<videolocation>/assets/video/looseweight.mpeg</videolocation>
This is a Markup Language but not HTML. We can pack our content in a Markup Language so that we
understand the HyperText that we get from the server.
Learn more about Markup from here.
What is HTML?
HTML stands for Hyper Text Markup Language.
HTML is a Markup Language that is used to mark the contents and then tell the browser how to
display them on the screen.
HTML is a markup language that our browser understands and know how to display them.
In HTML language, you will do the following things: Write how to display the contents on the
browser.
Links to another resource on the server. (HyperLinks)
Embed Videos and Audio from the Server.
Layout the Content.
The main Purpose of HTML markup language is to tell browser how the data is displayed and in
which location.
History of HTML?
English scientist Tim Berners-Lee invented the World Wide Web in 1989. He built a browser using
which the resource where accessed over the internet and displayed on the browser.

In 1991, it was released to General Public.


From then, all the big companies released their own browsers like Google has Chrome and Windows
released Edge.
Berners Lee released the first HTML sample page with 18 tags in it and displayed it on his own
browser.
He defined HTML as
HTML is a markup language that web browsers use to interpret and compose text, images, and other
material into visual or audible web pages
HTML5 is the latest version of HTML.
What is Web Server?
Web server is an application that is installed in the server which helps to listen to the HTTP request
and send the HTTP response. It is meant to handle the web requests and pass over the hypertext by
restricting and tracking the transactions.
Web server helps to track all the requests and additional details like IP address, location, browser
details and many other details.
It also helps to manage the load, execute the code at server, and restrict the access before accessing the
content at the server.
What is Web Application?
Application that is developed and deployed on Web Server are called as Web Applications.
Web Applications are small projects with bunch of files and media which are accessed via the Web
Server.
What is Web Pages?
Web pages are the documents that can be displayed in the browser like Google Chrome, Edge or
Safari.
Web pages are written using the HTML markup language and it is stored in the Web Server.
Then, Web pages are accessed in the Internet via a browser to display the output on the computer
screen.
What is Web Site?
Web site is collection of Web pages. Each website is accessed with a Domain Name.
A logical grouping of web page to perform a desired functionality is called as website.

2.2 – Tag, Element and Attribute

What is Markup Language?


Markup language are written using the Markups. We mention marks before and after the content to
show it has a special meaning to it.
Example of Markup:
<NAME>WPFREELANCER</NAME>
<SITE>WPFREELANCER.COM</SITE>
HTML is a Markup Language means everything you write using HTML will be with markups and
write the content between the markups.
What is Tag?
A Tag is the text between the left angle bracket (<) and the right angle bracket (>). There are starting
tags (such as <name>) and there are ending tags (</name>)

Example:
<name>wpfreelancer.com</name>
<name> = Opening Tag
</name> = Closing Tag
What is Element?
An Element is the opening tag, the closing tag and anything in between.
What is Empty Element?
Element that does not have any data between the tags is called as Empty Element.

<TAG /> is also called as self-closing element.


What is Attribute? An Attribute is a name=value pair inside the Element.

Attribute help to show additional details about the element.


Example:
<dog>German Shepard</dog> = ELEMENT
<dog color=”brown”>German Shepard</dog> = ELEMENT with ATTRIBUTE
Color = “brown” is called as Attribute.
Summary:

2.3 – HTML Basic Structure


Purpose of HTML?
HTML was written to organize the data in such way that it can be properly displayed on the browser.
Using Markups in HTML, Elements can be arranged in such a manner that it can be logically shown
how the final output looks like on computer screen.
Elements, tags, attributes of HTML were supposed to indicate how the title of the page looks like, how
the heading should look and in which order.
Structure of Data?
HTML markup language uses a markup structure to organize the elements in the page.
Consider this example:
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph</p>
</body>
</html>
Do not worry about the HTML but focus more on how the elements are organized to tell browser
about the purpose of each element and structure of each element.
The main purpose is to tell browser how to display the content on the computer screen so you organize
the markups in the same way it should be displayed. Sequencing is also important which decide how
the elements are organized on the page.

There is also a parent child relation between the elements.


head and body Elements are child for HTML p and h1 are child elements of body parent element.

2.4 – Setting up the System for Writing HTML

Install HTML Editor


To write the HTML pages you will need a HTML Editor. Follow this Steps to install the recommended
HTML Editor.
Step 1: Visit http://brackets.io/
Go to http://brackets.io/
Step 2: Download the Brackets Software
Download the Brackets Software

Step 3: Install the Software


Once the installation file is downloaded, install the software on your desired location.
Click on Search and Type “Brackets“. This will show the software that is installed.

Step 4: Open the Brackets Software


Step 5: Create the Folder and Open It
Once you open the Brackets software the first step is to point the editor to a folder on the system.
Create a folder in the system and Click on File -> Open Folder
Select the Folder where you want to store the files.
Verify the Folder Name from the Editor Title and Left side bar
Install Google Chrome Browser
Download and Install Google Chrome Browser
https://www.google.com/chrome/
Alternative Editors
There are other Editors that you can also use to write HTML:

1. Visual Studio Code


2. Notepad++
3. Atom

Alternative Browsers
You need to test your html code all of these browser before releasing the code in production:

1. Firefox
2. Safari
3. Edge

Do I need Internet to run HTML programs?


• NO
You don’t need Internet to Write and Run HTML Program on your local machine. You need Internet to
download the software but not to write and run it.

2.5 – First HTML Page

Check the Software:


Make sure you have all the following software installed
1. Brackets HTML Editor 2. Google Chrome Browser
If you don’t have these software then follow this guide to install it.
HTML Filename Convention:
HTML filename should be “.html” or “.htm” but always use “.html”
First HTML Page:
Step 1: Create the Folder and Open the Folder with Brackets
Option 1:
Create a Folder and Right Click on the Folder and Select “Open as Brackets Project”

Option 2:
Open the Brackets and go to File -> Open Folder
Step 2: Create an “index.html” file
Right Click and Select “New File”
Create the “index.html” file
Step 3: Copy the HTML code in the “index.html” file
Download the Source Code
<!DOCTYPE html>
<html>
<head>
<title>Welcome to HTML!</title>
</head>
<body>
<h1>This is a Heading 1</h1>
<p>This is a Paragraph.</p>
</body>
</html>
Live Preview
Sample Preview of the code in Brackets:
Step 4: Live Preview of the HTML Page
Click on the live preview button on the right hand side.
Try to change the text in the brackets editor and see how the changes are reflected live in the chrome
browser.

Understanding of HTML Tags:


See how the instruction given in the HTML file has been displayed by the browser.
2.6 – HTML Parts

Sample HTML
We will review the parts of HTML. Here is the sample HTML.
<!DOCTYPE html>
<html>
<head>
<title>Welcome to HTML!</title>
</head>
<body>
<h1>This is a Heading 1</h1>
<p>This is a Paragraph.</p>
</body>
</html>
DOC TYPE
!DOCTYPE is the first declaration of the HTML page. This will indicate the browser what type of
HTML version we are using.
If we want to tell browser to use different HTML version then we mention that in this DocType.
<!DOCTYPE html>
HTML
This is the root element and tell browser that this is a HTML document. All the HTML tags should be
inside this element.
You should not define anything outside this element.
HEAD
Head element is used for the following things:
Include other supporting files required for this page.
Tell search engine about your page.
Set Title for your Page.
Mention the Meta data about your page.
All the elements you define in the HEAD tag are not displayed on the page.
BODY
This is the place where you define all the elements. Any element defined under body will be displayed
on the page.

2.7 – HTML Boiler Plate

What is a Boiler Plate?


Boiler plate are like sample template that you can use as starting template to write your HTML page.

Boiler plates save time because you don’t have to type every time the same thing. It is a start point for
writing the web page. You can always build your own boiler plate template but you can download
some of the sample boiler plate from below.

Boiler Plate 1 – Empty Template


Download the Source Code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Live Preview
Boiler Plate 2 – Empty Template with Comments
Download the Source Code
<!DOCTYPE html>
<html>
<head>
<!-- All Meta tags goes here -->
</head>
<body> <!-- All Content tags goes here -->
</body>
</html>
Live Preview
Boiler Plate 3 – Empty Template with Title
Download the Source Code
<!DOCTYPE html>
<html>
<head>
<!-- All Meta tags goes here -->
<title>My First Web Page</title>
</head>
<body>
<!-- All Content tags goes here -->
</body>
</html>
Live Preview
Boiler Plate 4 – Empty Template with Meta Data
Download the Source Code
<!DOCTYPE html> <html>
<head>
<!-- All Meta tags goes here -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="First Web Page">
<title>My First Web Page</title>
</head>
<body>
<!-- All Content tags goes here -->
</body>
</html>
Live Preview
Boiler Plate 5 – Page Template with Heading
Download the Source Code
<!DOCTYPE html>
<html>
<head>
<!-- All Meta tags goes here --> <meta name="description" content="First Web Page">
<title>My First Web Page</title>
</head>
<body>
<!-- All Content tags goes here -->
<h1>Welcome to my First Page</h1>
</body>
</html>
Live Preview:
Boiler Plate 6 – Page Template with Paragraph
Download the Source Code
<!DOCTYPE html>
<html>
<head>
<!-- All Meta tags goes here -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="First Web Page">
<title>My First Web Page</title> </head>
<body>
<!-- All Content tags goes here -->
<h1>Welcome to my First Page</h1>
<!-- https://www.lipsum.com/ -->
<p>Lorem Ipsum is simply dummy text of the printing
and typesetting industry. Lorem Ipsum has been
the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and
scrambled it to make a type specimen book.
</p>
</body>
</html>
Live Preview:
Boiler Plate 7 – Standard HTML Template
Download the Source Code
<!DOCTYPE html>
<html>
<head> <meta name="description" content="Page Description">
<title>Page Title</title>
</head>
<body>
<h1>Heading</h1>
<p>Paragraph Text</p>
</body>
</html> Live Preview

3. TEXT ELEMENTS
3 TEXT ELEMENTS

3.1 – HTML Text Elements


Purpose of HTML Text Elements
Purpose of HTML Text elements is to display text in a format that is appealing and readable.
There are different types of HTML Text Elements that help to display our content like we see the
content in the newspaper and magazine.
Benefits of this Text Tags:
• Display Headings and Paragraphs
• Markup the Bold, Italics and Underlining the text.
• Show different format of text like Java code and normal readable text

Structural Markup
These are the markups that are used to define the text and give a real meaning to the text.
Like mentioning the Heading and Paragraphs on the Web Page.
Semantic Markup
Semantic elements are used to provide extra information to the user by bold text, underlines and
italics. They increase the readability and also help to mark the text in the paragraphs or headings.

Like marking a Quotation can also be done via the Semantic Markup.
List of HTML Text Elements
These are the HTML Text Elements that you will learn in this section:

• Headings
• Horizontal Lines
• Paragraph
• Single Line Breaks
• Strong
• Emphasis
• Underline
• Italics
• Code
• Preformatted
• More Text Tags

One Page Text Elements:


This is just a sample to show how all the elements looks like in the Web Page. Next topics, you will
learn all these elements one by one.
Download the Source Code
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>HTML Text Tags</title>
</head>
<body>
<!-- Headings -->
<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>
<!-- This is Horizontal Line -->
<h1>This is Horizontal Line.</h1>
<hr>
<!-- This is Paragraph -->
<h1>This is Paragraph.</h1>

<p>1. "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum."</p>

<!-- This is Single Line Breaks -->


<h1>This is Single Line Breaks.</h1>
<br><br>
<!-- This is Strong -->
<h1>This is Strong.</h1>

<p>1. "<strong>Lorem</strong> ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>

<!-- This is Emphasis -->


<h1>This is Emphasis.</h1>
<p>I <strong>love</strong> to write <em>HTML5</em>!</p>
<!-- This is Underline -->
<h1>This is Undeline.</h1>
<p>I <u><strong>love</strong></u> to write <em>HTML5</em>!</p>
<!-- This is Italics --> <h1>This is Italics.</h1>
<p>I <i><u><strong>love</strong></u></i> to write <em>HTML5</em>!</p>
<!-- This is Code -->
<h1>This is Code.</h1>
<code>
public void add(int a, int b){
return a + b;
}
</code>
=
<!-- This is Pre -->
<h1>This is Preformatted.</h1>
<code>
<pre>
<!-- Check the Whitespace importance! -->
public void add(int a, int b)
{
return a + b;
}
int c = add(1, 2); </pre>
</code>
<h1>Some More Text Formatting Tags</h1>
<p><del>This text is deleted</del> and <ins>This text is inserted</ins>.</p>
<p><s>This text has a strikethrough</s>.</p>
<p>Superscript<sup>®</sup>.</p>
<p>Subscript for things like H<sub>2</sub>O.</p>
<p><small>This small text is small for for fine print, etc.</small></p>
<p>Abbreviation: <abbr title="HyperText Markup Language">HTML</abbr></p>
<p><q cite="https://developer.mozilla.org/enUS/docs/HTML/Element/q">This text is a short inline
quotation.</q></p>
<p><cite>This is a citation.</cite></p>
<p>The <dfn>dfn element</dfn> indicates a definition.</p>
<p>The <mark>mark element</mark> indicates a highlight.</p>
<p>The <var>variable element</var>, such as <var>x</var> = <var>y</var>.</p>
</body> </html>
This is Heading 1. This is Heading 2.
This is Heading 3.

This is Heading 4.
This is Heading 5.
This is Heading 6.
This is Horizontal Line.
This is Paragraph.
1. “Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.”

This is Single Line Breaks.


This is Strong.
1. “Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.”

This is Emphasis.

I love to write HTML5!

This is Underline.

I love to write HTML5!

This is Italics.

I love to write HTML5!


This is Code.
public void add(int a, int b){
return a + b; }

This is Preformatted.
public void add(int a, int b)
{
return a + b;
}
int c = add(1, 2);
Some More Text Formatting Tags
This text is deleted and This text is inserted.
This text has a strikethrough.
Superscript®.
Subscript for things like H2O.
This small text is small for for fine print, etc.
Abbreviation: HTML
This text is a short inline quotation.
This is a citation.
The dfn element indicates a definition.
The mark element indicates a highlight.
The variable element, such as x = y. Live Preview:

3.2 – Headings

Usage of Headings
Headings are used to display title of the paragraph or show some text in bigger size and bolder.
There are 6 headings tags <h1> to <h6>

h1 is the bigger and h6 being the smallest. Headings text tags are always big in size and use to grab
attention of the user or show the purpose of the article.

The behavior of the headings can be change later using CSS which you will learn next.
Browser has a default settings to show headings.
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Headings</title>
</head>
<body>
<!-- Observe the default style -->
<!-- Observe the font size -->
<!-- Observe the new lines -->
<h1>This is Heading 1.</h1>
<h2>This is Heading 2.</h2> <h4>This is Heading 4.</h4>
<h5>This is Heading 5.</h5>
<h6>This is Heading 6.</h6>
</body> </html>

3.3 – Horizontal Lines

Usage of Horizontal Line


Horizontal line acts like a separator between the sections and paragraph.
This is used when you want to add some space between the paragraphs and also show a line indicating
a different topic.
TAG: <hr />
Remember that <hr> is a self-closing tag you don’t need to close it.
Attributes of hr tag:
width = percent (%)
align = left, right, center
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Horizontal Line</title>
</head>
<body>
<!-- Observe the spacing & line properties -->
<h1>This is Heading 1.</h1>
<hr>
<h2>This is Heading 2.</h2>
<hr>
<h3>This is Heading 3.</h3>
<hr>
<h4>This is Heading 4.</h4>
<hr>
<h5>This is Heading 5.</h5>
<hr> <hr width="50%" align="left">
</body>
</html> Live Preview:

3.4 – Paragraphs

Usage of Paragraphs
Paragraphs is the place where you put most of your content to display on the browser.
Paragraph tags helps to organize the content nicely into small container which makes content easy to
read and edit it.
TAG: <p>
ELEMENT: <p>sometext</p>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description"
content="Page Description">
<title>Paragraph</title>
</head>
<body>
<!-- Observe how the data is organized -->
<h1>Today's News</h1>

<p>1. It is a long established fact that a reader will be distracted by the readable content of a page
when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal
distribution of letters, as opposed to using 'Content here, content here', making it look like readable
English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their
default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.
Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected
humour and the like).</p>
<p>2. It is a long established fact that a reader will be distracted by the readable content of a page
when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal
distribution of letters, as opposed to using 'Content here, content here', making it look like readable
English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their
default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.
Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected
humour and the like).</p>

<p>3. It is a long established fact that a reader will be distracted by the readable content of a page
when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal
distribution of letters, as opposed to using 'Content here, content here', making it look like readable
English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their
default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.
Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected
humour and the like).</p>

</body>
</html>
Today’s News:
1. It is a long established fact that a reader will be distracted by the readable content of a page when
looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution
of letters, as opposed to using ‘Content here, content here’, making it look like readable English.
Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model
text, and a search for ‘lorem ipsum’ will uncover many web sites still in their infancy. Various versions
have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the
like).

2. It is a long established fact that a reader will be distracted by the readable content of a page when
looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution
of letters, as opposed to using ‘Content here, content here’, making it look like readable English.
Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model
text, and a search for ‘lorem ipsum’ will uncover many web sites still in their infancy. Various versions
have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the
like). 3. It is a long established fact that a reader will be distracted by the readable content of a page
when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal
distribution of letters, as opposed to using ‘Content here, content here’, making it look like readable
English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their
default model text, and a search for ‘lorem ipsum’ will uncover many web sites still in their infancy.
Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected
humour and the like).

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and write the Headings 1 to 3 and under
each Heading write a paragraph of text.
Live Preview
Exercise 2
Download the Exercise 2 Exercise 2: Create one HTML page and write the Headings 1
and some paragraph under it. Then draw a line under it and then show some more text.
Live Preview

3.5 – Single Line Break


Usage of Line Breaks
Line Breaks helps to break the link like the new line (\r\n) we have in the normal text file.
Breaks are used when we want to break a running line and start a new line. The more breaks you have
the more new lines are added.
TAG: <br>
ELEMENT: <br>
<br> is a self-enclosing tags.
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Line Break</title>
</head>
<body>
<!-- Observe how the data is organized with new line and empty spaces -->
<!-- <br> and <hr> are self closing tags -->

<h1>Today's News</h1> <p>1. It is a long established fact that a reader will be distracted by the
readable content of a page when looking at its layout. <br> The point of using Lorem Ipsum is that it
has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here',
making it look like readable English. Many desktop publishing packages and web page editors now
use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web
sites still in their infancy. Various versions have evolved over the years, sometimes by accident,
sometimes on purpose (injected humour and the like).</p>

<br>
<hr>

<p>2. It is a long established fact that a reader will be distracted by the readable content of a page
when looking at its layout. <br> <br> The point of using Lorem Ipsum is that it has a more-or-less
normal distribution of letters, as opposed to using 'Content here, content here', making it look like
readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as
their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their
infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose
(injected humour and the like).</p>

<br><br>
<hr>
<p>3. It is a long established fact that a reader will be distracted by the readable content of a page
when looking at its layout. <br> <br> <br> The point of using Lorem Ipsum is that it has a more-or-
less normal distribution of letters, as opposed to using 'Content here, content here', making it look like
readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as
their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their
infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose
(injected humour and the like).</p>

</body>
</html>
Today’s News:
1. It is a long established fact that a reader will be distracted by the readable content of a page when
looking at its layout.

The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed
to using ‘Content here, content here’, making it look like readable English. Many desktop publishing
packages and web page editors now use Lorem Ipsum as their default model text, and a search for
‘lorem ipsum’ will uncover many web sites still in their infancy. Various versions have evolved over
the years, sometimes by accident, sometimes on purpose (injected humour and the like).

2. It is a long established fact that a reader will be distracted by the readable content of a page when
looking at its layout.

The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed
to using ‘Content here, content here’, making it look like readable English. Many desktop publishing
packages and web page editors now use Lorem Ipsum as their default model text, and a search for
‘lorem ipsum’ will uncover many web sites still in their infancy. Various versions have evolved over
the years, sometimes by accident, sometimes on purpose (injected humour and the like).

3. It is a long established fact that a reader will be distracted by the readable content of a page when
looking at its layout.

The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed
to using ‘Content here, content here’, making it look like readable English. Many desktop publishing
packages and web page editors now use Lorem Ipsum as their default model text, and a search for
‘lorem ipsum’ will uncover many web sites still in their infancy. Various versions have evolved over
the years, sometimes by accident, sometimes on purpose (injected humour and the like),

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and add break line in the headings 1
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create one HTML page and break the paragraph line by line up to
10 lines.
Live Preview

3.6 – Strong Text


Usage of Strong
Strong tag helps to bold the text and highlight the text to emphasis some line in the paragraph.
It is often used in the Paragraphs.
TAG: <strong>
ELEMENT: <strong>something</strong>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Strong</title>
</head>
<body>
<!-- Observe how the data is organized -->
<h1>Today's News</h1>

<p>1. "<strong>Lorem</strong> ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>

<p>2. "<strong>Lorem ipsum</strong> dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>

<p>3. "<strong>Lorem ipsum dolor</strong> sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>

</body>
</html>
Today’s News

1. “Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.”

2. “Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.” 3. “Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.”

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and create three bold line in a paragraph.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create one HTML page and bold the first and last words in the
paragraphs.
Live Preview

3.7 – Emphasis Text

Usage of Emphasis
Emphasis is used to emphasis a word or line in the paragraphs. It is similar to italics but this is used
more to emphasis a word or line.
It is often used in the Paragraphs.
TAG: <em>
ELEMENT: <em>something</em>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Emphasis Tag</title>
</head>
<body>
<h1>Learning HTML5</h1>
<p>I <strong>love</strong> to write <em>HTML5</em>!</p>
</body>
</html>
Learning HTML5
I love to write HTML5!
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and make the entire paragraph emphasis

Live Preview

3.8 – Underline Text

Usage of Underline
Underline will simply underline the text.
It is often used in the Paragraphs.
TAG: <u>
ELEMENT: <u>something</u>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Underline Tag</title>
</head>
<body>
<h1>Learning HTML5</h1>
<p>I <u><strong>love</strong></u> to write <em>HTML5</em>!</p>
</body>
</html> Live Preview

3.9 – Italics

Usage of Italics
Italics tag will simply italics the text.
It is often used in the Paragraphs.
TAG: <i>
ELEMENT: <i>something</i>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Italics Tag</title>
</head>
<body>
<h1>Learning HTML5</h1>
<!-- i means italics and em means emphasis - Looks same right! -->
<!-- italics refer to font style but emphasis refers to readers context --> <p>I <i><u>
<strong>love</strong></u></i> to write <em>HTML5</em>!</p>
</body>
</html> Live Preview

3.10 – Code

Usage of Code
Code tag is used to display the programming source code on the web page.
Browser treats code tag as special and display it the code as it is written in the html. However, it
ignores the new lines. So, the code is displayed in one line.
TAG: <code>
ELEMENT: <code>function add(x, y){ return a + b }</code>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Code Tag</title> </head>
<body>
<h1>Add Function in Java!</h1>
<code>
public void add(int a, int b){
return a + b;
}
</code>
</body>
</html>
Add Function in Java!
public void add(int a, int b) {
return a + b;
}
Live Preview:
• https://phpbootcampdemo.com/html/code-html/em1/after
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and write a simple java code.
Live Preview

3.11 – Preformatted Tag

Usage of Pre
pre tag is used to display the white space and it will retain the indentation of the format that is written
in the html file
Browser does not format anything inside the pre tag but instead it will try to print as it is including the
spacing and formatting.
TAG: <pre>
ELEMENT: <pre>line1 line2 line3</pre>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Preformatted Tag</title>
</head>
<body>
<h1>Add Function in Java!</h1>
<code>
<pre>
<!-- Check the Whitespace importance! -->
public void add(int a, int b)
{
return a + b;
}
int c = add(1, 2);
</pre>
</code>
</body>
</html>
Add Function in Java!
public void add(int a, int b)
{
return a + b; }
int c = add(1, 2); Live Preview

3.12 – More HTML Text Tags

HTML Text Tags


Please find some more text tags that you can use in the HTML
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Preformatted Tag</title>
</head>
<body>
<h1>Some More Text Formatting Tags</h1>
<p><del>This text is deleted</del> and <ins>This text is inserted</ins>.</p> <p><s>This text has a
strikethrough</s>.</p>
<p>Superscript<sup>®</sup>.</p>
<p>Subscript for things like H<sub>2</sub>O.</p>
<p><small>This small text is small for for fine print, etc.</small></p>
<p>Abbreviation: <abbr title="HyperText Markup Language">HTML</abbr></p>
<p><q cite="https://developer.mozilla.org/enUS/docs/HTML/Element/q">This text is a short inline
quotation.</q></p>
<p><cite>This is a citation.</cite></p>
<p>The <dfn>dfn element</dfn> indicates a definition.</p>
<p>The <mark>mark element</mark> indicates a highlight.</p>
<p>The <var>variable element</var>, such as <var>x</var> = <var>y</var>.</p>
</body>
</html> Live Preview

4. LISTS

4 Lists
4.1 – Definition List

Usage of Definition List


Definition list is used to define Definition of list.
It is often used as a header for the list
TAG: <dl>, <dt>, <dd>
ELEMENT:
<dl>
<dt>title</dt>
<dd>definition</dd>
</dl>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description"
content="Page Description">
<title>Grouping</title>
</head>
<body>
<h1>Definition List</h1>
<dl>
<dt>This is Definition Title</dt>
<dd>This is Definition Description</dd>
</dl>
<dl>
<dt>HTML5</dt>
<dd>HTML5 stands for Hyper Text Markup Language used to write web pages <br> that is displayed
in the browser.</dd>
</dl>
</body>
</html>
Definition List:
This is Definition Title
This is Definition Description
HTML5 HTML5 stands for Hyper Text Markup Language used to write web pages
that is displayed in the browser.
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and create something like below with h1,
dl, p and hr.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create one HTML page and create something like below with h1,
dl, p and hr.
Live Preview

4.2 – Ordered List

Usage of Ordered List


Ordered List is used to show list of items with numbers.
It is often used to list the points like 1, 2, 3. The numbers will be auto generated by the tag.
TAG: <ol>, <li>
ELEMENT:
<ol>
<li>title</li>
<li>description</li>
</ol>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Grouping</title>
</head>
<body>
<h1>Definition List</h1>
<dl>
<dt>This is Definition Title</dt>
<dd>This is Definition Description</dd>
</dl>
<dl>
<dt>HTML5</dt>
<dd>HTML5 stands for Hyper Text Markup Language used to write web pages <br> that is displayed
in the browser.</dd>
</dl> <hr>
<h1>Ordered List</h1>
<ol>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
</ol>
</body>
</html>
Definition List
This is Definition Title
This is Definition Description
HTML5
HTML5 stands for Hyper Text Markup Language used to write web pages
that is displayed in the browser.
Ordered List
• List Item 1
• List Item 2
• List Item 3

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and create something like below.

Live Preview

4.3 – UnOrdered List

Usage of Un-Ordered List


Un-Ordered List is used to show list of items with circle dot.
It is often used to list the points without numbers. You can change the default list from circle dot to
any other symbol or image.
TAG: <ul>, <li>
ELEMENT:
<li>title</li>
<li>description</li>
</ul>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Grouping</title>
</head>
<body>
<h1>Definition List</h1>
<dl>
<dt>This is Definition Title</dt>
<dd>This is Definition Description</dd>
</dl>
<dl> <dt>HTML5</dt>
<dd>HTML5 stands for Hyper Text Markup Language used to write web pages <br> that is displayed
in the browser.</dd>
</dl>
<hr>
<h1>Ordered List</h1>
<ol>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
</ol>
<hr>
<h1>UnOrdered List</h1>
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
</ul>
<hr>
<h1>Learn HTML5</h1> <li>Why Learn HTML5?</li>
<ol>
<li>Create own Web Pages</li>
<li>Design Websites</li>
<li>Show off the skills</li>
</ol>
</ul>
</body>
</html>
Definition List
This is Definition Title
This is Definition Description
HTML5
HTML5 stands for Hyper Text Markup Language used to write web pages
that is displayed in the browser.
Ordered List
• List Item 1
• List Item 2
• List Item 3

UnOrdered List
• List Item 1
• List Item 2
• List Item 3

Learn HTML5
Why Learn HTML5?

1. Create own Web Pages


2. Design Websites
3. Show off the skills

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and create something like below.
Live Preview

5. ARTICLES
5 ARTICLES
5.1 – Articles

Usage of Article
Article is used to define one group of content which has heading, links and paragraph to make up one
independent content on the page.
A blog page can have list of all the articles displayed in small summary.
Article can have header, paragraph and footer. It makes up into a logical grouping of things in that
article.
<section> tag is used to group the articles into sections.
TAG: <article>, <section>, <header>, <footer>
ELEMENT:
<article>
<header>Header</header>
<p>Article Content</p>
<footer>Footer</footer>
</article>
We group the articles into sections
<section>
<article> <header>Article 1</header>
<p>Article Content</p>
<footer>Footer</footer>
</article>
<article>
<header>Article 2</header>
<p>Article Content</p>
<footer>Footer</footer>
</article>
</section>
Sample Example 1
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Sections</title>
</head> <body>
<section>
<article>
<header><h1>Header</h1></header>
<p>Article Content: Lorem Ipsum</p>
<footer><p>#Footer</p></footer>
</article>
</section>
</body>
</html>
Header
Article Content: Lorem Ipsum
#Footer
Live Preview
Sample Example 2
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Sections</title>
</head>
<body>
<section>
<article>
<header><h1><u>Article 1</u></h1></header>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has
been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.</p>

<footer><p>#End of Article 1</p></footer>


</article>
<hr>
<article>
<header><h1><u>Article 2</u></h1></header>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has
been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.</p>

<footer><p>#End of Article 2</p></footer> </article>


</section>
</body>
</html>
Article 1
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been
the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of
type and scrambled it to make a type specimen book.

#End of Article 1
Article 2
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been
the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of
type and scrambled it to make a type specimen book.

#End of Article 2
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and make the page look like this with
Articles
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create one HTML page and make the page looks like this with
Article tag.
Live Preview

6. TABLES
6 TABLES
6.1 – Simple Table

Usage of Table
Table is used to arrange data in a row and column format. It is similar to show data in a database
format or excel sheet format.
Table tags:
<table> tag is used to defined the table
<th> is used to define heading.
<tr> is used to mention row.
<td> represents column in the table.
TAG: <table>, <th>, <tr>, <td>
ELEMENT:
<table>
<th>Heading</th>
<tr>
<td>Column</td>
</tr>
</table>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Simple Table</title>
</head>
<body>
<h1>Simple Table Example</h1>
<table>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
</tr>
<tr>
<td>Col 1</td>
<td>Col 2</td> </tr>
</table>
<hr>
<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>John Smith</td>
</tr>
<tr>
<td>2</td>
<td>Walter Junior</td>
</tr>
</table>
</body>
</html>
Simple Table Example:
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and create table like this with simple row
and column.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create one HTML page and display all rows in one column.

Live Preview

6.2 – Table with Borders

Usage of Table Border


Border is an attribute of the Table.
border – Specify the border width to draw the line around the table.
Border will help to display the lines of the table to understand the width and height of each cell.
You can mention the width of the border with this value.
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Table with Border</title>
</head>
<body>
<h1>Table with Border Example</h1>
<table border="1">
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
</tr>
<tr>
<td>Col 1</td>
<td>Col 2</td>
</tr>
</table> <hr>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>John Smith</td>
</tr>
<tr>
<td>2</td>
<td>Walter Junior</td>
</tr>
</table>
</body>
</html>
Table with Border Example:
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and create something like below.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create one HTML page and create something like below.
Live Preview

6.3 – Table with Header and Footer

Usage of Header and Footer


Table has two important section apart from row and column and that is header and footer.
Header and footer as they are used to specify some text before row and after row. Like headings and
sub totals.
TAG: <table>, <caption>, <thead>, <tfoot>, <tbody>
ELEMENT:
<table>
<caption>Caption</caption>
<thead>
<tr>
<td>Heading 1</td>
</tr>
</thead>
<tfoot>
<tr>
<td>Footer 1</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Column 1</td>
</tr>
</tbody>
</table>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Table with Header and Footer</title>
</head>
<body>
<h1>Table with Heading and Footer</h1>
<table border="1">
<caption>Table Caption</caption>
<thead>
<tr>
<td>Heading 1</td>
<td>Heading 2</td>
</tr>
</thead>
<tfoot>
<tr>
<td>Footer 1</td>
<td>Footer 2</td>
</tr>
</tfoot> <tbody>
<tr>
<td>Column 1</td>
<td>Column 2</td>
</tr>
<tr>
<td>Column 1</td>
<td>Column 2</td>
</tr>
</tbody>
</table>
<hr>
<table border="1">
<caption>Employee Salary</caption>
<thead>
<tr>
<td>Month</td>
<td>Salary</td>
</tr>
</thead> <tfoot>
<tr>
<td>2018</td>
<td>$1000</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Jan</td>
<td>$500</td>
</tr>
<tr>
<td>May</td>
<td>$500</td>
</tr>
</tbody>
</table>
</body>
</html>
Table with Heading and Footer:
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and create table like this
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create one HTML page and display table like this.
Live Preview

6.4 – Table with RowSpan and ColSpan

Usage of Rowspan and ColSpan


RowSpan and ColSpan is to add spacing to the cell. If you want to merge two cell together then this
attribute will help.
rowspan and colspan are attribute you can use in the <td> or <tr>f
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Table with RowSpan and ColSpan</title>
</head>
<body>
<h1>Table with RowSpan and ColSpan Example</h1>
<table border="1">
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
</tr>
<tr>
<td>Col 1</td>
<td rowspan="2">Col 2</td>
<td>Col 3</td>
</tr>
<tr> <td>Col 1</td>
<td>Col 3</td>
</tr>
</table>
<hr>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>John Smith</td>
</tr>
<tr>
<td colspan="2">Total: 2</td>
</tr>
</table>
</body>
</html>
Table with RowSpan and ColSpan Example:
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and create table like this with simple row
and column.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create one HTML page and display all rows in one column.
Live Preview

7. EMBED CONTENTS
7 EMBED CONTENTS

Purpose of Embed Tags


Embed tags are used to include external resource into the html page. These resources could be in your
server or located at some other location.

• Well, the main purpose of WWW was to connect all the contents together with a link and that makes
the web so powerful that it has ability to connect things all over the web.

This concept makes the whole web very powerful.

• Here are the list of things you can embed in the HTML Page:
• Image
• Image with Attributes
• Image with Article
• Audio
• Video
• Embed one Page into Another (iFrame)
• Link Pages
• Anchor Links in the same page

These concepts will give you good idea on how to build your web page by combining the different
components together.

Till now we have been working on writing text on the HTML page but in this section you will learn
how to embed objects like image, audio or video on the page.

7.1 – Embed Image

Usage of Embed Image


<img> tag is used to embed image in the html page. The image could be in the same server or it could
be in the different server location.
Good example could be the images you see on this page is coming up from the server and embedded
into this page with the <img> tag.
TAG: <img>
ELEMENT: <img src=”location” />
src – is an attribute of img tag and point to the location of the image file.
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Embedded Image</title>
</head>
<body> <h1>German Shepherd</h1>
<img src ="dog1.jpg" alt="German Shepherd" >

<p>The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of


medium to large-sized working dog that originated in Germany. The breed's officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland.[5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep. </p>

<hr>
<h1>Vacation Time!</h1>
<img src="https://i.imgur.com/xtoLyW2.jpg">
</body>
</html>
German Shepherd:
The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of
medium to large-sized working dog that originated in Germany. The breed’s officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland.[5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep.

Vacation Time!
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Put two images side by side in a table format.
Live Preview

7.2 – Embed Image with Attributes


Usage of Embed Image with Attributes
<img> tag has some attributes that can help to
resize the image
control the position of the image
Align text beside it
Alternative text to display when image is not loaded properly

Good example could be the size of the image you can specify the image height and width with the
attribute.
alt attribute is displayed when image is not shown properly or missing. This also helps to show as a
tool tip when you hover over the image.

TAG: <img>
ELEMENT: <img src=”location” width=”643″ height=”389″ alt =”Hover on me” />
width– specifies the width of the image.
height– specifies the height of the image.
alt– specifies the alternative text of that image. Displays this text when image cannot be loaded.
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Image Attributes</title>
</head>
<body>
<h1>German Shepherd</h1> <img src ="dog1.jpg" alt="This is alt text displayed for missing image"
height="256" width="256 ">

<p>The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of


medium to large-sized working dog that originated in Germany. The breed's officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland.[5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep. </p>

<hr>
<h1><img src="https://i.imgur.com/xtoLyW2.jpg" height="128" width="128"> Vacation Time!</h1>
<hr>
</body>
</html>
German Shepherd
The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of
medium to large-sized working dog that originated in Germany. The breed’s officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland.[5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep.

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Display images in small thumbnails (Width: 64 x Height: 64)

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Make lines with Images Horizontal and Vertical.
Live Preview

7.3 – Embed Image in the Article

Usage of Embed Image in Article


<figure> is element inside the article that lets you define a image properly with a <figcaption> caption
as well.
TAG: <figure>, <figcaption>
ELEMENT:
<article>
<figure>
<img src =”dog1.jpg” alt=”German Shepherd” height=”256″ width=”256″> </article>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
<meta name="description" content="Page Description">
<title>Image Article</title>
</head>
<body>
<section>
<article>
<header><h2>German Shepherd</h2></header>
<figure>
<img src ="dog1.jpg" alt="German Shepherd" height="256" width="256">

<p>The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of


medium to large-sized working dog that originated in Germany. The breed's officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland.[5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep. </p>

<footer>True friend!</footer>
</article>
</section>
</body>
</html>
German Shepherd
Best bread in Dog Family

The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of


medium to large-sized working dog that originated in Germany. The breed’s officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland.[5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep.

True friend!
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write Two Articles side by side like below.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Add thumbnail images in the Article.
Live Preview

7.4 – Embed Audio

Usage of Embed Audio


<audio> elements are used to embed audio files in the html page.
TAG: <audio>
ELEMENT:
<audio controls autoplay>
<source src=”dogbarking.mp3″ type=”audio/mpeg”>
The browser does not support this audio format.
</audio>
autoplay – This attribute of Audio helps to play the audio automatically
controls – This attribute of Audio helps to show the audio controls.
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Audio Example</title>
</head>
<body>
<section>
<article>
<header><h2>German Shepherd</h2></header>
<figure>
<img src ="dog1.jpg" alt="German Shepherd" height="256" width="256">
<figcaption>Best bread in Dog Family</figcaption>
</figure>
<div>
<p> <audio controls>
<source src="dog-barking.mp3" type="audio/mpeg">
Having issue with the Audio?
</audio>
</p>
</div>

<p>The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of


medium to large-sized working dog that originated in Germany. The breed's officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland.[5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep. </p>

<footer>True friend!</footer>
</article>
</section>
</body>
</html>
German Shepherd:
The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of
medium to large-sized working dog that originated in Germany. The breed’s officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland.[5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep.

True friend!
Exercise 1
Download the Exercise 1
Exercise 1: Embed two Audio files in the same page.
Live Preview

7.5 – Embed Video

Usage of Embed Video


<video> elements are used to embed video files in the html page.
TAG: <video>
ELEMENT:
<video width=”320″ height=”240″ controls>
<source src=”Dog.mp4″ type=”video/mp4″>
Having issue with the Video?
</video>
controls – This attribute of Video helps to show the video controls.
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Video Example</title>
</head>
<body>
<section>
<article>
<header><h2>German Shepherd</h2></header>
<figure> <img src ="dog1.jpg" alt="German Shepherd" height="256" width="256">
<figcaption>Best bread in Dog Family</figcaption>
</figure>
<div>
<p>
<video width="320" height="240" controls>
<source src="Dog.mp4" type="video/mp4">
Having issue with the Video?
</video>
</p>
</div>

<p>The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of


medium to large-sized working dog that originated in Germany. The breed's officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland.[5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep. </p>

<footer>True friend!</footer>
</article>
</section> </body>
</html>
German Shepherd:
The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of
medium to large-sized working dog that originated in Germany. The breed’s officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland. [5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep.

True friend!
Exercise 1
Download the Exercise 1
Exercise 1: Embed Two Video files in the same page. Separate them with line.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Hide all the controls of the Video. Do not delete the Video tag but hide it.

7.6 – Embed iFrame

Usage of Embed Frame


<iframe> tags are used to embed other html page inside the existing one.
TAG: <iframe>
ELEMENT:
<iframe src=”iframesample.html” height=”300″></iframe>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>iFrame Example</title> </head>
<body>
<iframe src="iframe-sample.html" height="300"></iframe>
</body>
</html>
Exercise 1
Download the Exercise 1
Exercise 1: Embed two file into 1 HTML page one after the other.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2 : Show the iframe side by side.
Live Preview

7.7 – Embed Links

Usage of Embed Links


<a> tag allows you to link other pages, images, audio or video file or any other url using the <a> tag.
This is the most powerful and important tag in HTML that you will be using alot.
TAG: <a>
ELEMENT: <a href=”location” />
target – This attribute decides where the link should open
target = “_blank” – Will open the link in another window
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Hyperlink Example</title>
</head>
<body>
<h1>Hyperlink Example</h1>
<a href="https://www.google.com">Open Google.com Site Here.</a>
<br>
<a href="https://www.google.com" target="_blank">Open Google.com Site in New Window.</a>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Put a link to another page from existing page. Back to the old page.
Live Preview
Exercise 2
Download the Exercise 2 Exercise 2: Create 1 link that opens the image into another
page.

Live Preview

7.8 – Embed Anchor

Usage of Embed Anchor


<a> tag allows you to link to the specific section of the page.
Anchors helps users to jump on the specific section of the same page.
id – This id attribute is first assigned to the tag to mark as a anchor.
Using <a> tag, we can provide link to that specific location of the page.
TAG: <a>
ELEMENT:
<h1 id=”location1″>
<a href=”#location1″>Go Location 1</a>
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.<br>0">
<meta name="description" content="Page Description">
<title>Hyperlink Example</title>
</head>
<body>
<h1 id="top">Hyperlink Example</h1>
<div >
<p>
What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry.<br> Lorem Ipsum has
been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.<br> It has survived not only five centuries,
but also the leap into electronic typesetting, remaining essentially unchanged.<br> It was popularised
in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<br>

Why do we use it?

It is a long established fact that a reader will be distracted by the readable content of a page when
looking at its layout.<br> The point of using Lorem Ipsum is that it has a more-or-less normal
distribution of letters, as opposed to using 'Content here, content here', making it look like readable
English.<br> Many desktop publishing packages and web page editors now use Lorem Ipsum as their
default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.
<br> Various versions have evolved over the years, sometimes by accident, sometimes on purpose
(injected humour and the like).<br>

Where does it come from?

Contrary to popular belief, Lorem Ipsum is not simply random text.<br> It has roots in a piece of
classical Latin literature from 45 BC, making it over 2000 years old.<br> Richard McClintock, a Latin
professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words,
consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical
literature, discovered the undoubtable source.<br> Lorem Ipsum comes from sections 1.<br>10.
<br>32 and 1.<br>10.<br>33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil)
by Cicero, written in 45 BC.<br> This book is a treatise on the theory of ethics, very popular during
the Renaissance.<br> The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet.<br>.<br>", comes
from a line in section 1.<br>10.<br>32.<br>

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested.
<br> Sections 1.<br>10.<br>32 and 1.<br>10.<br>33 from "de Finibus Bonorum et Malorum" by
Cicero are also reproduced in their exact original form, accompanied by English versions from the
1914 translation by H.<br> Rackham.<br>

</p>
<p>
What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry.<br> Lorem Ipsum has
been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.<br> It has survived not only five centuries,
but also the leap into electronic typesetting, remaining essentially unchanged.<br> It was popularised
in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<br>

Why do we use it?

It is a long established fact that a reader will be distracted by the readable content of a page when
looking at its layout.<br> The point of using Lorem Ipsum is that it has a more-or-less normal
distribution of letters, as opposed to using 'Content here, content here', making it look like readable
English.<br> Many desktop publishing packages and web page editors now use Lorem Ipsum as their
default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.
<br> Various versions have evolved over the years, sometimes by accident, sometimes on purpose
(injected humour and the like).<br>

Where does it come from?

Contrary to popular belief, Lorem Ipsum is not simply random text.<br> It has roots in a piece of
classical Latin literature from 45 BC, making it over 2000 years old.<br> Richard McClintock, a Latin
professor at HampdenSydney College in Virginia, looked up one of the more obscure Latin words,
consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical
literature, discovered the undoubtable source.<br> Lorem Ipsum comes from sections 1.<br>10.
<br>32 and 1.<br>10.<br>33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil)
by Cicero, written in 45 BC.<br> This book is a treatise on the theory of ethics, very popular during
the Renaissance.<br> The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet.<br>.<br>", comes
from a line in section 1.<br>10.<br>32.<br>

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested.
<br> Sections 1.<br>10.<br>32 and 1.<br>10.<br>33 from "de Finibus Bonorum et Malorum" by
Cicero are also reproduced in their exact original form, accompanied by English versions from the
1914 translation by H.<br> Rackham.<br>

</p>
</div>
<a href="#top">Go Top</a>
</body> </html>
Exercise 1
Download the Exercise 1
Exercise 1: Create 5 Anchor points in the page.
Live Preview
8. FORMS

8 FORMS

Purpose of Form Elements


Form elements are the basic building blocks of HTML page. This is most common elements that you
will be using for any website development project.
Common scenario where you will use form elements:
Contact Form
Newsletter Form
Register or Login Form
Personal Information Form
Forms are used to collect information from the user and post the data to the script running on the
server.
The script on the server can save the data in the database or file.

With forms, you can restrict the data submit to the server and use different form elements to capture
different type of data from user. Like you can collect email id, phone number or Date from the form.

Here are the list of Form Elements which are most commonly used:

• Basic Form Elements


• Input Elements
• Select Element • Checkboxes
• Text Area
• Other Form Elements
• Form Action – GET
• Form Action – POST

• Radio Buttons
Learning how to work with the form elements can help you build a form on the web page that capture
the data from the user.
Remember, Forms are used to capture data from user and post them to script running on the server
which might take action on the data.

8.1 – Basic Form Elements

Usage of Basic Form Elements


Form tag are used to define all the form elements and into which users enter the data and submit the
data to the user.
To capture the user data, we define form and all the elements depending on the type of the data to be
captured from the user.
All the form elements should be defined inside the <form> tag.
TAG: <form>
ELEMENT:
<form>
<input type=”text” id=”input_name” >
<input type=”submit”>
<input type=”reset”> </form>
id – is an attribute that can used to identify that element in the HTML page.
In the Example below,
<label for=”input_name”>Label for Input Box:</label>
<input id =”input_name” type=”text” placeholder=”Placeholder”>
label is used to enter some text before the input field.
for attribute in label indicates the label is for which input tag.
input tag is used to define type of the field with the type field.
type attribute value is “text” which indicates that is a text box.
placeholder attribute shows a small text in the box to indicate what to type
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Form Elements</title>
</head> <body>
<h1>Form Basic Elements</h1>
<form>
<label for="input_name">Label for Input Box:</label>
<input id ="input_name" type="text" placeholder="Placeholder">
<p><input type="submit"> <input type="reset"></p>
</form>
<hr>
<h1>Student Information Form</h1>
<form>
<p>
<label for="input_name">Full Name:</label>
<input id ="input_name" type="text" placeholder="Name here">
</p>
<p>
<label for="input_age">Age:</label>
<input id ="input_age" type="text" placeholder="Your Age">
</p>
<p>
<label for="input_hobbies">Hobbies:</label> <input id ="input_hobbies" type="text"
placeholder="Seperate Hobbies with ,">
</p>
<p><input type="submit" value="Send"> <input type="reset" value="Clear"></p>
</form>
</body>
</html> Form Basic Elements:
Student Information Form:

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create a form like this below
Live Preview

8.2 – Input Box Form Elements

Usage of Input Box Form Element


<input> tag elements are used to display text box, submit buttons, email boxes and many other types
of form elements.
input tags are defined inside the form elements.
TAG: <input>, <fieldset>, <legend>, <form>
ELEMENT:
<form>
<fieldset>
<legend>Input Fields</legend>
<input type=”text” id=”input_name” >
<input type=”submit”>
<input type=”reset”>
</fieldset>
</form>
fieldset tag is used to group the elements together.
legend tag is used to display short heading of group of elements for readability purpose.
id – is an attribute used to identify an element or give a reference name to it.
type is an attribute used to indicate that input type is text or submit or reset button.
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description"> <title>Form Elements</title>
</head>
<body>
<h1>Form Basic Elements</h1>
<form>
<fieldset>
<legend>Input Box Elements</legend>
<p>
<label for="input_text">Text:</label>
<input id ="input_text" type="text" placeholder="Text">
</p>
<p>
<label for="input_email">Email:</label>
<input id ="input_email" type="email" placeholder="test@domain.com">
</p>
<p>
<label for="input_password">Password:</label>
<input id ="input_password" type="password" placeholder="Password">
</p> <p>
<label for="input_number">Number:</label>
<input id ="input_number" type="number" placeholder="Number">
</p>
<p>
<label for="input_phonenumber">Phone Number:</label>
<input id ="input_phonenumber" type="tel" placeholder="(999) 999999">
</p>
<p>
<label for="input_url">URL:</label>
<input id ="input_url" type="url" placeholder="http://somesite.com">
</p>
<p>
<label for="input_search">Search:</label>
<input id ="input_search" type="search" placeholder="Search...">
</p>
</fieldset>
<p><input type="submit"> <input type="reset"></p>
</form>
<hr> <h1>Student Information Form</h1>
<form>
<p>
<label for="input_name">Full Name:</label>
<input id ="input_name" type="text" placeholder="Name here">
</p>
<p>
<label for="input_age">Age:</label>
<input id ="input_age" type="number" placeholder="Your Age">
</p>
<p>
<label for="input_hobbies">Email ID:</label>
<input id ="input_hobbies" type="email" placeholder="Email ID">
</p>
<p><input type="submit" value="Send"> <input type="reset" value="Clear"></p>
</form>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Use FieldSet and Legend around the Personal Information Form.
Live Preview:

8.3 – Select Form Elements

Usage of Select Form Element


<select> Form elements are used to show list of values that user can select from.
■ It is like asking user to select one from the option given.
TAG: <select>, <option>, <optgroup>
ELEMENT:

■ <form>
■ <select>
■ ■ 10″>
■ <option>1</option>
■ <option>2</option>
■ </optgroup>
■ </select>
■ </form>
optgroup will group the options together with a label.

Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Form Elements</title>
</head>
<body>
<h1>Form Basic Elements</h1>
<form>
<fieldset>
<legend>Input Box Elements</legend>
<p>
<label for="input_text">Text:</label>
<input id ="input_text" type="text" placeholder="Text">
</p> <p>
<label for="input_email">Email:</label>
<input id ="input_email" type="email" placeholder="test@domain.com">
</p>
<p>
<label for="input_password">Password:</label>
<input id ="input_password" type="password" placeholder="Password">
</p>
<p>
<label for="input_number">Number:</label>
<input id ="input_number" type="number" placeholder="Number">
</p>
<p>
<label for="input_phonenumber">Phone Number:</label>
<input id ="input_phonenumber" type="tel" placeholder="(999) 999999">
</p>
<p>
<label for="input_url">URL:</label> <input id ="input_url" type="url"
placeholder="http://somesite.com">
</p>
<p>
<label for="input_search">Search:</label>
<input id ="input_search" type="search" placeholder="Search...">
</p>
</fieldset>
<fieldset>
<legend>Select Form Element</legend>
<p>
<label for="select">Select</label>
<select id="select">
<optgroup label="Option Group 1">
<option>Option1 One</option>
<option>Option1 Two</option>
<option>Option1 Three</option>
</optgroup>
<optgroup label="Option Group 2">
<option>Option2 One</option>
<option>Option2 Two</option> <option>Option2 Three</option>
</optgroup>
</select>
</p>
</fieldset>
<p><input type="submit"> <input type="reset"></p>
</form>
<hr>
<h1>Student Information Form</h1>
<form>
<p>
<label for="input_name">Full Name:</label>
<input id ="input_name" type="text" placeholder="Name here">
</p>
<p>
<label for="input_age">Age:</label>
<input id ="input_age" type="number" placeholder="Your Age">
</p>
<p>
<label for="input_hobbies">Email ID:</label> <input id ="input_hobbies" type="email"
placeholder="Email ID">
</p>
<p>
<label for="input_mobile">Mobile No.:</label>
<input id ="input_mobile" type="tel" placeholder="Contact Number">
</p>
<p>
<label for="select_class">Applying for</label>
<select id="select_class">
<optgroup label="Primary">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
</optgroup>
<optgroup label="Secondary"> <option>8</option>
<option>9</option>
<option>10</option>
</optgroup>
</select>
</p>
<p><input type="submit" value="Send"> <input type="reset" value="Clear"></p>
</form>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Show Select group 1-10 values with 1-10 as header and A-D as
group header with A-D options in the form.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Show all the months in the select element.

Live Preview

8.4 – Radio Buttons Form Elements

Usage of Radio Buttons


Radio buttons are used to give options for user to pick one option from the various options provided.
User can only select one from the options
TAG: <input>
ELEMENT:
<form>
<input id =”radio1″ name=”gender” type=”radio” checked>
<input id =”radio2″ name=”gender” type=”radio” >

</form>
➢ type = radio will change the input type to radio button. ➢ checked attribute will select the radio
button.

Sample Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Form Elements</title>
</head>
<body>
<h1>Form Basic Elements</h1>
<form>
<fieldset>
<legend>Input Box Elements</legend>
<p>
<label for="input_text">Text:</label>
<input id ="input_text" type="text" placeholder="Text">
</p> <p>
<label for="input_email">Email:</label>
<input id ="input_email" type="email" placeholder="test@domain.com">
</p>
<p>
<label for="input_password">Password:</label>
<input id ="input_password" type="password" placeholder="Password">
</p>
<p>
<label for="input_number">Number:</label>
<input id ="input_number" type="number" placeholder="Number">
</p>
<p>
<label for="input_phonenumber">Phone Number:</label>
<input id ="input_phonenumber" type="tel" placeholder="(999) 999999">
</p>
<p>
<label for="input_url">URL:</label> <input id ="input_url" type="url"
placeholder="http://somesite.com">
</p>
<p>
<label for="input_search">Search:</label>
<input id ="input_search" type="search" placeholder="Search...">
</p>
</fieldset>
<fieldset>
<legend>Select Form Element</legend>
<p>
<label for="select">Select</label>
<select id="select">
<optgroup label="Option Group 1">
<option>Option1 One</option>
<option>Option1 Two</option>
<option>Option1 Three</option>
</optgroup>
<optgroup label="Option Group 2">
<option>Option2 One</option>
<option>Option2 Two</option> <option>Option2 Three</option>
</optgroup>
</select>
</p>
</fieldset>
<fieldset>
<legend>Radio Button Element</legend>
<p>
<ul>
<li>
<label for="radio_option1">Option 1:</label>
<input id ="radio_option1" name="radio" type="radio" checked>
</li>
<li>
<label for="radio_option2">Option 2:</label>
<input id ="radio_option2" name="radio" type="radio">
</li>
</ul>
</p>
</fieldset> <p><input type="submit"> <input type="reset"></p>
</form>
<hr>
<h1>Student Information Form</h1>
<form>
<p>
<label for="input_name">Full Name:</label>
<input id ="input_name" type="text" placeholder="Name here">
</p>
<p>
<label for="input_age">Age:</label>
<input id ="input_age" type="number" placeholder="Your Age">
</p>
<p>
<label for="input_hobbies">Email ID:</label>
<input id ="input_hobbies" type="email" placeholder="Email ID">
</p>
<p>
<label for="input_mobile">Mobile No.:</label>
<input id ="input_mobile" type="tel" placeholder="Contact Number"> <p>
<label for="select_class">Applying for</label>
<select id="select_class">
<optgroup label="Primary">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
</optgroup>
<optgroup label="Secondary">
<option>8</option>
<option>9</option>
<option>10</option>
</optgroup>
</select> <!-- Observe how the Radio buttons are grouped with name attribute -->
<p>
<h3>Gender</h3>
<label for="radio_male">Male:</label>
<input id ="radio_male" name="gender" type="radio" checked>
<label for="radio_female">Female:</label>
<input id ="radio_female" name="gender" type="radio">
</p>
<p><input type="submit" value="Send"> <input type="reset" value="Clear"></p>
</form>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create two groups of Radio Button and make sure anyone can be selected in that 4

radio button

8.5 – Checkbox Form Elements

Usage of Checkbox
Checkbox buttons are used to pick many options from the list of the items displayed.
User can only select one or more from the options
TAG: <input>
ELEMENT:
<form>
<input id =”chk1″ name=”checkbox1” type=”checkbox” checked>
<input id =”chk2″ name=”checkbox2″ type=”checkbox” >
</form>
type = checkbox will change the input type to checkbox button.
checked attribute will select the checkbox button.
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Form Elements</title>
</head>
<body>
<h1>Form Basic Elements</h1>
<form>
<fieldset>
<legend>Input Box Elements</legend>
<p>
<label for="input_text">Text:</label>
<input id ="input_text" type="text" placeholder="Text">
</p>
<p>
<label for="input_email">Email:</label>
<input id ="input_email" type="email" placeholder="test@domain.com">
</p>
<p>
<label for="input_password">Password:</label> <input id ="input_password" type="password"
placeholder="Password">
</p>
<p>
<label for="input_number">Number:</label>
<input id ="input_number" type="number" placeholder="Number">
</p>
<p>
<label for="input_phonenumber">Phone Number:</label>
<input id ="input_phonenumber" type="tel" placeholder="(999) 999999">
</p>
<p>
<label for="input_url">URL:</label>
<input id ="input_url" type="url" placeholder="http://somesite.com">
</p>
<p>
<label for="input_search">Search:</label>
<input id ="input_search" type="search" placeholder="Search...">
</p>
</fieldset> <fieldset>
<legend>Select Form Element</legend>
<p>
<label for="select">Select</label>
<select id="select">
<optgroup label="Option Group 1">
<option>Option1 One</option>
<option>Option1 Two</option>
<option>Option1 Three</option>
</optgroup>
<optgroup label="Option Group 2">
<option>Option2 One</option>
<option>Option2 Two</option>
<option>Option2 Three</option>
</optgroup>
</select>
</p>
</fieldset>
<fieldset> <legend>Radio Button Element</legend>
<p>
<ul>
<li>
<label for="radio_option1">Option 1:</label>
<input id ="radio_option1" name="radio" type="radio" checked>
</li>
<li>
<label for="radio_option2">Option 2:</label>
<input id ="radio_option2" name="radio" type="radio">
</li>
</ul>
</p>
</fieldset>
<fieldset>
<legend>Checkbox Element</legend>
<p>
<label for="checkbox_option1">Checkbox 1:</label>
<input id ="checkbox_option1" name="checkbox1" type="checkbox" checked>
<label for="checkbox_option2">Checkbox 2:</label> <input id ="checkbox_option2"
name="checkbox2" type="checkbox">
<label for="checkbox_option3">Checkbox 3:</label>
<input id ="checkbox_option3" name="checkbox3" type="checkbox">
</p>
</fieldset>
<p><input type="submit"> <input type="reset"></p>
</form>
<hr>
<h1>Student Information Form</h1>
<form>
<p>
<label for="input_name">Full Name:</label>
<input id ="input_name" type="text" placeholder="Name here">
</p>
<p>
<label for="input_age">Age:</label>
<input id ="input_age" type="number" placeholder="Your Age">
</p>
<p> <label for="input_hobbies">Email ID:</label>
<input id ="input_hobbies" type="email" placeholder="Email ID">
</p>
<p>
<label for="input_mobile">Mobile No.:</label>
<input id ="input_mobile" type="tel" placeholder="Contact Number">
</p>
<p>
<label for="select_class">Applying for</label>
<select id="select_class">
<optgroup label="Primary">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
</optgroup>
<optgroup label="Secondary"> <option>8</option>
<option>9</option>
<option>10</option>
</optgroup>
</select>
</p>
<p>
<h3>Gender</h3>
<label for="radio_male">Male:</label>
<input id ="radio_male" name="gender" type="radio" checked>
<label for="radio_female">Female:</label>
<input id ="radio_female" name="gender" type="radio">
</p>
<!-- Observe how the Checkbox are grouped with name attribute -->
<p>
<h3>Do you need these special services:</h3>
<label for="checkbox_bus">School Bus:</label>
<input id ="checkbox_bus" name="checkbox1" type="checkbox">
<label for="checkbox_lunch">School Lunch:</label>
<input id ="checkbox_lunch" name="checkbox2" type="checkbox"> <label
for="checkbox_facility">Hostel Facility:</label>
<input id ="checkbox_facility" name="checkbox3" type="checkbox">
</p>
<p><input type="submit" value="Send"> <input type="reset" value="Clear"></p>
</form>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create two groups of checkbox and independent of each other.

Live Preview

8.6 – TextArea Form Elements

Usage of Text Area


Text area is similar to text box but you can enter multiple line in the text area and also control the
width and height of the box by specifying the rows and columns attribute of it.

This is mostly used to capture long text from user on the form.
TAG: <textarea>
ELEMENT:
<form>
<textarea rows = “5” cols=”50″ ></textarea>
</form>
id – is an attribute used to give a identifier or reference name to that element.
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Form Elements</title>
</head> <body>
<h1>Form Basic Elements</h1>
<form>
<fieldset>
<legend>Input Box Elements</legend>
<p>
<label for="input_text">Text:</label>
<input id ="input_text" type="text" placeholder="Text">
</p>
<p>
<label for="input_email">Email:</label>
<input id ="input_email" type="email" placeholder="test@domain.com">
</p>
<p>
<label for="input_password">Password:</label>
<input id ="input_password" type="password" placeholder="Password">
</p>
<p>
<label for="input_number">Number:</label> <input id ="input_number" type="number"
placeholder="Number">
</p>
<p>
<label for="input_phonenumber">Phone Number:</label>
<input id ="input_phonenumber" type="tel" placeholder="(999) 999999">
</p>
<p>
<label for="input_url">URL:</label>
<input id ="input_url" type="url" placeholder="http://somesite.com">
</p>
<p>
<label for="input_search">Search:</label>
<input id ="input_search" type="search" placeholder="Search...">
</p>
</fieldset>
<fieldset>
<legend>Select Form Element</legend>
<p>
<label for="select">Select</label>
<select id="select"> <optgroup label="Option Group 1">
<option>Option1 One</option>
<option>Option1 Two</option>
<option>Option1 Three</option>
</optgroup>
<optgroup label="Option Group 2">
<option>Option2 One</option>
<option>Option2 Two</option>
<option>Option2 Three</option>
</optgroup>
</select>
</p>
</fieldset>
<fieldset>
<legend>Radio Button Element</legend>
<p>
<ul>
<li>
<label for="radio_option1">Option 1:</label>
<input id ="radio_option1" name="radio" type="radio" checked> </li>
<li>
<label for="radio_option2">Option 2:</label>
<input id ="radio_option2" name="radio" type="radio">
</li>
</ul>
</p>
</fieldset>
<fieldset>
<legend>Checkbox Element</legend>
<p>
<label for="checkbox_option1">Checkbox 1:</label>
<input id ="checkbox_option1" name="checkbox1" type="checkbox" checked>
<label for="checkbox_option2">Checkbox 2:</label>
<input id ="checkbox_option2" name="checkbox2" type="checkbox">
<label for="checkbox_option3">Checkbox 3:</label>
<input id ="checkbox_option3" name="checkbox3" type="checkbox">
</p> </fieldset>
<fieldset>
<legend>TextArea Element</legend>
<p>
<label for="textarea1">Textarea:</label><br>
<textarea id="textarea1" rows="5" cols="50" placeholder="Enter Text here"></textarea>
</p>
</fieldset>
<p><input type="submit"> <input type="reset"></p>
</form>
<hr>
<h1>Student Information Form</h1>
<form>
<p>
<label for="input_name">Full Name:</label>
<input id ="input_name" type="text" placeholder="Name here">
</p>
<p>
<label for="input_age">Age:</label>
<input id ="input_age" type="number" placeholder="Your Age"> </p>
<p>
<label for="input_hobbies">Email ID:</label>
<input id ="input_hobbies" type="email" placeholder="Email ID">
</p>
<p>
<label for="input_mobile">Mobile No.:</label>
<input id ="input_mobile" type="tel" placeholder="Contact Number">
</p>
<p>
<label for="select_class">Applying for</label>
<select id="select_class">
<optgroup label="Primary">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option> </optgroup>
<optgroup label="Secondary">
<option>8</option>
<option>9</option>
<option>10</option>
</optgroup>
</select>
</p>
<p>
<h3>Gender</h3>
<label for="radio_male">Male:</label>
<input id ="radio_male" name="gender" type="radio" checked>
<label for="radio_female">Female:</label>
<input id ="radio_female" name="gender" type="radio">
</p>
<p>
<h3>Do you need these special services:</h3>
<label for="checkbox_bus">School Bus:</label>
<input id ="checkbox_bus" name="checkbox1" type="checkbox">
<label for="checkbox_lunch">School Lunch:</label> <input id ="checkbox_lunch"
name="checkbox2" type="checkbox">
<label for="checkbox_facility">Hostel Facility:</label>
<input id ="checkbox_facility" name="checkbox3" type="checkbox">
</p>
<p>
<label for="textarea_comments">Have any Comments?</label><br>
<textarea id="textarea_comments" rows="5" cols="50" placeholder="Your comments here">
</textarea>
</p>
<p><input type="submit" value="Send"> <input type="reset" value="Clear"></p>
</form>
</body>
</html>
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create a perfect contact form using fullname, email, and textarea.
Live Preview

8.7 – Other Form Elements

Usage of Other Form Elements


There are many other different form elements available for various purpose.
Example: Color, Progress Bar and Date Input.
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description"
content="Page Description">
<title>Form Elements</title>
</head>
<body>
<h1>Form Basic Elements</h1>
<form>
<p>
<label for="date_element1">Date input</label>
<input type="date" id="date_element1" value="2018-01-01">
</p>
<p>
<label for="color_element2">Color input</label>
<input type="color" id="color_element2" value="#ffffff">
</p>
<p>
<label for="range_element3">Range input</label>
<input type="range" id="range_element3" value="10">
</p>
</form>
</body> </html> Live Preview

8.8 – Action GET from Form

Usage of Action GET


Method are attributes of <form> tag and indicates how the data should go when the form is submitted.
Action is used to point to the page or script on the server where the user data is sent.
Action Methods are of two types:
• GET
• POST
GET means the data should be sent via the URL parameters.
POST means the data should be hidden and not visible in the URL parameters.
You can send high volume data via POST and simple data can be sent via the GET methods.
In this example, we are using GET method so observe the URL which will have the form parameters
with name=value format.
TAG: <form>, method=”GET”, method=”POST”, action=URL
ELEMENT:
<form action=”page.html” method=”get”> <input type=”text” id=”input_name” >
<input type=”submit”>
<input type=”reset”>
</form>
• When the submit button is clicked the form will pack the data into a long string and then send it to
the page that was mentioned in the action.
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Form Elements</title>
</head>
<body>
<h1>Form Basic Elements</h1>
<form action="index.html" method="get">
<h1>Student Registration Form</h1>
<p> <label for="input_name">Full Name:</label>
<input id ="input_name" type="text" name="name" placeholder="Name here">
</p>
<p>
<label for="input_age">Age:</label>
<input id ="input_age" type="number" name="age" placeholder="Your Age">
</p>
<p>
<label for="input_hobbies">Email ID:</label>
<input id ="input_hobbies" type="email" name="email" placeholder="Email ID">
</p>
<p><input type="submit" value="Send"> <input type="reset" value="Clear"></p>
</form>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Submit your page request to https://www.freelancer.com with GET
method.
Observe the URL: https://wpfreelancer.com/name=Srini&age=1&email=test%40test.com

Live Preview

8.9 – Action POST from Form

Usage of Action POST


POST Method is used to send huge size data to the server when the user submits the form.
This is the perfect case when user attach a file and file needs to be uploaded in the server.

POST means the data should be hidden and not visible in the URL parameters. In this example, we are
using POST method and the post data can only be observed from the browser inspect window

TAG: <form>, method=”GET”, method=”POST”, action=URL


ELEMENT:
<form action=”page.html” method=”post”>
<input type=”text” id=”input_name” >
<input type=”submit”>
<input type=”reset”>
</form>
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Form Elements</title>
</head>
<body>
<h1>Form Basic Elements</h1> <form action="index.html" method="get">
<h1>Student Registration Form</h1>
<p>
<label for="input_name">Full Name:</label>
<input id ="input_name" type="text" name="name" placeholder="Name here">
</p>
<p>
<label for="input_age">Age:</label>
<input id ="input_age" type="number" name="age" placeholder="Your Age">
</p>
<p>
<label for="input_hobbies">Email ID:</label>
<input id ="input_hobbies" type="email" name="email" placeholder="Email ID">
</p>
<p><input type="submit" value="Send"> <input type="reset" value="Clear"></p>
</form>
</body> </html> Live Preview
9. META TAGS

9 META TAGS

Purpose of Meta Tag


Metadata means data about the data (information).
<meta> tag is the most important tag on your page. This tag describes about your page to the machines
that are accessing your page.
When search engines, machines and browsers visit your page they learn more about your page with
the <meta> tags.
All the information about the page is described here. It is like a summary of your page that you want
to share with the search engines.
Your page keywords are defined in the <meta> tag which is used by search engines to learn about your
page.
You can do the following things with <meta> tag:

• Meta with SEO tags


• Meta with View Port
• Meta without View Port
• Page Auto Refresh
• Page Auto Redirect
<meta> tags are written under the <head> tag.
<meta> tags are not displayed on the browser because they are used to understand about your page.
Also notice that <meta> tag does not have any closing tags.

9.1 – Meta with SEO Tags

Usage of Meta with SEO Tags


These <meta> tags will improve the SEO for the page as it describes your page in such way that
search engine understand and learn about your page.
<meta> tags are one of the most important tag that will help to boost your page SEO.
Two most important things you define in the <meta> tags are keywords and description.
keywords will help to tell search engine to show your page when these keywords are searched in the
search engine.
description is the small description about your page that search engine will use.
robots attribute helps to communicate with the search engine bots. You can ask robots to ignore the
page to index and follow further on this page.
TAG: <meta>
ELEMENT:
<meta name=”robots” content=”index, follow”>
<meta name=”Description” CONTENT=”Author: A.N. Author, Illustrator: P. Picture, Category:
Books, Price: £9.24, Length: 784 pages”>
<meta name=”keywords” content=”html5, learning, wpbootcamp, web”>
<meta> tags are not displayed on the browser so you won’t see anything on the page. Sample Example
<!DOCTYPE html>
<html>
<head>
<meta name="robots" content="index,follow">
<meta name="Description" CONTENT="Author: A.N. Author, Illustrator: P. Picture, Category:
Books, Price: £9.24, Length: 784 pages">
<meta name="keywords" content="html5, learning, techiesbootcamp, web">
<title>META tags - Search Engine Optimization</title>
</head>
<body>
<!-
Meta tags that Google understands
https://support.google.com/webmasters/answer/79812?hl=en
-->
<h1>Invisible Tags</h1>
</body>
</html> Live Preview

9.2 – Meta tags with View Port

Usage of Meta with View Port


View ports are used to tell browsers how to scale (zoom) the page on the browser.
Things like:
• Width and Height
• Scaling (Zoom)
TAG: <meta>
ELEMENT:
<meta charset=”utf8″>
<meta name=”viewport” content=”width=device-width, initialscale=1.0″>

charset=”utf8″ tells the browser that HTML content is written in that character set. We have different
character set for different languages. Like we have SHIFTJIS to represent the Japanese character.

How to see the ViewPort Settings:


Press CTRL + SHIFT + I button to bring the inspect window and click on the “Toggle Device
Toolbar” -> Change the Layout to Responsive – 400 x 300 size.
Sample Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="index,follow">
<meta name="Description" CONTENT="Author: A.N. Author, Illustrator: P. Picture, Category:
Books, Price: £9.24, Length: 784 pages">
<meta name="keywords" content="html5, learning, wpbootcamp, web">
<title>With Viewport Tag</title>
</head>
<body>
<h1>With Viewport</h1>
<img src ="dog1.jpg" alt="German Shepherd">

<p>The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of


medium to large-sized working dog that originated in Germany. The breed's officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland.[5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep. </p>

</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Change the Viewport initial-scale=5.0 and observe the output in
the inspect window.
Live Preview

9.3 – Meta tags without View Port

Usage of Meta without View Port


If you disable the viewport then the page is not scaled to match the device size.
How to see the ViewPort Settings:
Press CTRL + SHIFT + I button to bring the inspect window and click on the “Toggle Device
Toolbar” -> Change the Layout to Responsive – 400 x 300 size.
Live Preview

9.5 – Page Auto Redirect

Usage of Page Auto Redirect


With the <meta> tag you can tell browser to redirect the page to another page after n number of
seconds.
This is very much useful when you want to show an ads for 5 seconds and auto redirect to the home
page.

You will find site like forbes.com does it by showing an Quote for the day + ads for 5 seconds and
then route to the main page.
TAG: <meta>
ELEMENT:
<meta http-equiv=”refresh” content=”10; url=https://wpfreelancer.com/”>
url indicate which site the page should redirect to
Sample Example:
To see the page redirect go to Inspect mode (CTRL + SHIFT + I) -> Click on Network and observe the
refresh.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="index,follow">
<meta name="description" CONTENT="Author: A.N. Author, Illustrator: P. Picture, Category:
Books, Price: £9.24, Length: 784 pages">
<meta name="keywords" content="html5, learning, wpbootcamp, web">
<title>Auto Redirect to WPFreelancer.com</title> <meta http-equiv="refresh" content="10;
url=https://wpfreelancer.com/">
</head> <body>
<h1>Page redirect to WPFreelancer.com after 10 Sec...</h1>
<img src ="dog1.jpg" alt="German Shepherd">

<p>The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed of


medium to large-sized working dog that originated in Germany. The breed's officially recognized
name is German Shepherd Dog in the English language (sometimes abbreviated as GSD). The breed
was once known as the Alsatian in Britain and Ireland.[5] The German Shepherd is a relatively new
breed of dog, with their origin dating to 1899. As part of the Herding Group, German Shepherds are
working dogs developed originally for herding sheep. </p>
</body> </html>

Live Preview

10. LAYOUTS
10 LAYOUTS

Layout of Page
In this section, you will learn basics HTML elements that are used to make a HTML page. This is a
pseudo code that you can apply for all the page as a structure.

Even though the layout of the page differs from site to site but the basics tags that makes up the layout
does not differ.
Layout of the page are made of:

1. Header – <header></header>
2. Navigation – <nav></nav>
3. Side Bars – <aside></aside>
4. Content
5. Sections – <section></section>
6. Articles – <article></article>
7. Footer – <footer></footer>

HTML has the tags to represent each of the item and you can use them to draw a basic structure of the
page.
10.1 – Layout 1

Simple HTML Layout


This simple HTML page layout will include all the tags that is used to create a simple layout.
HTML page layout is divided into the following sections.
TAG: <header>, <nav>, <aside>, <section>, <article> and <footer>
ELEMENT:
<body>
<header>Heading</header>
<nav>Navigation</nav>
<aside>Navigation</aside>
<section>
<article>Content</article>
</section>
<footer>Footer</footer>
Sample Example:
<!DOCTYPE html>
<html>
<head>
<title>Sample HTML5 Layout</title>
</head>
<body>
<header>
<h1>Page Layout 1</h1>
</header>
<hr>
<section> <article>
<header><h1><u>Article 1</u></h1></header>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has
been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.</p>

<p>#End of Article 1</p>


</article>
<article>
<header><h1><u>Article 2</u></h1></header>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has
been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.</p>
<p>#End of Article 2</p>
</article>
</section>
<footer>
<hr>
Copyright (C) 2018. WPbootcamp.com
</footer>
</body> </html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create an About Page and Contact Page and link the pages from
the home page.

Live Preview

11. ADDITIONAL TAGS


11 ADDITIONAL TAGS

Additional Tags
This section will list out all the additional tags that can most commonly used in HTML.
The tags are:
• <div> (Division)
• <span> Tag
White Spaces, Special Characters and Case Sensitive
<div> tags are used as a container to group the elements together and apply a simple formatting on it.
It is also used to divide the tags into small groups.
HTML tags and attributes are incase-sensitive which means you can write it in lowercase or
uppercase.

You can also add white spaces and remove white spaces which does not affect how the content is
displayed on the browser. As white spaces are ignored by the browser.

There are some special characters that starts with &#xxx; format. This can be used to show a symbol
or simple icon like ©.

11.1 – DIV HTML Tag

Usage of DIV HTML Tag


<div> tags are called as Division Tags they help to divide the tags into groups and apply special
formatting on them.
• <div> acts as container to wrap the elements together.
Difference between DIV and P:
• <div> tags are container tags to hold group of elements
<p> tags are used to tell browser that it is a paragraph. <p> tags is used to write paragrahs
It is the semantic difference between the two:
1. <div> tag means a block of container 2. <p> tag means a paragraph of content.
<p> tag is wrapped inside the <div> tag as <div> is a container to group elements together.
<div>
<p>something</p>
</div>
TAG: <div>
ELEMENT:
<div>
<h1>Heading</h1>
<p>something</p>
</div>
Sample Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML5 DIV Tag</title>
</head>
<body>
<header>
<h1>DIV Tag Example</h1>
</header>
<hr>
<div>
<header><h1><u>Article 1</u></h1></header>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has
been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.</p>

<p>#End of Article 1</p>


</div>
<div>

<header><h1><u>Article 2</u></h1></header> <p>Lorem Ipsum is simply dummy text of the


printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since
the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
book.</p>

<p>#End of Article 2</p>


</div>
<footer>
<hr>
Copyright (C) 2018. WPBootcamp.com
</footer>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Write 3 DIV tags and 3 DIV tags and inside the DIV tags write <p>
tags. Observe the spacing. Live
Preview

11.2 – SPAN HTML Tag

Usage of SPAN HTML Tag


<span> tags are like Division Tags they help to group the elements
<span> acts as container to wrap the elements together.
Difference between SPAN and DIV
<div> tags are block line which means it adds a new line for each div closing tag.
<span> tags are in-line which means it does not add the new line and put all the text inline and in same
line.
TAG: <span>
ELEMENT:
<span>
<h1>Heading</h1>
<p>something</p>
</span>
Sample Example
<!DOCTYPE html>
<html>
<head>
<title>HTML5 SPAN Tag</title>
</head>
<body>
<header>
<h1>SPAN Tag Example</h1>
</header>
<hr>
<span>
1) This is a text with span.
</span>
<span>
2) This is a text with span.
</span>
<hr>
<div>
1) This is a text with div. </div>
<div>
2) This is a text with div.
</div>
<footer>
<hr>
Copyright (C) 2018. WPBootcamp.com
</footer>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Write one <span> and inside it write one <div> then some text. Repeat it for 2 times.
11.3 – White Space, Special Characters & Case Sensitive

Usage of White Spaces


White spaces symbols are used to add additional white space in the running text.
These small symbols can be included anywhere in the HTML page and it will be converted by the
browser.
These are called as ENTITIES not TAG.
White spaces like ‘ ‘this are ignored by the browser if you want to add white space then you need to
use entities.
HTML tags are in-case sensitive which means <H1> and <h1> are both same.
It is recommend to write HTML tags and entities in lowercase.
ENTITY:
• &nbsp; – Single Space
• &ensp; – Two Space
• &emsp; – Four Space

&copy; – ©
ELEMENT:
• <p>Paragraph &nbsp; Text with One Space</p>
• <p>Paragraph &ensp; Text with Two Spaces</p>
• <p>Paragraph &emsp; Text with Four Spaces</p>
• <p>Copyright: &copy; – ©</p>

Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>White Space and Escape Character</title>
</head> <body>
<h1>White Spaces</h1>
<p>Paragraph Text with One Space</p>
<p>Paragraph Text with Two Space</p>
<p>Paragraph Text with Three Space</p>
<p>Paragraph Text</p>
<p>Paragraph Text</p>
<p>Paragraph Text</p>
<p>Paragraph Text</p>
<p>Paragraph Text with Two Spaces</p>
<p>Paragraph Text with Four Spaces</p>
<p>Paragraph Text with Four Spaces</p>
<hr>
<h1>Character Entities - Special Characters</h1>
<!-- List here: https://brajeshwar.github.io/entities/ -->
<p>Dollar: $</p>
<p>Commat: @</p>
<p>Copyright: ©</p>
<p>PI: Π</p>
<p>Sum: ∑</p> </body>
</html>
Live Preview
Exercise 1
Exercise 1: Make the page looks like below image by using white spaces.

Live Preview

12. PROJECTS
12 HTML Projects

12 HTML Projects

List of HTML based Projects:


All these projects are built only using HTML without any formatting or styling to the page.
In the section 2, you will learn how to add colors, change the font size, spacing and everything with
the Cascaded Style Sheet. (CSS)

12.1 – Personal Profile Page

Personal Profile Page:


Build a personal profile page with only HTML and use your profile pic along with your personal,
education, skills and work experience details.

Live Preview
About this Book

About this Book

CSS is a cascading style sheet that allows web developers to design the
HTML Page that can be viewed on Web Browser. CSS are styling rules
which is applied on the web page. This book will help you understand the
basics of CSS Syntax and how to put it in practice to build Websites.

Audience

This tutorial has been designed to meet the requirements of all those readers
who are keen to learn the basics of CSS.

Prerequisites

This book assumes you have no prior knowledge on Programming


knowledge and assume you are at a beginner level.

How to use this Book

This book contains CSS Syntax Basics, Exercises and Examples which are
part of the PHP Bootcamp Program. This bootcamp has helped many
students to become PHP Full Stack Web Developer in Just 30 days.

>>>Check out more about this program here. ..


Copyright & Disclaimer

Copyright & Disclaimer

© Copyright 2019 by SrinivasIT.com.

All the content and graphics published in this e-book are the property of
SrinivasIT.com. The user of this e-book is prohibited to reuse, retain, copy,
distribute or republish any contents or a part of contents of this e-book in any
manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or
errors. SrinivasIT.com provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this
tutorial. If you discover any errors on our website or in this tutorial, please
notify us at contact@SrinivasIT.com .

Found Typos & Broken Link

If you found any typos and broken links in the course or book, then please
let me know using this email address.
contact@SrinivasIT.com

Support

You can reach me for technical discussions and other support related queries
from here.
support@SrinivasIT.com
Thanks for your support!

Free Courses
Learn HTML in 1 Hour
Learn CSS in 1 Hour
Learn JAVASCRIPT in 1 Hour
Table of Contents

About this Book .......................................................................................... 1


Audience...................................................................................................... 1
Prerequisites ............................................................................................... 1
How to use this Book ................................................................................. 1
Copyright & Disclaimer .............................................................................. 2
Found Typos & Broken Link ...................................................................... 2
Support ........................................................................................................ 2
1 CSS Basics ............................................................................................ 8
1.1 Introduction to CSS...................................................................... 8
1.2 Internal CSS ................................................................................13
1.3 CSS Comments...........................................................................17
1.4 External CSS ...............................................................................21
1.5 Inline CSS ....................................................................................26
1.6 Linking CSS .................................................................................29
1.7 Simple CSS Example ..................................................................34
2 CSS Selectors.........................................................................................39
2.1 Selectors & Declaration ................................................................39
2.2 Universal Selector..........................................................................45
2.3 Type Selector..................................................................................50
2.4 Class Selector .................................................................................56
2.5 Class Multiple Selector..................................................................62
2.6 ID Selector ......................................................................................67
2.7 ID Multiple Selector .......................................................................73
2.8 Attribute Selector ..........................................................................79
2.9 Child Selector .................................................................................84
2.10 Descendant Selector ...................................................................88
2.11 Adjacent Sibling Selector ............................................................94
2.12 General Sibling Selector ...........................................................100
2.13 Pseudo Classes ..........................................................................106
2.14 Pseudo Elements.......................................................................111
3 CSS Rules .............................................................................................116
3.1 Precedence...................................................................................116
3.2 Inheritance ...................................................................................121
3.3 Last Rule Wins..............................................................................126
3.4 Important Rule Wins ...................................................................132
4 Colors and Text...................................................................................138
4.1 Colors ............................................................................................138
4.2 Text................................................................................................144
5 CSS Box................................................................................................150
5.1 Borders .........................................................................................150
5.2 Margin...........................................................................................155
5.3 Padding.........................................................................................162
5.4 Height and Width.........................................................................168
6 Floating Columns................................................................................174
6.1 Floating Box..................................................................................174
6.2 Floating Images............................................................................178
6.3 Horizontal Menu..........................................................................184
6.4 Vertical Menu ...............................................................................187
7 Positioning Elements .........................................................................192
7.1 Position Fixed...............................................................................192
7.2 Position Absolute.........................................................................198
7.3 Position Relative ..........................................................................203
8 Display Inline and Block.....................................................................209
8.1 Display Inline & Block Example 1 ..............................................209
8.2 Display Inline & Block Example 2 ..............................................213
9 Layouts ................................................................................................218
9.1 Layout 1 ........................................................................................218
9.2 Layout 2 ........................................................................................221
9.3 Layout 3 ........................................................................................225
9.4 Layout 4 ........................................................................................229

1. CSS Basics

1 CSS Basics
1.1 Introduction to CSS

What is CSS? CSS stands for Cascading Style Sheet. It is used to describe
how the content should be displayed on the browser, print or screen.

With CSS Language, you can control the layout of the page, color of the
text, size of the font, spacing between the text, width and height of the
elements and complete presentation of the web page.
In Short, CSS handles the look and feel of the web page. HTML is used to
describe the content and CSS is used to display the content in a
presentable way.
Usage of CSS CSS are written in a file with extension .css and it is linked
into the HTML page.
Define the style once and then use it any where on your site. Load the CSS
once per page and it will manage the entire page layout and presentation.

Helps to change the page layout based on the screen the site is viewed on
like Mobile, Tablet or Computer Screen.
CSS helps to separate the presentation work from the HTML page and the
developer can focus on building the content and displayed it separately.

Global Standards also suggest to use CSS and do not use any HTML
attributes to style the tag.
Reuse the same CSS for multiple WordPress site to have the same look and
feel.
Who are W3 Group?
The World Wide Web Consortium, or W3C is a group that provides
guidelines on how things should work in Internet.
They don’t provide implementation libraries or code but they just provide
guidelines and all the browser implement this guidelines. Visit W3.org
History of CSS
CSS was invented by Håkon Wium Lie on October 10, 1994 and maintained
through a group of people within the W3C called the CSS Working Group .

Visit CSS Working Group


Without CSS

Without CSS, HTML page will be displayed as per the browser default
formatting and coloring. Most of the time is plain black and white with some
browser defined font size.

With CSS
With CSS, you can add styles to the each elements of the HTML tag.
CSS can control every element and format it.
CSS Syntax
In this above CSS example, we are changing the h1 tag property to display it
in RED color and font-size to be 12 points.
CSS Language & Terms:
property represents the name of Selectors are the HTML tags that you want
to apply the style on.
Custom selectors are the selectors which name does not matches with the
HTML tag name.

Example : h1 is a selector and h1a is a custom selector .


the attribute you want to change.
value is the value of that property.
{ } is called as block .
{ property: value; } is called as Declaration .
Collection of Declaration is called as Declaration Block .
You can separate the each declaration with ; inside the block.

Declaration property is predefined like color, font-size it cannot be custom


name.
CSS Summary

CSS is a collection of selectors which has many declaration blocks to


modify the HTML tags and you can define custom selectors which can be
applied on the HTML tags.

1.2 Internal CSS

Usage of Internal CSS Cascaded Style Sheet (CSS) can be written in many
different places in HTML page.
One of the method of defining the CSS is inside the same HTML page.
This type of CSS includes is restricted to page level only means you cannot
reuse this code in some other pages.
Benefit of using this internal css is when you want specific changes to apply
for that page level only.
QUICK SYNTAX:
<head>
<style type=”text/css”>
h1 { color: red; }
</style>
</head>
<style> tag is used to write the CSS inside this tag.
This tag <style> is defined inside the <head>

Data written inside the <style> tag is not displayed in the browser but it is
used as instruction to the browser to do something on the page.

Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>How to write CSS within the
Page</title>
<!-- CSS Starting --> <style type="text/css">
h1 { color: red; }
</style> <!-- CSS Ending -->
</head>

<body> <h1>Heading</h1> <p>Paragraph Text</p> <ul>

<li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul>

</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Color the Paragraph in Blue Color and list in Green Color.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Change the font size of h1, p and li tags.

h1 – { font-size: 12 px; }
p – { font-size: 24 px; }
li – { font-size: 48 px; }
Follow the correct syntax to add the internal CSS on the HTML page.

Live Preview

1.3 CSS Comments

Usage of Comments
You can use the special notation to comment the code inside the CSS.
HTML comments and CSS comments are not same. Don’t get confused with
the comments in CSS vs comments in HTML.

Comments in CSS are multiple line comments.


/* is used to indicate the comments are starting.
*/ is used to indicate the comments are ended.
Anything between /* and */ will not be executed by the browser.

SYNTAX : <head>
<style type=”text/css”>
/* Starting of the comment h1 { color: red; }
Ending of the Comments */

</style>
</head>
Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>How to Write Comments in
CSS</title>
<!-- HTML Comments --> <style type="text/css">

/* This is a multi-line comment in CSS. This is different than the HTML comments.
Anything inside this block will be ignored.

h1 { color: red; } */ </style> <!-- HTML Comments -->


</head>

<body> <h1>Heading</h1> <p>Paragraph Text</p> <ul>

<li>Item 1</li> <li>Item 2</li> <li>Item 3</li>

</ul> </body> </html>

Live
Preview

Exercise 1 Download the Exercise 1

Exercise 1: Make the multi-line comments of CSS looks like single line.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Comment the entire <style> block with HTML comments.
Live
Preview

1.4 External CSS

Usage of External CSS


Cascaded Style Sheet (CSS) can be written in many different places in
HTML page.
One of the method of defining the CSS is externally which means you can
write CSS inside a file and import it into the HTML page. External CSS
means the CSS is written externally into another file which is later linked in
the page.
This type of external CSS is very powerful and helpful technique which is
commonly used in every website development.

Benefit of using this external css is that you have one CSS file that is
included in all the website pages.
By just changing at one place in the CSS it will impact the overall site
design look and feel.
This is one of the best practice to separate the design with the html tags and
store them in a external file and include it in all the HTML pages.

External CSS filename should be .css and it is included in the <head>


section with <link> tag.

SYNTAX :
<head>

<!– Make sure styles.css file exists in the same folder –> <link
rel=”stylesheet” type=”text/css” href=”styles.css ”
media=”screen” />

</head>

<link> tag is used to link the resource to the HTML page. The attribute of
link tag will let the browser knows what type of resource it is.

rel attribute is used to tell browser what kind of resource it is. rel =
“stylesheet” means it is a file with CSS inside it.
type attribute tells the type of the content in the file. In this case, it is text/css
href attribute is similar to <a> tag href to map the location of the file in the
server with the path and filename.
media attribute tells the browser to embed the file for screen purpose.
Sample Example
Download the Example

There are two files: index.html styles.css

styles.css file is linked inside the index.html file with <link> tag in the
<head> section.
FileName: index.html
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>How to Include CSS from
external file.</title>
<!-- Make sure styles.css file exists in the same folder --> <link rel="stylesheet"
type="text/css" href="styles.css" media="screen" />
</head>
<body>
< body > <h1>Heading</h1> <p>Paragraph Text</p>

</body> *{ border-style: solid; border-color: red;

</html>
FileName: styles.css
}

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Create style1.css and style2.css and link them in the HTML
page.

Filename: style1.css
h1 { color: red; }
Filename: style2.css
h1 { color: blue; }

Live Preview Exercise 2 Download the Exercise 2

Exercise 2: Change the font size of h1, p and li tags in style.css and embed
the CSS file in the HTML page.
Write comments in the style.css
h1 – { font-size: 12 px; }
p – { font-size: 24 px; }
li – { font-size: 48 px; }

Follow the correct syntax to add the external CSS on the HTML page. Live
Preview

1.5 Inline CSS

Usage of Inline CSS Inline CSS is defined inside the tag itself like an
attribute.

Inline CSS overrides all the styles defined in internal CSS and External CSS.

This is defined in the HTML tag as a attribute.


SYNTAX :
<h1 style =”color: red;”>This heading should be red in color.</h1> <style>
tag is used to write the CSS as a attribute in the HTML tag. The syntax for
CSS is similar in inline, external and internal CSS.

Sample Example Download the Example


<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>How to Apply CSS from the
HTML tag - Inline CSS</title> </head>
<body>
<!-- style attribute is used to apply the CSS style to any html tag. -->
<h1 style="color: red;">This heading should be red in color.</h1>
<p>Paragraph Text</p> <h1>This heading is without any style</h1> </body> </html>

This heading should be red in color. Paragraph Text This heading is


without any style. Live Preview Exercise 1 Download the Exercise 1

Exercise 1: Write Inline CSS and change the h1 tags color as red, paragraph
as blue and list as green.
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Change the font size of h1, p and li tags as inline CSS along
with the color.

h1 – { font-size: 12 px; }
p – { font-size: 24 px; }
li – { font-size: 48 px; }
Live Preview

1.6 Linking CSS

Usage of Linking CSS


CSS files can be linked together and embed into one another.

Linking one CSS into another CSS file can help to split the functionality into
smaller units.
You can create the multiple CSS file and import the one css file into another
css file.

SYNTAX :
<head>

<link rel=”stylesheet” type=”text/css” href=”mynewstyles.css”


media=”screen” />

</head>
Sample Example
Download the Example
There are three files:

• index.html
• mynewstyles.css
• anotherstylesfile.css

mynewstyles.css has a import statement to import the “anotherstylesfile.css


“.
FileName: index.html
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Embeded CSS from One file
into Another CSS File.</title>
<!-- Make sure mynewstyles.css file exists in the same folder --> <link rel="stylesheet"
type="text/css" href="mynewstyles.css" media="screen" />
</head>
<body>

< body > <h1>Heading</h1> <p>Paragraph Text</p>

</body> </html>
FileName: mynewstyles.css
/* @import notation is used to import another css file Don't forget the semicolor ; at
the end of the line.

*/
@import "anotherstylesfile.css";
FileName: anotherstylesfile.css
/* This file is imported in the mynewstyles.css file */

*{ border-style: solid; border-color: red;

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create style1.css , style2.css, style3.css and link like this
index.html -> style1.css -> style2.css -> style3.css
Live Preview Exercise 2 Download the Exercise 2

Exercise 2: Change font of h1 in style1.css and p in style2.css and li in


style3.css

h1 – { font-size: 12 px; }
p – { font-size: 24 px; }
li – { font-size: 48 px; }
Follow the correct syntax to add the external CSS on the HTML page.

Live Preview

1.7 Simple CSS Example

Simple Example of CSS In this simple example, you will combine all the
ways of using CSS

• Internal CSS
• External CSS
• Inline CSS
• Linking CSS

Sample Example Download the Example There are three files:


index.html mynewstyles.css anotherstylesfile.css

mynewstyles.css has a import statement to import the “anotherstylesfile.css


“.
FileName: index.html
<!DOCTYPE html> <html>

<head> <meta charset="utf-8"> <!-- Make sure mynewstyles.css file exists in the same
folder -->

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>CSS Simple Example</title>
<link rel="stylesheet" type="text/css" href="mynewstyles.css" media="screen" />

<style type="text/css"> p { font-size: 20px; font-weight: bold; font-style: italic;


text-align: center;

} </style> </head>
<body> <h1 style="text-align: center; color: red;">This is Inline Style with Red Heading
and Center.</h1>
<p>This is a Paragraph Text with 20px Font Size, Bold, Italics and Aligned Center.</p>
<p>Power of CSS!!!</p>
</body>
</html>
FileName: mynewstyles.css
/* @import notation is used to import another css file Don't forget the semicolor ; at
the end of the line.

*/
@import "anotherstylesfile.css";
FileName: anotherstylesfile.css
/* This file is imported in the mynewstyles.css file */

*{ border-style: solid; border-color: red;


}

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Copy all the style in inline css in a single HTML file
without any external CSS and no <script> tag
Exercise 2 Download the Exercise 2

Exercise 2: Copy all the CSS in styles.css file and link it from the
index.html
2. CSS Selectors
2 CSS Selectors
2.1 Selectors & Declaration

Usage of Selectors and Declaration A CSS rule made up of two parts:


Selector Declaration

Selector is used to indicate which element this rule should be applied to.
You can even write multiple elements by separating them by “, ”

h1, p, li elements will be red in color with this one css rule.
Declaration indicates what is the rule to be applied on that element. The rule
is indicated with property: value .

Multiple Declaration are separated with “ ; ”


SYNTAX :

<head>
<style type=”text/css”>
h1 { color: red; }
p,
li { color: blue; font-size: 12px }
</style>
</head>
EXAMPLE:

/*
selector
{
property1: value1; => Declaration
property2: value2; => Declaration
}
*/

Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Definition of Selector and
Declaration in CSS.</title>
<style type="text/css">

/* selector {

property1: value1; => Declaration property2: value2; => Declaration }


*/

/* p is the selector and color: red is declaration */ /* Apply this rule to <p> tag and
assign this propery to it */ p {

color: red; }
</style>
</head>

<body> <h1>Heading</h1>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting,
remaining essentially unchanged. It was popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Write the CSS selector and Declaration into another css and link
them in the index.html.
Apply this CSS Rule:
Make all the text on the body blue in color with one CSS rule.

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Add two declaration for each selector and change the CSS to see
the following output.
/* selector { property: value; property: value; } */

Live Preview

2.2 Universal Selector

Usage of Universal Selector


Universal selector is the rule that you want to apply for all the elements of
the page.

Wild Character ‘ * ‘ is used to represent the universal selector.


Universal selector are applied on all the elements of the page. SYNTAX:

<head>
<style type=”text/css”>

*
{
border-style: solid;
border-color: red;
}

</style>
</head>

border-style property is used to set the style of the border border-color is


used to indicate the color of the border.

If you observe properly, every element on the HTML page has a magical
box around it using which you can control that element. Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Universal Selector
Notation</title>
<style type="text/css">
/* selector {

property1: value1; => Declaration property2: value2; => Declaration }


*/

/* '*' is the universal selector which is applied to all tags. */

/* Make all tags text color as red */ * {

border-style: solid; border-color: red; }


</style>

</head> <body> <h1>Universal Selector - *</h1>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting,
remaining essentially unchanged. It was popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</body> </html>

Live Preview

Exercise 1 Download the Exercise 1 Exercise 1: Write two CSS rule Using
Universal Selector change the color to red Change the h1 tag color to blue.
Observe the result
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Do the following steps:

Put the universal selector into another css file and change the color to red
change the h1 tag to blue using inline css.
Guess the output.
Live Preview

2.3 Type Selector

Usage of Type Selector


Type Selector are defined with HTML tags only.

When you find any selector that has rule applied on the HTML tags then it is
called as Type Selector.

Type selectors only apply to HTML tags. SYNTAX:

<head>
<style type=”text/css”>

h1
{
border-style: solid;
border-color: red;
}

</style>
</head>
Sample Example
Download the Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport"
content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description">
<title>Type Selector Notation</title>
<style type="text/css">

/* selector {

property1: value1; => Declaration property2: value2; => Declaration }


*/

/* Specify the HTML TAG as the Selector. */ /* Apply the rule to specified tag as
selector. */
p

{ color: red;
}
h1
{ color: blue;
}

/* This rule applies to <p> and <h1> tag */ p, h1 {

font-style: italic; }
</style>

</head> <body> <h1>Type Selector - HTML TAG</h1>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting,
remaining essentially unchanged. It was popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Write the CSS rule with Type Selectors Make the font size of h6
biggest and h1 smallest. Make all the headings tags blue in color.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Do the following steps:
Make h1 and h2 same size and color.
h3 and h4 same size and color h5 and h6 same size and color. All the
headings should be in Italics
Live
Preview

2.4 Class Selector

Usage of Class Selector Class Selector is custom selector that you can
create in the CSS rules and apply it to any HTML tag with class attribute.
Class selector names are custom so you should NOT use the
predefined HTML tag names.
Custom Selector names are class selectors that can be applied to any HTML
tag.
Class selector can be defined to any specific HTML tags and applied to any
specify the tags.
You define the class selector with “.” in-front of it.

If the selector starts with “.” and it name is not HTML tag then it is called as
Class Selector.
SYNTAX:
<head>
<style type=”text/css”>
.redcolor { color: red; }

</style>
</head>
<body>
<h1 class=”redcolor” >This is red color heading</h1> </body>
Remove the “.” when the class selector is applied to the HTML tag attribute.

If you want to create class selector only specific to HTML tags then use this
notation.

.redcolor class selector will only works for h1 tag.


Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Class Selector
Notation</title>
<style type="text/css">

/* .selector {
property1: value1; => Declaration property2: value2; => Declaration }
*/

/* Specify the Custom name selector with '.' */ /* Use this style to any tag with class
attribute */
.color-red

{ color: red;
}
.color-blue
{ color: blue;
}
.align-center
{ text-align: center;
}

</style>
</head>
<body>
<!-- Multiple class separator are added with space --> <h1 class="color-red align-
center">Class Selector - HTML TAG</h1>

<p class="color-blue">Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type specimen
book. It has survived not only five centuries, but also the leap into electronic
typesetting, remaining essentially unchanged. It was popularised in the 1960s with the
release of Letraset sheets containing Lorem Ipsum passages, and more recently with
desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write the CSS rule with Class Selector

Create one rule called as “.headings” and make the color as blue, align
center and italics.
Create one more rule with same name “.headings” and change the color to
red.
See how the overwrite function will work.

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Create a class selector only for h1 tag. Even if this class selector
is applied to other tags like p it should not work.

Example:
h1.redcolor { color: red; }
This class is only applicable to h1 tag.

Live Preview

2.5 Class Multiple Selector


Usage of Class Multiple Selector You can apply the selector to the parent
HTML tag and all the child elements will inherit the property from the
parent tags properties. SYNTAX:
<head>
<style type=”text/css”>
div.redcolor { color: red; }

</style>
</head>
<body>
<div class=”redcolor”> <p>This is red color paragraph</p> </div> </body>

Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Multiple Class Selector
Notation</title>

<style type="text/css"> /* selector.class-selector {

property1: value1; => Declaration property2: value2; => Declaration }


*/

div.color-red

{ color: red;
}

/* id and class are siblings */ #color-red.align-center {

color: red; text-align: center; }

/* id is parent and class is child */ #color-blue .text-underline {

color: blue; text-decoration: underline; }


</style>
</head>
<body> <h1 class="color-red">Mutiple Class Selector - HTML TAG</h1>

<div class="color-red"> This is red color paragraph.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</div>
<!-- Specify id and class together - Siblings --> <h1 id="color-red" class="align-
center">Power of CSS!!!</h1>
<hr>
<!-- id is the parent of class --> <div id="color-blue"> <h1 class="text-underline">
Cascaded CSS with Class & ID!! </h1> </div>
</body> </html>

Live Preview

Exercise 1
Download the Exercise 1
Exercise 1: Write the CSS rule with Multiple Class Selector Create one rule
called as “.align-center” for p tag and h1 tag. Apply the rule to h1 tag only.
Write p tag inside the h1 tag.
See if the text in p align in center or not? Any Guess?
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create a class selector “align-center”
Apply the class to h1 tag and see if p tag inside get affected

Apply the class to p tag inside the h1 tag. Write some text inside the h1 tag.
Apply the class to div tag inside the h1 tag and write p tag inside the div tag.
Guess the output.
Live Preview

2.6 ID Selector
Usage of ID Selector
ID Selector is custom selector that you can create in the CSS rules and apply
it to any HTML tag with id attribute.
ID selector names are custom so you should NOT use the predefined HTML
tag names.
Custom Selector names can be ID selectors that can be applied to any
HTML tag.
You define the ID selector with “# ” in-front of it.

If the selector starts with “# ” and it name is not HTML tag then it is called
as ID Selector .
SYNTAX:
<head>
<style type=”text/css”>
#redcolor { color: red; }

</style>
</head>
<body>
<h1 id=”redcolor” >This is red color heading</h1>
</body>
Remove the “# ” when the class selector is applied to the HTML tag
attribute.
If you want to create ID selector only specific to HTML tags then use this
notation.

#redcolor class selector will only works for h1 tag.


Sample Example
Download the Example
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description">
<title>ID Selector Notation</title>
<style type="text/css">

/*
#selector {

property1: value1; => Declaration property2: value2; => Declaration }


*/

/* Specify the Custom name selector with '#' */ /* Use this style to any tag with id
attribute */
#color-red

{ color: red;
}
#color-blue
{ color: blue;
}
#align-center
{ text-align: center;
}

</style>
</head>
<body>
<!-- Cannot combine two ID together --> <h1 id="color-red align-center">ID Selector -
Any TAG</h1>

<p id="color-blue">Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type specimen
book. It has survived not only five centuries, but also the leap into electronic
typesetting, remaining essentially unchanged. It was popularised in the 1960s with the
release of Letraset sheets containing Lorem Ipsum passages, and more recently with
desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

<h1 id="align-center">Power of CSS!!!</h1> </body> </html>

Live Preview

Exercise 1 Download the Exercise 1 Exercise 1: Write the CSS rule with
ID Selector
Create one rule called as “#headings” and make the color as blue, align
center and italics.
Create one more rule with same name “#headings” and change the color to
red.
See how the overwrite function will work.

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Create a ID selector only for h1 tag. Even if this ID selector is


applied to other tags like p it should not work.

Example:
h1#redcolor { color: red; }
This id is only applicable to h1 tag.

Live Preview
2.7 ID Multiple Selector

Usage of ID Multiple Selector


You can apply the selector to the parent HTML tag and all the child elements
will inherit the property from the parent tags properties. SYNTAX:
<head>
<style type=”text/css”>
div#redcolor { color: red; }

</style>
</head>
<body>
<div id=”redcolor”> <p>This is red color paragraph</p> </div> </body>

Brother and Sister Sibling Relation:


#brother.sibling { color: red; }

If there is no space between the #id.class then both can be specified at the
same HTML tag attribute.
Parent and Child Relation:
#brother .sibling { color: red; }

If there is space between the #id .class then class should be specified under
the parent.
Sample Example Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Multiple Class Selector
Notation</title>
<style type="text/css">

/* selector.class-selector {

property1: value1; => Declaration property2: value2; => Declaration }


*/

div.color-red

{ color: red;
}

/* id and class are siblings */ #color-red.align-center {

color: red; text-align: center; }

/* id is parent and class is child */ #color-blue .text-underline {

color: blue; text-decoration: underline; }


</style>
</head>
<body>
<h1 class="color-red">Mutiple Class Selector - HTML TAG</h1>

<div class="color-red"> This is red color paragraph.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</div>
<!-- Specify id and class together - Siblings --> <h1 id="color-red" class="align-
center">Power of CSS!!!</h1>
<hr>
<!-- id is the parent of class --> <div id="color-blue"> <h1 class="text-underline">
Cascaded CSS with Class & ID!! </h1> </div>
</body> </html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write the CSS rule with Multiple ID Selector
Create one rule called as “.align-center” for p tag and h1 tag. Apply the rule
to h1 tag only.
Write p tag inside the h1 tag.
See if the text in p align in center or not? Any Guess?
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create a id selector “align-center”
Apply the class to h1 tag and see if p tag inside get affected

Apply the class to p tag inside the h1 tag. Write some text inside the h1 tag.
Apply the class to div tag inside the h1 tag and write p tag inside the div tag.
Guess the output.
Live Preview

2.8 Attribute Selector


Usage of Attribute Selector

Attribute selector helps to apply the CSS rule when some specific condition
is met on the HTML attribute.
One example is when you want apply color red on all the <p> tag when it
has class attribute with any value.

SYNTAX:
<head>
<style type=”text/css”>

p[class]{
color: red;
}
</style>
</head>

<body>
<p class=”something”>This is RED Color Text</p>
</body>

p[class] this attribute selector tell the browser to apply the rule to the <p>
HTML Tag when it has the class attribute.
Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Attribute Selector
Notation</title>
<style type="text/css">

/* selector[class] {

property1: value1; => Declaration property2: value2; => Declaration }


*/

/* Affect the <p> tag that has class attribute */

p[class]{ color: red; font-weight: bold;

p[class=color-blue]{ color: blue;


}
/*
p[class~=color-blue] ===> Targets <p> tag which has many class name and one of it is
"color-blue"

p[attr^"c"] ====> Attribute value starts with "c" p[attr*"c"] ====> Attribute value has
the letter "c" p[attr$"c"] ====> Attribute value ends with the letter "c"

*/
</style>
</head>

<body> <!-- CSS rule is applied here --> <hr> <!-- CSS rule is not applied here -->

<p class="something">Lorem Ipsum is simply dummy text of the printing and typesetting
industry. </p>
<p class="color-blue">Lorem Ipsum is simply dummy text of the printing and typesetting
industry. </p>
</body> </html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write the CSS rule with Attribute Selectors
Apply the color red to all <h1> tag that has id attribute.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Do the following steps:
Make h1 red when it has class and id both.

Live
Preview

2.9 Child Selector


Usage of Child Selector Child Selector are used to pin point the location of
the HTML tag in the nested HTML sections.
“>” greater than symbol is used to point the location of the HTML tag.

If you want to apply the rule to <a> anchor tag inside the <p> paragraph tag
then you can use the child selector to apply the style to only <a> tag inside
the <p> tag.

p>a { color: red; }


means apply the rule to <a> tag when it is inside the <p> tag. SYNTAX:

<head>
<style type=”text/css”>

p>a
{
color: red;
}

</style>
</head>
<body>
<p><a href=”#”>This is Red</a></p>
</body>

Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Child Selector
Notation</title>
<style type="text/css">

/* selector>selector {

property1: value1; => Declaration property2: value2; => Declaration }


*/

/* Direct child element of the parent element. */ /* Only <a> tag inside the <p> tags
are affected. */

div>a{ color: red; font-weight: bold;


}
</style>
</head>
<body> <h1>Child Selector - HTML TAG</h1>
<a href="#">Home Page</a>

<hr> <!-- CSS rule is applied here -->

<div><a href="#">Rule Applied here! Lorem Ipsum is simply dummy text</a> of the printing
and typesetting industry.</div>
<hr>
<!-- CSS rule is not applied here --> <div>

<p> CSS Rule not applied here. <a href="#">Lorem Ipsum is simply dummy text</a> of the
printing and typesetting industry.

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

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write the CSS rule with Child Selectors
Apply the color red rule to <a> tag when it is inside the <div> and <p>

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Do the following steps: Apply the CSS color red when <a> tag
is inside the <p> and it has the class and id attribute only.

Live Preview

2.10 Descendant Selector

Usage of Descendant Selector


Descendant Selector rule is used when you want to apply rule to for every
element under one parent element.
Selectors are separated with ‘ ‘ (space) to indicate they are parent and child
relation.

body a { color: red; }


means apply the rule to ALL <a> tag under the <body> tag.
SYNTAX:

<head>
<style type=”text/css”>
body a
{
color: red;
}

</style>
</head>
<body>
<p><a href=”#”>This is Red</a></p> </body>

Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Descendant Selector
Notation</title>
<style type="text/css">

/* selector selector {

property1: value1; => Declaration property2: value2; => Declaration }


*/ /* All child element of the parent element will be affected. */ /* All the <a> tag
inside the <body> tags are affected. */

body a { color: red; font-weight: bold;


}

</style>
</head>
<body>
<h1>Descendant Selector - HTML TAG</h1>
<a href="#">Home Page</a>
<!-- CSS rule is applied here --> <p><a href="#">Lorem Ipsum is simply dummy text</a> of
the printing and typesetting industry. </p>
<hr>
<!-- CSS rule is also applied here --> <p><div><a href="#">Lorem Ipsum is simply dummy
text</a></div> of the printing and typesetting industry. </p>
</body> </html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write the CSS rule with Descendant Selectors
First make the <a> tag as blue
Then make all the <a> tag as red inside the <body>
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Do the following steps:

Apply the CSS color red when <a> tag is inside the <p> with descendant and
also child selectors.
Observe which rule is applied.
Live Preview

2.11 Adjacent Sibling Selector

Usage of Adjacent Selector


Adjacent Sibling Selector rule is used when you want to apply rule to for the
first element which is one after the other.
Selectors are separated with ‘+’ (plus) sign to indicate the rule is applied one
after the other
h1 + a { color: red; }
means apply the rule to only the first adjacent sibling <a> tag after h1.

It is Adjacent (right after) and sibling and at the same level.


<h1>Test</h1>
<a href=”#”>Red1</a>
<a href=”#”>Red2</a>
<a> with Red1 is adjacent to <h1> and sibling as well.
<a> with Red2 is NOT adjacent to <h1> instead it is adjacent to <a> with
RED1.

SYNTAX:
<head>
<style type=”text/css”>

h1 + a
{
color: red;
}

</style>
</head>
<body>
<h1>Test</h1>
<a href=”#”>Red1</a>
<a href=”#”>Red2</a>
</body>

Sample Example
Download the Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport"
content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description">
<title>Adjacent Sibling Selector Notation</title>
<style type="text/css">

/* selector + selector {

property1: value1; => Declaration property2: value2; => Declaration }


*/

/* Adjacent Siblings not nested but one after the other. */ /* First <a> tag after the
<h1> tags are affected. Not Inside but after. */

h1 + a { color: red; font-weight: bold;


}

</style>
</head>
<body>
<h1>Adjacent Sibling Selector - HTML TAG</h1>

<a href="#">Home Page</a> <a href="#">Contact</a> <a href="#">About</a>


<!-- CSS rule is applied here --> <p><a href="#">Lorem Ipsum is simply dummy text</a> of
the printing and typesetting industry. </p>
<hr>
<!-- CSS rule is also applied here --> <div><a href="#">Lorem Ipsum is simply dummy
text</a> of the printing and typesetting industry.</div>
</body> </html>

Live Preview

Exercise 1 Download the Exercise 1 Exercise 1: Write the CSS rule with
Adjacent Selectors First make the <a> tag as blue Apply this rule only when
<a> is adjacent to another <a> tag
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Do the following steps:

Apply the CSS color red when <a> tag is inside the <p> with
descendant and also child selectors and also with Adjacent Siblings Selector.
Observe which rule is applied.
Live Preview

2.12 General Sibling Selector

Usage of General Adjacent Selector


General Adjacent Sibling Selector rule is used when you want to apply rule
to for every element which is one after the other. Selectors are separated
with ‘~’ (plus) sign to indicate the rule is applied one after the other.

h1 ~ a { color: red; }
means apply the rule to all the adjacent sibling <a> tag after h1.

It is Adjacent (right after) and sibling and at the same level. All the next <a>
will also be affected

<h1>Test</h1>
<a href=”#”>Red1</a>
<a href=”#”>Red2</a>

<a> with Red1 is adjacent to <h1> and sibling as well.


<a> with Red2 is also near adjacent to <h1>.

Outtput: Both will be RED SYNTAX:


<head>
<style type=”text/css”>

h1 ~ a
{
color: red;
}

</style>
</head>
<body>
<h1>Test</h1>
<a href=”#”>Red1</a> <a href=”#”>Red2</a> </body>

Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>General Adjacent Sibling
Selector Notation</title>
<style type="text/css">

/* selector + selector {

property1: value1; => Declaration property2: value2; => Declaration }


*/

h1 ~ a { color: red; font-weight: bold;


}

</style>
</head>
<body>
<h1>Adjacent Sibling Selector - HTML TAG</h1>

<a href="#">Home Page</a> <a href="#">Contact</a> <a href="#">About</a>

<p><a href="#">Lorem Ipsum is simply dummy text</a> of the printing and typesetting
industry. </p>
<hr> <div><a href="#">Lorem Ipsum is simply dummy text</a> of the printing and
typesetting industry.</div>
</body> </html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write the CSS rule with General Adjacent Selectors Make the
all the paragraph bold after the h1 tag which are adjacent.

Live Preview Exercise 2 Download the Exercise 2 Exercise 2: Do the


following steps:

Apply the CSS color red when <a> tag is inside the <p> with descendant and
also child selectors and also with Adjacent Siblings Selector and also the
general sibling selector.
Observe which rule is applied.
Live
Preview

2.13 Pseudo Classes

Usage of Pseudo Class Selector Pseudo Class Selector are predefined class
that are available to use for the HTML tags.
For Example, You want to change the color of link when someone mouse
over the link.
This is done by predefined class for the HTML tags called as Pseudo Class
Selectors.

<a> anchor tags has hover, visited pseudo class that we can use. Pseudo class
are separated with “:” along with the HTML tags. Example: a:hover { color:
red; }
SYNTAX:

<head>

<style type=”text/css”>
a:hover { color: red; }

</style>
</head>
<body>
<a href=”#”>Hover on me and I will turn red in color</a> </body>

You don’t have to mention the Pseudo class to the HTML tags attribute.

These are the properties of the HTML tags that you are changing. Sample
Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Pseudo Class Selector
Notation</title>
<style type="text/css">

/* selector: pseudo class {


property1: value1; => Declaration property2: value2; => Declaration }
*/ /* UnVisited Link */ a:link
{ color: blue;
}
/* Visited Link */
a:visited
{ color: gray;
}
/* On Mouse Over Link */
a:hover
{ color: red;
}
/* Active link that is clicked */
a:active
{ color: green;
}

</style>
</head>
<body>
<h1>Pseudo Class Selector - HTML TAG</h1>

<a href="#1">Home Page</a> <a href="#2">Contact</a> <a href="#3">About</a>

</body> </html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write the CSS rule with Pseudo Class Selector Change the <a>
color to red when mouse is over the link. Apply the Pseudo class only for the
first <a> tag after the h1. Rest of the <a> are not affected.
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Apply the hover effect to all the <a> anchor tag only in <p> tag
anywhere in the body.
All the <a> tags outside the <p> are not affected.

Live Preview

2.14 Pseudo Elements

Usage of Pseudo Elements Selector Pseudo Elements Selector are rules that
you want to add right after the element is closed. Irrespective of what is
there after the tag. For Example, You want to add “!!!” after every paragraph
ending. Then you can use the Pseudo Element Selector.
Pseudo class are separated with “::” along with the HTML tags. Example:
p::after { content: “!!!”; }
This will add “!!!” after the every paragraph tag.
p::before will apply the before the tag.
SYNTAX:

<head>
<style type=”text/css”>
p::after { content: “!!!”; }

</style>
</head>
<body>
<p>See the !!! right after the paragraph</p>
</body>

You don’t have to mention the Pseudo element to the HTML tags attribute.
These are the addition data you are inserting before/ after the HTML tags.
Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Pseudo Elements Selector
Notation</title>
<style type="text/css">

/* selector:: Pseudo Elements {

property1: value1; => Declaration property2: value2; => Declaration }


*/

h1::after{ content: "!!!";


}

</style>
</head>
<body>
<h1>Pseudo Elements</h1> <h1>Exclamation Mark is added by CSS</h1>

<a href="#1">Home Page</a> <a href="#2">Contact</a> <a href="#3">About</a>

<p><a href="#">Lorem Ipsum is simply dummy text</a> of the printing and typesetting
industry. </p>
</body> </html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write the CSS rule with Pseudo Element Selector Add “!!!” only
to the first paragraph after the h1 tag.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Add the “!!!’ before every paragraph
Tip: use p::before to apply the rule before the paragraph.

Live Preview

3. CSS Rules

3 CSS Rules
3.1 Precedence

Usage of Precedence
There are many ways to write the same rule in different ways but which one
will be applied on the browser depends on the precedence of the rule.

Some rule has higher priority or precedence over the other rules. Here are
some the rules of precedence:

Order of precedence and last one is applied and gets higher precedence.

ID selector has higher precedence than class selector. div { color: red; }
div { color: blue’ }

div will be blue in color because of the order of the precedence. CSS rule
that is more specific has more priority and applied.

.text-blue{ color: blue; }


div.text-blue { color: blue; }
div.text-blue gets the higher precedence over normal .text-blue class selector
because it is very specific to div tag.
Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>CSS Order Precedence</title>
<!-- CSS Starting --> <style type="text/css">

h1 { color: blue;
}

p { color: green;
} /* This takes the precedence over the first declaration */ p, h1
{ color: red;
}

/* First id then class then element */ /* The more specific the more precedence */ div {

color: red; }

#text-blue{ color: blue;


}

.text-green{ color: green;


}

div#text-blue{ color: lightblue;


}

</style> <!-- CSS Ending -->


</head>
<body> <h1>Heading</h1> <p>Paragraph Text</p>

<!-- Guess what is the color of the text below --> <div id="text-blue" class="text-
green"> CSS Rule which is more specific has more precedence. <br> id has more precedence
over the class. class is more predence over the element.
</div>

<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li>

</ul> </body>
</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Check if ID is higher precedence or class get the higher


precedence.
Change the color of h1 with two selector one is ID selector with blue color
and another one is class selector with red color.
Guess the color of h1?
Live Preview
Exercise 2

Download the Exercise 2 Exercise 2: Check which one has the higher
precedence h1 + p { color: blue; } h1 ~ p { color: red; }

Live Preview

3.2 Inheritance

Usage of Inheritance
All the styles are inherited from the parent styles. This is very important
concept to understand.
Lets say you set the background color of body as red color then every
elements get the red background
If you make the font color as red in body then all the text on the page will
red in color.

The style is inherited from parent tags to child tags.


Example:

<head>
<style type=”text/css”>
body { color: red; }

</style>
</head>
<body>
<h1>This is red color heading</h1> <p>This is red color Paragraph</p>
</body>

Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Inheritance in CSS</title>
<!-- CSS Starting --> <style type="text/css">
/* Anything defined here will be applied to all child elements. */

body{ color: white; background-color: red;

}
/* Overwrite background-color style from parent. */ h1{ text-decoration: underline;
background-color: black; }

.blackscreen{ background-color: black;


} </style> <!-- CSS Ending -->

</head>

<body> <h1>Heading!</h1>

<!-- Inherit the background-color from body parent element style.


->

<p>Paragraph Text</p> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li>


</ul>
<hr>
<!-- Overwrite the background-color style from parent -->

<p class="blackscreen"><a href="#">Lorem Ipsum is simply dummy text</a> of the printing


and typesetting industry. </p>
<hr>
<p><a href="#">Lorem Ipsum is simply dummy text</a> of the printing and typesetting
industry. </p>
</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Apply the default style to all the content on the page. Font Size
12 px
Color Red
Text is italics
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Make body font-size to 12 px and h1 font size to 20px. See
which one take the precedence and the style is inherited or not.

Live Preview

3.3 Last Rule Wins

Usage of Last Rule Wins


When working with CSS you will often find situation when you want to
apply that last rule and it should work everytime irrespective of all the other
inheritance rules applied on that tag.

You can specify the last rule to the tag using the inline css on the tag itself.
This last rule can be applied with style attribute on the tag.

All the elements will have this style attribute using which you can apply the
desired style which will override all the styles mentioned in the internal or
external css.

SYNTAX:
<head>
<style type=”text/css”>
p { color: red; }

</style>
</head>
<body>
<p style=”color: blue;”>This text color will be BLUE</p>
</body>

All the other precedence is overwritten by this inline style because it is


applied at the last after all the rules are applied on that tag. Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Last Rule has the Highest
Precedence</title>
<!-- CSS Starting --> <style type="text/css"> body{ color: red; }
h1

{ color: red;
}

{ color: red;
}

#text-red { color:red;
}
.text-red { color: red;
}
h1#text-red{ color: red; }

h1.text-red{ color:red;
}

</style> <!-- CSS Ending -->


</head>
<body>
<!-- inline style will be applied last --> <h1 style="color: green;" class="text-red" id
="text-red" >Heading!</h1>

<p style="color: blue;">Paragraph Text</p> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item
3</li>
</ul> </body>

</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Apply color red with tag, class, id and blue color with inline to
see the impact of the rules on the tag.
Live Preview Exercise 2 Download the Exercise 2

Exercise 2: Define <p> tag inline as color red. Check if for the next iteration
of <p> will it be red or black.

Will the inline rule is limited to that tag or it is inherited to next tag?
Live
Preview

3.4 Important Rule Wins

Usage of Important Rule Wins

If Inline is the last rule that applied on the HTML tags and it overrides all the
rule then this important rule will even overwrites the inline rule.

“ !important ” is the keyword that we can append to the declaration


property value at the end to indicate to the browser that this is important than
anything else said in the CSS.

Browser will always give important to the rules that has !important at the
end of the rule.

Example: p { color: red!important; }


Observe !important is used after the value and before the “;” SYNTAX:

<head>
<style type=”text/css”>
p { color: red!important; }

</style>
</head>
<body>
<p style=”color: blue;”>This text will still be red</p>
</body>
Nothing can override the property that is marked as Important.

Sample Example

Download the Example


<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Last Rule has the Highest
Precedence</title>
<!-- CSS Starting --> <style type="text/css">
p,h1

{ color: red!important;
}

#text-blue { color:blue;
}
.text-blue { color: blue;
}

h1#text-blue{ color: blue;


}

h1.text-blue{ color:blue;
} </style> <!-- CSS Ending -->

</head>
<body>
<!-- Important rule on the tag is applied. --> <h1 style="color: green;" class="text-
blue" id ="text-blue" >Heading!</h1>

<p style="color: blue;">Paragraph Text</p> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item
3</li>
</ul> </body>
</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Use the !important for <p> as inline css. Check for next element
is it inherited.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Apply the !important for <p> tag as red and for one p tag use the
inline color as blue with !important.
Which one gets the precedence. Will the paragraph be red or blue?

Live Preview

4. Colors and Text

4 Colors and Text


4.1 Colors

Usage of Colors You can represent colors in CSS using different ways.

Colors can be applied to almost every HTML tag like background, text,
border and fill the box.
Mostly commonly used method to represent colors: RGB Value
Hex Code Value
Name of the Color.

RGB is represented with the short form rgb(red, green, blue) and numbers
inside it.
RGB(255, 0, 0) – Red, RGB(0, 255, 0) – Green

Hex Code Value is also used to represent the specific colors. The value starts
with # and then followed by numbers & characters in Hexadecials. It is
typically 6 digits long.

background-color: #ff0000 ;
You can use UPPERCASE – FF or lowercase ff to represents the HEX value.
It is good to use lowercase.
SYNTAX:
<head>
<style type=”text/css”>
a:hover { color: red; }

</style>
</head>
<body>
<a href=”#”>Hover on me and I will turn red in color</a> </body>

Sample Example
Download the Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport"
content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description">
<title>CSS Colors</title>
<style type="text/css">

div{ padding: 10px; width: 50%; font-size: 40px;

} .redboxRGB { background-color: rgb(255,0,0); color: white;


}
.redboxHEX { background-color: #FF0000; color: white;
}
.redboxNAME { background-color: red; color: white;
}
.redboxDARKNAME { background-color: darkred; color: white;
}
</style> </head>
<body> <div class="redboxRGB">

RED BOX - RGB - rgb(255,0,0) </div> <hr> <div class="redboxHEX">

RED BOX - HEX - #FF0000 </div> <hr> <div class="redboxNAME">

RED BOX - NAME - red </div> <hr> <div class="redboxDARKNAME">

RED BOX - NAME - dark red </div>


</body> </html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Fill the body with GREEN color and all the tags
background colors with White and Text as Black.
Represent the colors only with rgb notation.
rgb(0,0,0) – Black , rgb(255,255,255) – White

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Replace the RGB value with Hex Values for the Exercise 1.
RGB value 255 – Hex Value ff
Live Preview

4.2 Text

Usage of Text Font or Text word is used change the behavior of text on the
page. Here are some of the font and text properties. font-family – Specify the
font-name to be used.

font-size – Specify the size of the font in pixels or px. It is the same pixel
used in MS Word.
font-style – Used to apply the italics, normal or oblique
font-weight – Weight is used to represent how thick the stroke of the font
should be. Usually bold, light, medium

text-transform – Control the case of text – Uppercase or lowercase. text-


decoration – Decorating the text underline or over-line. text-shadow – Add
shadow at the back of the text.

Changing Fonts in CSS is no different that you modify a Word document


and changing the contents.
Most of the words will match with the keywords we use in Microsoft Word
Software.
Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>CSS Fonts</title>

<style type="text/css"> p {

font-family: 'Times New Roman', Times, serif; font-size: 20px; /* em, px, %,
normal/medium/large */ line-height: 2em; letter-spacing: 0.2em; word-spacing: 1em; text-
align: left; /* left, right, center, justify */

font-style: italic; /* Normal, Italic, Oblique */ font-weight: bold; /* Light, Medium,


Bold, Black */ text-transform: uppercase; /* lowercase, capitalize */ text-decoration:
underline;

/* none, overline, line-through */


text-indent: 500px; text-shadow: 1px 1px 0px red;
}

p::first-letter{ font-size: 200%;


}
p::first-line{ text-shadow: none;
}

</style> </head>
<body>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book.</p>

</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Use the same text as above sample and apply the
following rules without seeing the properties.

Change the Font Name to ‘Georgia’


Font Size to 18 px;
Align the text to be at the Center
Underline the some part of the Text
Capitalize the entire text. Bold Few things in the text Italics some words in
the text

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Add Text Shadow to First Letter and Make the First Letter Big.
Handle all the changes via the CSS only.

Live Preview

5. CSS Box
5 CSS Box

5 CSS Box
5.1 Borders

Usage of Borders There is a magical box around every HTML tags. To see
the BOX around every HTML tag apply this rule.

*{
border-style: solid;
border-color: red;
}
Always remember that every html tag has a box around it that you can
control.

Every element is a box which is arranged side by side or on top of each


other.
You can control that element by controlling that box.

border-style: solid; – Controls the style of the line


border-color: red; – Color of the border line
border-width: 4px; – Width of the Border Line
border-top-style: dashed; – Apply the style only to top line border-bottom-
style: dotted; – Apply the style only to bottom line

Sample Example
Download the Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport"
content="width=device-width, initial-scale=1.0"> <meta name="description" content="Page
Description"> <title>CSS Box - Border</title>

<style type="text/css">

div{ border-style: solid; border-color: red; border-width: 4px; border-top-style:


dashed; border-bottom-style: dotted; width: 50%; }

.blue-border{ border: 5px solid blue; }

.green-border{ border: 5px solid green; } </style> </head>

<body>

<div> Border Example with Diff line of 4px width and red in color. </div>

<div class="blue-border"> Border Example with Solid line of 5px width and blue in color.
</div>

<div class="green-border"> Border Example with Solid line of 5px width and green in
color. </div> </body> </html>
Live Preview Exercise 1 Download the Exercise 1 Exercise 1: Draw the
Box with Border like this.

border-top-style is used to style the border border-top-color will change the


border color border-width will change the size of the border width

height: 250px; //This make the box 250 px of height width: 250px; //This
make the box 250 px of width

Live Preview Exercise 2 Download the Exercise 2

Exercise 2: Add Border Style Class Selector with blue color and apply it to
h1 to h6.
Live Preview

5.2 Margin
Usage of Margin
With Margin, you can push the boxes around the HTML tag.
You can add Margin on four sides of the box TOP RIGHT BOTTOM LEFT

Margin can be used to add spaces between the boxes and push the boxes
around.

Margin Properties:
margin
margin-top
margin-right
margin-bottom
margin-left
Margin can be set in different ways:

Always think like a clock rotating in clockwise direction Top, Right, Bottom
and Left. That is how the parameters settings are done as well.

h1{
margin-top: 5px;
margin-right: 5px;
margin-bottom: 5px;
margin-left: 5px;
}

OR
h1{
margin: 5px; /*All the 4 sides will have margin of 5 px;*/ }

OR

h1{
/* margin: top right bottom left */
margin: 5px 5px 5px 5px;
}

h1{
/* margin: top left+right bottom */
margin: 5px 5px 5px;
}

Sample Example
Download the Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport"
content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>CSS Box - Margin</title>
<style type="text/css">

.red-border{ border: 5px solid red; margin-bottom: 25px;

.blue-border{ border: 5px solid blue; margin-top: 25px; margin-left: 20px;

.green-border{ border: 5px solid green; margin-left:50px; margin-top: 25px;

} </style> </head>
<body>
<div class="red-border">

Margin Example with Solid red line. </div> <div class="red-border" style="border-style:
dashed">

Margin Example with Dashed red line. </div> <div class="red-border" style="border-style:
dotted">

Margin Example with Dotted red line. </div>


<div class="blue-border">

Margin Example with Solid Blue line. </div> <div class="blue-border" style="border-
style: dashed">

Margin Example with Dashed Blue line. </div> <div class="blue-border" style="border-
style: dotted">
Margin Example with Dotted Blue line. </div>
<div class="green-border">

Margin Example with Solid Green line. </div> <div class="green-border" style="border-
style: dashed">

Margin Example with Dashed Green line. </div> <div class="green-border" style="border-
style: dotted">

Margin Example with Dotted Green line. </div>


</body> </html>
Live Preview Exercise 1 Download the Exercise 1

Exercise 1: Add h1 and p tag and add a red color border. Add negative value
to <p> margin-top: -50px;
Observe the Output.

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Push the paragraph to the bottom of the page and heading on the
top of the page.
Add the margin to h1 tag.
Live Preview

5.3 Padding
Usage of Padding
Padding is the extra space that you inside the box .
Padding add extra space inside the box to make it look bigger.

Padding properties are similar to margin properties the only different is that
margin add space after the box and padding add space inside the box.

Padding add space inside the box.


Margin add space outside the box.
Sample Example
Download the Example
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description">
<title>CSS Box - Padding</title>
<style type="text/css">

.red-border{ border: 5px solid red; padding-top: 10px;

.blue-border{ border: 5px solid blue; padding-left: 10px;

.green-border{ border: 5px solid green; padding: 10px;

} </style> </head>
<body>
<div class="red-border">

Padding Top Example with Solid red line. No Margin. </div> <div class="red-border">

Padding Top Example with Solid red line. No Margin. </div> <div class="red-border">
Padding Top Example with Diff red line. No Margin. </div>
<div class="blue-border">

Padding Left Example with Solid blue line. No Margin. </div> <div class="blue- border">

Padding Left Example with Solid blue line. No Margin. </div> <div class="blue-border">

Padding Left Example with Solid blue line. No Margin. </div>


<div class="green-border"> Padding all sides Example with Solid green line. No Margin.
</div>
<div class="green-border"> Padding all sides Example with Solid green line. No Margin.
</div>
<div class="green-border"> Padding all sides Example with Solid green line. No Margin.
</div>
</body> </html>

Live Preview
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Create RED Box of Width 250px and Height 100px and add
margin of 100px all sides and padding of 50px all sides.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Draw 4 red square box at 4 corner of the page.
Live Preview

5.4 Height and Width

Usage of Height and Width


Height and Width property is used to control the box sizes. How big or small
you want the box size is defined with this property.

You can even set the minimum and maximum height and width of the box.
This is very important property to organize the boxes size on the page.

100 x 250 means 100 Width x 250 Height Properties of the Height and
Width: width height minwidth minheight maxwidth maxheight Sample
Example Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>CSS Box - Width and
Height</title>
<style type="text/css">

.box250 { height: 250px; width: 250px; border: 5px solid green; margin: 10px; min-width:
100px; min-height: 100px;

} .minbox100 { border: 5px solid green; margin: 10px; min-width: 300px; min-height:
300px;
}
.maxbox500 { border: 5px solid green; margin: 10px; max-width: 500px; max-height: 500px;
} </style> </head>

<body>
<div class="box250"> This is a box with 250x250 size and green border and margin of
10px.
</div> <div class="box250" style="padding: 10px;"> This is a box with 250x250 size and
green border and margin of 10px. <strong>It also has Padding of 10px all sides.</strong>
</div>
<div class="box250">
This is a box with 250x250 size and green border and margin of 10px.

</div> <div class="minbox100"> </div> <div class="maxbox500">

I am a flexible box and I can become as small as 300px. How big i can grow? No Limit.
I am a flexible box and I can grow as big as 500px. I can be the smallest.
</div>
</body> </html>
Exercise 1 Download the Exercise 1 Exercise 1: Draw two box on top of
each other.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Draw two boxes side by side.
Use the Property display: inline on both box1 and box2

6. Floating Columns
6 Floating Columns

6 Floating Columns
6.1 Floating Box

Usage of Floating Box float property to specify the element to float left or
right or follow the existing flow of box arrangement.
float: none|left|right|initial|inherit;
none – This will follow the default floating of box and it also breaks the
existing floating property set by it siblings or parent.

left and right – allows to element to float left or right


initial – Custom value can be given to float the element inherit – Follows
the inheritance property from its parent style.

clear: both – property will clear the floating of boxes next to each other.
Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8"> <title>Floating Example</title> <style type="text/css">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description">

.box{ height: 130px; width: 130px; margin-bottom: 10px; margin-right: 10px;

} .blue{ background-color: #5bc0de; float: left;

} .green{ background-color: #5cb85c; float: right;


} </style> </head>

<body> <div class="box blue"></div> <div class="box blue"></div> <div class="box blue">
</div> <div class="box blue"></div> <div class="box blue"></div>

<div class="box green"></div> <div class="box green"></div> <div class="box green">


</div>

</body> </html>

Exercise 1 Download the Exercise 1

Exercise 1: Draw 2 box one row and another two box another row. Like a 2
x 2 matrix.

Use Property: clear: both; to break the floating of boxes. BOX 1 BOX 2
BOX 3 BOX 4

Live Preview Exercise 2 Download the Exercise 2 Exercise 2: Float one


box on left and one on right. Try: float: center; See the code for more
details.
6.2 Floating Images

Usage of Floating Images


Text beside the images can be floated to right or left with the float property.
Like the articles in the newspaper, you have the image and then text running
sometime or left side or right side.
This is achieved by floating the image to left or right and then next text
element will float with it.
Code Snippet to clear floating :

.clearfix::after {
content: “.”;
/* This display property you will learn in next lesson */
display: block;
clear: both;
height: 0;
/* Hide the content that we placed above “.” */
visibility: hidden;
}

This code snippet is a famous hack that many developers use to clear any
floating objects after the box.
Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Page Description"> <title>Floating Example</title>


<style type="text/css">
h1 {
text-align: center; text-decoration: underline;

} img { margin-right: 20px; }

.clearfix::after { /* content: ""; clear: both; display: table; */

content: "."; display: block; clear: both; height: 0; visibility: hidden;

.float-left { float: left;


}

.float-right{ float: right;


} </style> </head>

<body> <h1>German Shepherd</h1> <div class="clearfix">

<img class="float-left" src ="dog1.jpg" alt="German Shepherd" height="250px"


width="250px">

<p>The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed


of medium to large-sized working dog that originated in Germany. The breed's officially
recognized name is German Shepherd Dog in the English language (sometimes abbreviated as
GSD). The breed was once known as the Alsatian in Britain and Ireland.</p>

</div>
<hr>
<div class="clearfix">

<img class="float-right" src ="dog1.jpg" alt="German Shepherd" height="250px"


width="250px">

<p>The German Shepherd (German: Deutscher Schäferhund, German pronunciation: is a breed


of medium to large-sized working dog that originated in Germany. The breed's officially
recognized name is German Shepherd Dog in the English language (sometimes abbreviated as
GSD). The breed was once known as the Alsatian in Britain and Ireland.</p>

</div>
<hr>
<div class="clearfix">

<img class="float-left" src ="dog1.jpg" alt="German Shepherd" height="250px"


width="250px">
<img class="float-left" src ="dog1.jpg" alt="German Shepherd" height="250px"
width="250px">
<img class="float-left" src ="dog1.jpg" alt="German Shepherd" height="250px"
width="250px">
</div>
<hr>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Draw a table with two columns and display content as below.

Exercise 2 Download the Exercise 2

Exercise 2: Put the Image in the center and text in the center without table.

Use Property on img:


display: block;
margin-left: auto;
margin-right: auto;
Refer to the code for more details

6.3 Horizontal Menu


Usage of Horizontal Menu display: inline-block property is used to align
all the block side by side.
Floating the <li> elements left will align all the block to stick together. There
are two properties in this declaration inline-block – one is block and another
one is inline.
All the properties of block can be applied to display:inline-block . display
property controls the behavior of the displaying the elements on the page.

display: none; will hide that element on the page.


display: block will show the block
display: inline will show the block inline.

With display: inline-block allows to set the height and width of the block
where as display: inline does not.
Sample Example
Download the Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport"
content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Floating Example</title>

<style type="text/css"> ul{ background-color: #333; list-style-type: none; overflow:


hidden;

li{ float: left;


}

li a{ display: inline-block; color: white; padding: 14px 16px; text-decoration: none;

} </style> </head>
<body>

<ul> <li><a href="#">Home</a></li> <li><a href="#">Blog</a></li> <li><a


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

</ul>
</body> </html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Write a simple html page with h1, p and li tags and with display
property hide everything on the page.
Live Preview
Exercise 2 Download the Exercise 2 Exercise 2: Add Red Underline on
hover of the menu elements.

Live Preview

6.4 Vertical Menu

Usage of Vertical Menu


Vertical menu is achieved by displaying the each list items as block and not
floating either to left or right.
NOT Floating the <li> elements left/right will align all the block stack one
top of each other.
It is like block of items stacked on top of each other.
Remove the float: left from previous horizontal menu and you can find all
the elements stack vertically.
Sample Example
Download the Example
<!DOCTYPE html>
<html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Page Description"> <title>Floating Example</title>


<style type="text/css">

ul{
background-color: #333; list-style-type: none; width: 200px;

}
li a{ display: block; /* Make the links appear below each other */

color: white; padding: 8px 16px; text-decoration: none;

} </style> </head>
<body>
<ul> <li><a href="#">Home</a></li> <li><a href="#">Blog</a></li> <li><a
href="#">Contact</a></li> <li><a href="#">About</a></li>

</ul> </body> </html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Change the Color of the Link when hover over it.
Live Preview Exercise 2 Download the Exercise 2

Exercise 2: Combine the Horizontal Menu and Vertical menu together and
do it without seeing the code.
Live Preview

7. Positioning Elements
7 Positioning Elements

7 Positioning Elements
7.1 Position Fixed

Usage of Position Fixed With position: fixed property any element can be
fixed at any position of the screen.

Once the element property is mentioned as position: fixed then using the
following property the element can be moved any where on the page.

top
right
bottom
left
Element will be fixed and will will not move on the page.

It is good when you want to show a header bar or footer announcement of


some pages.
Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<!-- <meta name="viewport" content="width=device-width, initialscale=1.0"> -->

<meta name="description" content="Page Description"> <title>Fixed Bar Position at Bottom


of Page</title> <style type="text/css">

/* Default Page & Font Styles - Because we love to see nice design. */

body, html { height: 100%;


}

p { margin: 0 auto; max-width: 600px; margin-top: 40px; line-height: 1.5;

body { font-family: Georgia, serif;


}

h1 { text-align: center;
}

/* Lesson Example - Focus on below code. */ .announcement-bottom { background-color:


red; opacity: .85; padding: 20px; color: rgba(255,255,255,.9); position: fixed; bottom:
0; /* Key Property */ left: 0; right: 0; text-align: center;

.announcement-top{ background: #d4765d; position: fixed; top: 0; /* Key Property */


left: 0; right: 0; /* z-index: 2; */ /* opacity: .85; */ text-align: center; color:
white; padding: 20px;

} </style> </head>
<body> <div class="announcement-top">Get this 10% Off.</div> <div class="announcement-
bottom">Fixed Element at end of the Page</div>
<br><br>
<h1>Position: Fixed</h1>
<p>What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum
has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting,
remaining essentially unchanged. It was popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?

It is a long established fact that a reader will be distracted by the readable content
of a page when looking at its layout. The point of using Lorem Ipsum is that it has a
more-or-less normal distribution of letters, as opposed to using 'Content here, content
here', making it look like readable English. Many desktop publishing packages and web
page editors now use Lorem Ipsum as their default model text, and a search for 'lorem
ipsum' will uncover many web sites still in their infancy. Various versions have evolved
over the years, sometimes by accident, sometimes on purpose (injected humour and the
like).

Where does it come from?

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a
piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard
McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of
the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through
the cites of the word in classical literature, discovered the undoubtable source. Lorem
Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The
Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the
theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum,
"Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those
interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero
are also reproduced in their exact original form, accompanied by English versions from
the 1914 translation by H. Rackham.

Where can I get some? or randomised words which don't look even slightly believable. If
you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything
embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the
Internet tend to repeat predefined chunks as necessary, making this the first true
generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a
handful of model sentence structures, to generate Lorem Ipsum which looks reasonable.
The generated Lorem Ipsum is therefore always free from repetition, injected humour, or
non-characteristic words etc.

There are many variations of passages of Lorem Ipsum available, but the majority have
suffered alteration in some form, by injected humour,
</p>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write Your Name on the top, right, bottom and left of the page.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Display a Word Center of the page.
Live Preview
Live Preview

7.2 Position Absolute

Usage of Position Absolute


Positions allows to move the element around the pages.

By default without CSS, browser will lay all the element one after the other.

To arrange them into correct position we use this position declaration.


With position: absolute we break the running flow of browser placement and
position based on the body position again.

Example:
<h1>This is h1</h1>
<p>This is paragraph</p>

Without CSS, they both appear one after the other. h1 tags starts from the
absolute position the parent position and <p> tag will follow the flow and sit
after <h1>

If you want to break the <p> flow and want to position somewhere else and
follow the new location then we set the position of that element as absolute.

Then browser will start placing them again from top.

position: absolute tells the browser to take this element out of the flow and
start putting from the absolute body position not the current flow.

Sample Example
Download the Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!-- <meta name="viewport"
content="width=device-width, initialscale=1.0"> -->

<meta name="description" content="Page Description"> <title>Fixed Bar Position at Bottom


of Page</title> <style type="text/css">

/* Page Styles */
/* Exercise Section */

.container { background: rgba(0,0,0,.4); height: 250px; width: 250px; margin-left:


300px; margin-top: 150px;
}

.box { height: 150px; width: 150px; background-color: #5bc0de; top: 50px; left: 50px;

position: absolute; /* Absolute to Document and break from parent */


}
</style> </head>
<body> <div class="container"> <div class="box"></div> </div>
</body> </html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Open the Example 1 file and change the parameter to observe
the behavior of the box.
position: absolute; ==> position: relative;

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Draw 2 box (box1 and box2) within one container to and lay
them on top of each other.
Live Preview

7.3 Position Relative

Usage of Position Relative


Relative is just tell browser to follow the current flow and make it relative to
is parent.
Where ever the parent element is, relative property will make the child stack
them relative to parent element.
position: relative helps to group the parent and child together and flow them
next to each other.
Sample Example
Download the Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<!-- <meta name="viewport" content="width=device-width, initialscale=1.0"> -->

<meta name="description" content="Page Description"> <title>Fixed Bar Position at Bottom


of Page</title> <style type="text/css">

/* Page Styles */
body {
background: rgba(0,0,0,.1);
}
/* Exercise Section */

.container { background: rgba(0,0,0,.4); height: 250px; width: 250px; margin-left:


500px; margin-top: 150px;

position: relative; /* For all my child element this is the document. */


}

.box { height: 150px; width: 150px; background-color: #5bc0de; top: 50px; left: 50px;
position: absolute;
}

</style> </head>
<body> <div class="container"> <div class="box"></div> </div>
</body> </html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Draw two box inside the container stack them vertically.
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Draw 3 boxes side by side inside the container horizontally.


Live Preview

8. Display inline Block


8 Display Inline and Block

8 Display Inline and Block


8.1 Display Inline & Block Example 1

Usage of Display Inline Example 1 display: inline and display:block is


the most important CSS rule that will help to align all the blocks in the page
as you want.

display:inline will arrange all the elements side by side. display:block will
arrange all the elements one after the other. Sample Example Download the
Example
<!DOCTYPE html> <html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Display Inline
Example</title>
<style type="text/css">
/* Page Styles */

/* Exercise Section */ span {

display: block; }
div

{ display: inline;
}

</style> </head>
<body>

<!-- <span> == <div style="display: inline"> --> <span>Hello This is the first span tag.
</span> <span>Hello This is the second span tag.</span> <span>Hello This is the third
span tag.</span>

<!-- <div> == <span style="display: block">. --> <div>Hello This is the first div tag.
</div> <div>Hello This is the second div tag.</div> <div>Hello This is the third div
tag.</div>

</body> </html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Display the images side by side and one after the other with
display inline and block.
Live Preview Exercise 2 Download the Exercise 2

Exercise 2: Draw two menu one with inline and another one with block.

Live Preview

8.2 Display Inline & Block Example 2

Usage of Display Inline Example 2


display:inline will not allow to change the height and width of the box.
display:inline-block can be used to change height and width of the box and
still remain inline.
Sample Example
Download the Example
<!DOCTYPE html>
<html>

<head> <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description"> <title>Display Inline and Block
Example</title>
<style type="text/css">
/* Page Styles */
/* Exercise Section */ body{ color: white; }

li{ display: block;


}

li { display: inline; background-color: blue;

width: 100px; /* Cannot add width and height when display is inline. */
height: 100px;
}

li{ display: inline-block; background-color: blue; width: 100px; height: 100px;

}
</style> </head>

<body> <ul> <li>Home</li> <li>Blog</li> <li>Contact</li> <li>About</li>

</ul> </body> </html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Try to change the height and width of the box when
display:inline is used.

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Draw two boxes and align them side by side with
display:inline. Try to change the size of the box with width and height.

Change the display:inline with display:inline-block; See the difference.

Live Preview

9. Layouts
9 Layouts

9 Layouts
9.1 Layout 1

Usage of Layout 1 Build a simple layout with the following things: Header
Content Footer
Sample Example
Download the Example
<!DOCTYPE html> <html> <head>
<title>Sample HTML5 Layout</title> <style>

body { width: 940px; margin: 0 auto; font: "Georgia", Arial, sans-serif;

header,section,article,aside,footer{ display: block;


}

header, footer { padding: 0px; text-align:center;


} </style> </head> <body> <header>
<h1>Page Layout 1</h1> </header> <hr> <section>
<article> <header><h1><u>Article 1</u></h1></header> <div>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book.</p>

</div> <p>#End of Article 1</p> </article> <article>


<header><h1><u>Article 2</u></h1></header>
<div>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book.</p>

</div>
<p>#End of Article 2</p>

</article>
</section>
<footer>

<hr>
Copyright (C) 2018. WPFreelancer.com

</footer>
</body>
</html>

Live Preview
Project Work 1:
Build the same layout from scratch by adding a horizontal menu under the
header.
Try it yourself as a Project!

9.2 Layout 2

Usage of Layout 2
Build a simple layout with the following things:
Header
Content
Left Sidebar
Footer
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<title>Sample HTML5 Layout</title>

<style>
body {
width: 940px; margin: 0 auto; font: "Georgia", Arial, sans-serif;

header,section,article,aside,footer{ display: block;


}

header, footer { padding:0px; text-align:center;

aside{ float: left;


}

section{ float: right; width: 700px; padding-left: 20px; border-left: 2px dotted
#b2a497;

footer{ clear:both !important; width:940px; height: 100px; padding: 10px;

</style> </head> <body>

<header> <h1>Page Layout 2</h1>


</header>
<hr>
<aside> <figure> <img src="dog1.jpg" height="100px" width="100px" /> <figcaption>German
Breed</figcaption>
</figure>
<div> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a
href="#">Contact</a></li> </ul>

</div> </aside>

<section> <article> <header><h1><u>Article 1</u></h1></header> <div>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book.</p>

</div>
<p>#End of Article 1</p>
</article>
<article>
<header><h1><u>Article 2</u></h1></header>
<div>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
<p>#End of Article 2</p>
</article>
</section>

<footer> <hr> Copyright (C) 2018. WPFreelancer.com

</footer> </body> </html>

Live Preview
Project Work 1:

Build the same layout from scratch by adding a horizontal menu under the
footer also.
Try it yourself as a Project!

9.3 Layout 3

Usage of Layout 3
Build a simple layout with the following things:
Header Top Navigation Menu Content Left Side Bar Footer
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<title>Sample HTML5 Layout</title>


<style>

body {
width: 940px; margin: 0 auto; font: "Georgia", Arial, sans-serif;

} header,section,article,aside,footer{ display: block; }

header, footer { padding: 0px; text-align:center;


} </style> </head> <body> <header>
<h1>Page Layout 1</h1> </header> <hr> <section>
<article> <header><h1><u>Article 1</u></h1></header> <div>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book. </p>

</div>
<p>#End of Article 1</p>
</article>
<article>
<header><h1><u>Article 2</u></h1></header>
<div>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer took a galley of type and scrambled
it to make a type specimen book.</p>
</div> <p>#End of Article 2</p>

</article> </section> <footer>

<hr> Copyright (C) 2018. WPFreelancer.com

</footer> </body> </html>


Live Preview
Project Work 1:

Build the same layout from scratch by adding a right side sidebar along with
the left side.
Try it yourself as a Project!

9.4 Layout 4

Usage of Layout 4 Build a simple layout with the following things: Header
Top Navigation Menu Content Left Side Bar Right Side Bar Footer
Sample Example
Download the Example
<!DOCTYPE html> <html> <head>

<title>Sample HTML5 Layout</title> <style>

body { width: 940px; margin: 0 auto; font: "Georgia"", sans-serif;

header,section,article,aside,footer{ display: block;


}

header, footer { padding:0px; text-align:center;


}
nav
{ text-align:center;
}
nav ul
{ list-style-type: none; padding: 0; margin-bottom: 0;
}

nav li { display: inline-block; margin: 0 0 0 50px; width: 100px;

aside, .aleft{ float: left;


}
aside, .aright{ float: right;
}

section{ float: left; width: 500px; padding-left: 20px; padding-right: 20px; border-
left: 2px dotted #b2a497; border-right: 2px dotted #b2a497;

footer{ clear:both !important; width:940px; height: 100px; padding: 10px;

} </style> </head> <body>

<header> <h1>Page Layout 4</h1> </header> <hr> <nav>

<ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a


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

</ul> </nav> <hr> <aside class="aleft">

<figure> <img src="dog1.jpg" height="100px" width="100px" /> <figcaption>German


Breed</figcaption>

</figure> <div>

<ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a


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

</ul>
</div> </aside>

<section> <article> <header><h1><u>Article 1</u></h1></header> <div>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book.</p>
</div> <p>#End of Article 1</p> </article> <article>

<header><h1><u>Article 2</u></h1></header> <div>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type specimen book.</p>

</div>
<p>#End of Article 2</p>

</article>
</section>
<aside class="aright">

<figure>
<img src="dog1.jpg" height="100px" width="100px" /> <figcaption>German
Breed</figcaption>

</figure>
<div>

<ul>
<li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a>
</li>

</ul>

</div> </aside> <footer>

<hr> Copyright (C) 2018. WPFreelancer.com

</footer> </body> </html>

Live Preview
Project Work 1:
Build the same layout from scratch by adding your social profiles in the right
side bar section.
Try it yourself as a Project!
About this Book

About this Book

JAVASCRIPT is a client-side programming language that allows web


developers to create scripts that can run on Client Browser. JAVASCRIPT
Language is basically used to run program at client side. This book will help
you understand the basics of JAVASCRIPT Language and how to put it in
practice to build Websites.

Audience

This tutorial has been designed to meet the requirements of all those readers
who are keen to learn the basics of JAVASCRIPT.

Prerequisites

This book assumes you have no prior knowledge on Programming


knowledge and assume you are at a beginner level.

How to use this Book

This book contains JAVASCRIPT Language Basics, Exercises and Examples


which are part of the PHP Bootcamp Program. This bootcamp has helped
many students to become PHP Full Stack Web Developer in Just 30 days.

>>>Check out more about this program here. ..


Copyright & Disclaimer

Copyright & Disclaimer

© Copyright 2019 by SrinivasIT.com.

All the content and graphics published in this e-book are the property of
SrinivasIT.com. The user of this e-book is prohibited to reuse, retain, copy,
distribute or republish any contents or a part of contents of this e-book in any
manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or
errors. SrinivasIT.com provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this
tutorial. If you discover any errors on our website or in this tutorial, please
notify us at contact@SrinivasIT.com .

Found Typos & Broken Link

If you found any typos and broken links in the course or book, then please
let me know using this email address.
contact@SrinivasIT.com

Support

You can reach me for technical discussions and other support related queries
from here.
support@SrinivasIT.com
Thanks for your support!

Free Courses
Learn HTML in 1 Hour
Learn CSS in 1 Hour
Learn JAVASCRIPT in 1 Hour
Table of Contents

About this Book .......................................................................................... 1


Audience...................................................................................................... 1
Prerequisites ............................................................................................... 1
How to use this Book ................................................................................. 1
Copyright & Disclaimer .............................................................................. 2
Found Typos & Broken Link ...................................................................... 2
Support ........................................................................................................ 2
1 JavaScript Basics ..................................................................................... 8
1.1 Introduction to JavaScript ........................................................... 8
1.2 Internal JavaScript........................................................................ 9
1.3 Comments JavaScript ................................................................12
1.4 External JavaScript .....................................................................16
1.5 Inline JavaScript..........................................................................21
1.6 Hello Sample JavaScript ............................................................24
1.7 JavaScript Terminology .............................................................27
1.8 Testing & Debugging JavaScript ...............................................28
2 Working with Data................................................................................34
2.1 Identifiers .......................................................................................34
2.2 Variables .........................................................................................37
2.3 Primitives........................................................................................43
2.4 Keywords ........................................................................................47
2.5 Reserved Words.............................................................................48
3 Expressions in JavaScript.....................................................................50
3.1 Assignment Expressions...............................................................50
3.2 Comparison Expressions..............................................................54
3.3 Arithmetic Expressions .................................................................60
3.4 Logical Expressions .......................................................................65
3.5 String Operations ..........................................................................69
3.6 Quotes ............................................................................................73
3.7 Boolean...........................................................................................75
3.8 Arrays..............................................................................................78
3.9 Date and Time................................................................................83
4 Statements ............................................................................................88
4.1 if Statements ..................................................................................88
4.2 switch Statements .........................................................................92
4.3 while Statements ...........................................................................97
4.4 for Statements .............................................................................101
5 Function, Objects and Events............................................................106
5.1 Functions ......................................................................................106
5.2 Objects ..........................................................................................109
5.3 Events............................................................................................114
6 Testing .................................................................................................118
6.1 Debugging ....................................................................................118
6.2 Common Errors ...........................................................................121
6.3 Try Catch Block ............................................................................123
7 Document Object Model ...................................................................129
7.1 Find an Element by ID .................................................................129
7.2 Update the Data ..........................................................................132
7.3 Access Form Elements ................................................................134
8 Snippets JavaScript.............................................................................139
8.1 Access the Browser URL .............................................................139
9 Projects JavaScript ..............................................................................141
9.1 Form Validations..........................................................................141
9.2 Guess the Number ......................................................................143

1. JavaScript Basics

1 JavaScript Basics
1.1 Introduction to JavaScript

Invention of JavaScript

During 1990’s, When Internet and HTML was introduced to the IT industry
web pages main purpose was to display content on the browser.

Webpages was created and stored on server which are connected to internet.
These Web page main purpose is to connect all the other resource on the
internet.

Connecting things in internet and accessing all resources via web page was
the main concept.
In 1995, Brandon Eich Wrote Java Script and main purpose of it was to
change the DOM which was created by the HTML.
JavaScript was born.
JavaScript main purpose is to execute program at the browser. With
JavaScript you are do following things:

• Change the Page Data at Runtime.


• Validate what user is doing on the Page.
• Show and Hide things on the page based on the User Action.
• Download and Upload data in the background from the

browser.
• Animation Effects

• Control the timer. History of JavaScript

In 1995, Brandon Eich Wrote Java Script at Netscape. Original name of


JavaScript was Mocha. It was renamed to LiveScript and then to JavaScript.

Soon many browsers were released and which adopted the specification.
JavaScript is a Scripting Language. Know more about Scripting language
from here.
Future of JavaScript

The main advantage of JavaScript is that it runs on users browser. There is


no need to refresh the page or send the page to server and do some
calculation.

All the operations happens on Browser so it makes the JavaScript extra


ordinary faster than any web language.

Latest Famous Languages like Angular are completely built on JavaScript


which handles front and back of the application from browser itself.

New Web Programming Language are based on JavaScript.

1.2 Internal JavaScript

Usage of Internal JavaScript JavaScript can be written in many different


places in HTML page.
One of the method of defining the JavaScript is inside the same HTML page.
This type of JavaScript includes is restricted to page level only means you
cannot reuse this code in some other pages.

Benefit of using this internal JavaScript is when you want specific changes
to apply for that page level only.
SYNTAX:
<head>
<script>
alert(‘This will show an alert box’);
</script>
</head>

alert is a function to show alert box on the web page.


alert(‘some text here’);
Add semicolor ‘;’ at the end of the line.
<style> tag is used to write the JavaScript inside this tag. This tag <style>
can be defined in <head> or <body>

JavaScript code written inside the <style> tag are executed as it is written.
If you have two <script> tag one after the other then code inside the <script>
executes one after the other.
If you put the <script> tag at the end of the <body> tag then the script is
executed at the last after the page is loaded.
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta


name="description" content="Page Description">
<title>Internal JavaScript</title>
<script>

alert('This is called from Head Section!');


</script>
</head>

<body>
<h1>Heading</h1>
<p>Paragraph Text</p> <ul>
<li>Item 1</li> <li>Item 2</li> <li>Item 3</li>

</ul>
</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Put the <script> tag with alert at the end of the page in the
<body> section.
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Put the script tag with alert with tags in the <body> section and
see if that works.
Also, Press “OK” button and then Press F5 to see if the alert box comes
again.
Live Preview

1.3 Comments JavaScript

Usage of Comments
You can use the special notation to comment the code inside the JavaScript.
Comments helps to document about the code with a single or multiple line.
Comments are ignored by the JavaScript Engine and it is not displayed on
the browser.
HTML comments and JavasScript comments are not same. Don’t get
confused with the comments in JavaScript vs comments in HTML.

There are two types of Comments in JavaScript:


Single Line Comments
Multi Line Comments
// – This is Single Line Comments. Use to comment one line. /* – is used to
indicate the comments are starting.
*/ – is used to indicate the comments are ended.
Anything between /* and */ will not be executed by the browser.

SYNTAX:
<head>
<script>
// This will alert the user – Single Line Comments
alert(‘This is alerted on the browser’);

/* Starting of the Multi Line Comment


alert(‘This is not executed by the browser’);
Ending of the Multi Line Comments */

</sript>
</head>
Sample Example Download the Example
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Page Description"> <title>How to Write Comments in


JavaScript</title>
<!-- This is HTML Comments -->

<script> /*
This is a multi-line comment in JS. This is different than the HTML comments. Anything
inside this block will be ignored.

alert('This is Multi Line Comment Blok. Ignored by the Browser');


*/
//Alert the user with the text alert('Welcome to JavaScript!');
</script>
<!-- This is HTML Comments -->
</head>

<body>
<h1>Heading</h1> <p>Paragraph Text</p> <ul>

<li>Item 1</li> <li>Item 2</li> <li>Item 3</li>

</ul>
</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Make the multi-line comments that looks like single line.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2:
1. Comment the entire <script> block with HTML comments.

Observe how the HTML comments can comment all the <script> tags
2. Write Multi Line Comments inside the Multi Line comments and see it
shows an error on the page.

Live Preview

1.4 External JavaScript

Usage of External JavaScript


JavaScript (JS) can be written in another file and included inside the HTML
page.
This type of external JS is very powerful and helpful technique which is
commonly used in every website development.

Benefit of using this external JS is that you have one JS file that is included
in all the website pages.
By just changing at one place in the JS it will impact the overall site design
look and feel.

This is one of the best practice to separate the design with the html tags and
store them in a external file and include it in all the HTML pages.

External JS filename should be .js and it can be included anywhere inside the
HTML page with

<script type=’text/javascript‘ src=”location of the file></script> SYNTAX:


<head>
<!– Make sure javascriptcode.js file exists in the ‘javascript’ folder –>

<script type=’text/javascript‘
src=”javascript/javascriptcode.js”></script>
</head>

<script> tag is used to link the resource to the HTML page. The attribute of
script tag will let the browser knows what type of resource it is.

src attribute is similar to <img> tag src to map the location of the file in the
server with the path and filename. You can even mention the foldername/file
name to refer the file path.

Sample Example
Download the Example

There are two files: index.html javascript/javascriptcode.js

javascriptcode.js file is linked inside the index.html file with <script> tag.
javascript is the folder name it could be any name and not mandatory to have
that name.
type attribute tells the type of the content in the file. In this case, it is
text/javascript
FileName: index.html
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>External JavaScript</title>
<script type='text/javascript'

src="javascript/javascriptcode.js"></script>
</head>

<body>
<h1>External JavaScript!</h1>
<p>Paragraph Text</p>
<ul>

<li>Item 1</li> <li>Item 2</li> <li>Item 3</li>

</ul>
</body>
</html>
FileName: javascriptcode.js
alert('I am called from javasriptcode.js file!');

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create js1.js and js2.js and link them in the HTML page. Do not
create folder and place the js files along with the HTML file. Filename:
js1.js
alert( ‘This is called from js1.js’ );
Filename: js2.js
alert( ‘This is called from js2.js’ );

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Place one <script> tag inside the <head> tag and put another
<script> tag at the end of <body>.
Swap the sequence, put js2.js first and js1.js last.

Live Preview

1.5 Inline JavaScript

Usage of Inline JavaScript Inline JavaScript is defined inside the HTML


tag itself like an attribute. Inline JS overrides all the styles defined in internal
JS and External JS. Inline JS code is executed first. This is defined in the
HTML tag as a attribute. SYNTAX: <a href=”#” onclick=”alert(‘Welcome
to JavaScript!’);”>Click Me</a>
onclick is a event for <a> tag and it is called when user clicks on the link.
Calling this alert is handled by the browser itself. When user clicks on the
link, browser will raise the click event on this tag and because we ask to
raise an alert when this event is raised. This method is called.

Whatever is mentioned inside the onClick value will be executed as


JavaScript.

JavaScript is written inside this onClick event within double quotes “”. All
the JavaScript is exactly similar as mentioned in internal and external
JavaScript.

Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Inline JavaScript</title>

</head>

<body>
<a href="#" onclick="alert('Welcome to JavaScript!');">Click Me</a>
</body>

</html>

Live Preview
Exercise 1 Download the Exercise 1
Exercise 1: Add an Image and on clicking the image show an alert message.

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Show a alert message when clicked anywhere on the page.


Find the area when clicked – alert is raised and find the area where alerts are
not raised on the body.
Live Preview
1.6 Hello Sample JavaScript

Hello World Program You can choose to write JavaScript Internal, External
or Inline and it will work.
But the best way is to organize your code into one file so that it is easy to fix
issues at one place for your entire site.

For this hello world sample, we will use the inline javascript. Once we know
how to write functions and call them from on click even then we improve
this program.

Instead of alert we will use confirm method that shows ok and cancel button.
However, we don’t take any action on what user pressed so just show a
different confirm box when user click the link.
confirm(‘Enjoying JavaScript!’);

Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Sample JavaScript Program!</title>

</head>

<body>
<h1>Sample JavaScript Program</h1>
<p>Paragraph Text</p>
<a href="#" onclick="alert('Hello World!');">Hello Message!</a>

<br>
<a href="#" onclick="confirm('Enjoying JavaScript!');">Do you Like?</a>
</body>
</html>

Live Preview Exercise 1 Download the Exercise 1

Exercise 1: Show list of items 1, 2 and 3. When user clicks any links show
what they have clicked.

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Replace onclick with onmouseover in the above example and


see how alert is raised when mouse is over the link. Live Preview

1.7 JavaScript Terminology


These are the terms you need to know if you are a JavaScript Programmer.
Semicolon (;) – Semicolor symbol is used to indicate the browser that line is
finished.
Brackets – [] – These are used to represent Arrays.

Braces – { } – Flower brackets are used to define the scope like starting
point and ending point and we write the code inside this block.

Like starting of function and ending of a function.


parantheses – () – Is used to call a function.

Identifiers – are the name given to variables, functions, properties or object.


Any thing you name it is identifier.
Variable – Any identifier that stores a value.
Operators – Special symbols that are used to perform some operation. Like
Arithmetic operator + is used to add two numbers. Example : +, -, ++
Expressions – They are variables or operators that resolves into something.
a = 1 + 2 is an expression.
a = 1 + 2; //Expression always evaluate to some other value.

Statements – Group of commands to perform an action or could be a single


statement. They end with ‘;’. Statement are meant to do some action.

{
y = sum(1, 2);
alert(“value of y” + y);
}

1.8 Testing & Debugging JavaScript

Testing Debugging JavaScript Because JavaScript runs in the browser the


only way to debug the JavaScript program is from the browser tools

Chrome and Firefox has plenty of debugging tools that can help to find the
issue and fix it. You can pause the execution of javascript program and
debug it steps by step.

You need to learn this method to find the issues in JavaScript and Fix it.
Inspect Window:
Load any HTML program with JavaScript in Chrome and press CTRL +
SHIFT + I.
This will load the Inspect Window.

Console Tab:
Console tab is the output tab where you can write the logs of your program
and view it.
Even browser will it is own log here if there is any issue in the HTML
program.
console.log(‘This is a log from JavaScript program’);

This is the easiest way to debug your program by writing console.log at


many places in your code and verify it from the inspect -> console window.

Download the Example


<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>External JavaScript</title>
<script type='text/javascript' src="js1.js"></script>

</head>

<body>
<h1>External JavaScript!</h1> <p>Paragraph Text</p>
<ul>

<li>Item 1</li> <li>Item 2</li> <li>Item 3</li>

</ul>
</body>
</html>

Live Preview Exercise 1 Download the Exercise 1

Exercise 1: Include another js file in the head section. js2.js but do not
create the file. Verify the error in the console window.
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Remove the ) at the end of the console.log or alert and see the
error in the console window.
Live Preview
2. Working with Data
2 Working with Data
2.1 Identifiers

Usage of Identifiers Identifiers are the name that we give to variables,


functions, objects, properties and events.
There are some rules that you need follow to define the Identifiers.
• Identifiers can contain only letters, numbers, underscore and dollar sign
• Identifiers cannot start with a number.
• Identifiers are case sensitive
• Identifiers can be any length.
• Identifiers cannot use keywords and reserved words.

Some of the Valid Identifiers:

• strFirstName
• $var
• index_1
• crashReport

InValid Identifiers:

• 1PhoneNumber
• false
• long
• package

Sample Example Download the Example


<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Identifiers JavaScript</title>
<script>

Alert('JavaScript is Case Sensitive');


</script>
</head>

<body>
<a href="#" onclick="ALERT('Welcome to JavaScript!');">Click Me</a>
</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Try to change the console.log as CONSOLE.LOG and see what


happens.
CONSOLE.LOG(‘JavaScript is Case Sensitive’);

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Make onclick as ONCLICK and see if the click command still
works. Write the correct JavaScript Syntax.
OnClick is an attribute of the HTML tag not JavaScript.
Live Preview

2.2 Variables

Usage of Variables Variables are used to store information which are used
inside the program.
var keyword is used to define a variable.
var message = “This is a test message”;

= is the assignment operator used to assign the value to the


variable.

“” double quotes is used to represent string value.


; semicolor is used to end the assignment statement.
SYNTAX:

//Declaring a Variable
var variableName;
//Initialize the variable with empty string
variableName = “”;
//Assigning Value to the Variable.
variableName = “This is a Test Message!”;

//Multiple Variable
var name1, name2, name3;
nam1 = “firstName”, name2 = “middleName”, name3 =”lastName”;

//Defining the Integers & Decimals


var counter = 0;
counter = 10;
var total = 10.98;
counter = total;

Show Variable in alert message:


var firstName = “WPFreelancer.com”;
alert(‘Welcome to ” + firstName );

+ symbol is used to attach a variable to the string and display it. Write
Variables on HTML Document

document.write() method can be used to write anything on the HTML page.

As alert is used to show alerts similarly document.write() method is used to


write content on the HTML page. It can also access variable defined in the
head -> script section.
<script type=”text/javascript”>
document.write(“Your Message” + message + “<br>”); </script>

Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Variables</title>
<script>

//Declaring a Variable var message;


//Initalizing a Variable with Empty String message = "";
//Assigning value to the Variables message = "1) Say Hello to Variables!";

//Displaying the Variables alert(message);


console.log(message);

var counter = 0;
alert("2) Counter Before: " + counter); message = "2) Counter Before: " + counter;
console.log(message);

counter = 100;
alert("3) Counter After: " + counter); message = "3) Counter After: " + counter;
console.log(message);

</script>
</head>

<body>
<h1>Variables</h1>
<script type="text/javascript">
document.write("Your last Message: " + message); </script>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1 Exercise 1: Count the number of times the user
clicked the link and show it for every click on the link.
Define the counter variable in the head -> script section and track the
number of clicks and show it in the console.log.
Snippet:
onclick=”counter = counter + 1; console.log(‘counter:’ + counter);”
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Accept two names from User and Display them on the HTML
page.
Accept Name: firstName = prompt (“Enter First Name”);
Display Name: document.write(“First Name: ” + firstName + “<br>”);
Live Preview

2.3 Primitives

Usage of Primitive Data Types Primitive data types means the basics data
types that can be used in JavaScript programs.
There are 3 Primitive Data Types:

1. Number Data Type


2. String Data Type
3. Boolean Data Type
Number Data Type is used to store whole, positive, negative and decimal
numbers.

String Data Type is used to store character data.


Boolean Data Type is used to store true and false values. Numeric Data:
var count = 1;
String Data:
// Use Single Quote or Double Quotes

var fullName = “WPFreelancer”;


var lastName = ‘WPFreelancer’;
Boolean Data:
var flag = true;
var results = false;
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Primitive</title>
<script>

//Numeric Data Type


var counter = 0;
counter = counter + 100; console.log("Counter : " + counter);

var decimalcount = 1.45;


decimalcount = decimalcount + 74.32; console.log("Decimals : " + decimalcount);

//String Data Type


var fullName = "WPFreelancer";
fullName = fullName + '.com';
console.log("Website Name: " + fullName);

//Boolean Data Type


var flag = true;
console.log("Flag Value: " + flag);

</script>
</head>
<body>
<h1>Check the Console Log</h1>
</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Accept two numbers using prompt. Add those numbers and
display on the browser.
Tip:
Use parseInt() method to convert the string to integer.

var firstValue = prompt(“Enter the First Value: “);


var firstValue = parseInt( firstValue);

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Ask user a question and print if they click ok or cancel.

Tip:
var userAnswer = confirm(“Do you like grapes?”);
Live Preview

2.4 Keywords

Keywords
These are the list of the keywords that you should not use to define
variables.

Keywords should not be used as Identifiers .


Keywords separated with space:

abstract arguments boolean break byte case catch char class const continue
debugger default delete do
double else enum eval export extends false final
finally float for function goto if implements import
in instanceof int interface let long native new
null package private protected public return short static super switch
synchronized this throw throws transient true try typeof var void volatile
while with yield

2.5 Reserved Words

Reserved Words These are the list of the reserved words that you should
not use to define variables, functions, objects or properties.

Reserved words should not be used as Identifiers .


Reserved Words separated with space:

Array Date eval function hasOwnProperty Infinity isFinite isNaN


isPrototypeOf length Math NaN name Number Object prototype String
toString undefined valueOf
3.Expression in JavaScript
3 Expressions in JavaScript
3.1 Assignment Expressions

Usage of Assignment Expressions Expressions are evaluated into a result


value or final value or single value.
There are couple of Expressions:

1. Assignment Expressions
2. Comparison Expressions
3. Arithmetic Expressions
4. Logical Expressions

We will look at Assignment Expressions in this topic.


Expressions uses Operators to perform the activity.
= is the assignment operator which assigns the value to the variable.
message = “something”; is a assignment expression that assign value to the message variable.
Compound Assignment Operators

Compound assignment operators helps to do more than one operators job. It


combines two operators together to perform an action.
Compound Assignment Operators are:

• +=
• -=
• *=

counter += 1;
counter = counter + 1; counter -= 1;
counter = counter – 1; counter *= 1;
counter = counter * 1; Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Assignment Expressions</title>
<script>

var counter = 10;


</script>
</head>
<body>
<h1>Assignment Expressions</h1>
<a href="#" onclick="counter+=1;console.log(counter);">Increase

Counter</a>
<a href="#" onclick="counter-=1;console.log(counter);">Decrease
Counter</a>
<a href="#" onclick="counter*=2;console.log(counter);">Multiple
Counter</a>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Ask user to enter a number and display the square of this
number.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create two <script> tags. Define variable in first <script> tag
and assign value in another <script>. Finally display it on the body.

Live Preview

3.2 Comparison Expressions


Usage of Comparison Expressions
Expressions are evaluated into a result value or final value or single value.

There are couple of Expressions:


1. Assignment Expressions
2. Comparison Expressions
3. Arithmetic Expressions
4. Logical Expressions

We will look at Comparison Expressions in this topic. Expressions uses


Operators to perform the activity. Comparison expression always evaluate
into a true or false value.

> is the comparison operator which compares the two values. message
variable will be have a true or false.
Comparison Operations:

• < – Less than


• > – Greater than
• == – Equal to
• === – Equal value and Equal Data Type
• !== – Not Equal Value and Equal Data Type
• != – Not Equal
• >= – Greater than or Equal to
• <= – Less than or Equal to
Conditional (Ternary) Operator JavaScript also contains a conditional
operator that assigns a value to a variable based on some condition.
variablename = (condition) ? value1:value2
counter = (10<=10) ? 10 : 0;
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Comparison Expressions</title>
<script>

var counter = 10 <= 10;


//Conditional (Ternary) Operator var resultValue = (counter) ? 10:0;
</script>
</head>
<body>
<h1>Comparison Expressions</h1>

<script type="text/javascript">
document.write("Compared: " + counter + "<br>"); document.write("Result Value: " +
resultValue);

</script>
</body>
</html>

Live Preview Exercise 1 Download the Exercise 1

Exercise 1: Ask user to guess your number. When the number is matched
with 7 then show “WINNER’ word or show ‘TRY AGAIN’
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Find out a Even number and Odd Number from the number
entered by the User.
Tips:
var resultValue = (counter%2) ? “ODD NUMBER”: “EVEN NUMBER”;
Live Preview

3.3 Arithmetic Expressions

Usage of Arithmetic Expressions Expressions are evaluated into a result


value or final value or single value.
There are couple of Expressions:

1. Assignment Expressions
2. Comparison Expressions
3. Arithmetic Expressions
4. Logical Expressions

We will look at Comparison Expressions in this topic.


Expressions uses Operators to perform the activity.

Arithmetic expression always evaluate into a single value. A series of


operations that results into a single value.
+ is the arithmetic operator which adds two values.
message variable will be have 8 value.
Arithmetic Operations:

• + – Addition
• – Subtraction
• * – Multiple
• / – Division
• % – Modulus
• ++ – Increment
• — Decrement
Order of Precedence Order of precedence decides which operates evaluates
first. From Left to Right, these operators has higher priority

• ++
• —
• * / %
• + –

Increment Example: counter = 10;


counter++; // This means counter = counter + 1; Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Arithmetic Expressions</title>
<script>

var counter = 10;


console.log(counter);
counter = counter + 10; </script>
</head>
<body>
<h1>Arithmetic Expressions</h1>
<a href="#" onclick="counter++;console.log(counter);">Increase

Counter</a>
<a href="#" onclick="counter--;console.log(counter);">Decrease
Counter</a>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Accept two numbers from user and show addition, subtraction,
multiplication and division of two numbers.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Ask length and breadth from the user and calculate the area of a
rectangle and display on the page.
Tips:
var resultValue = length * breadth;

Live Preview

3.4 Logical Expressions

Usage of Logical Expressions Expressions are evaluated into a result value


or final value or single value.
There are couple of Expressions:

1. Assignment Expressions
2. Comparison Expressions
3. Arithmetic Expressions
4. Logical Expressions

We will look at Logical Expressions in this topic. Expressions uses


Operators to perform the activity.

Logical Operators are used to check the if the condition is true or false based
on many conditions.
&& is the logical operator which checks left side and right side value and
decides if the condition is true or false.

(5 > 3) – true
(8 < 5) – false
true && false = false

result variable will have false boolean value.


Logical Operations:

• && – AND
• || – OR
• ! – NOT

Order of Precedence Order of precedence decides which operates evaluates


first.

• NOT
• AND
• OR

Sample Example Download the Example


<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Arithmetic Expressions</title>
<script>
var input1 = prompt("Enter First Value: ");
var input2 = prompt("Enter Second Value: ");
var result = (input1 < input2) || (input1 == input2)
</script>
</head>
<body> <h1>Arithmetic Expressions</h1>

<script type="text/javascript">
document.write(input1 + " <= " + input2 + " is "+ result);
</script>
</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Ask user to enter spelling of days of the week in lowercase and
check if the spelling is correct.
Print “CORRECT” or “WRONG” based on the condition met.

Live Preview Exercise 2 Download the Exercise 2

Exercise 2: Ask user to enter a value between 1 to 10 and confirm it is


correct or wrong.
Print “CORRECT” or “WRONG” based on the condition met.
Live Preview

3.5 String Operations

Usage of String Operations There two string operators that can be used to
join the string:

1. +
2. +=

+ is the string operator that can be used anywhere to join two strings.
Examples:
var name = “Firstname” + “lastname”;
var name += “!”; //Add the value at the last.
String Methods:

• indexOf(search, position)
• substr(start, length)
• substr(start, stop)
• toLowerCase()
• toUpperCase()

var name = “WP Freelancer”; alert( name.toLowerCase() ); Sample


Example Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>String Expressions</title>
<script>

var input1 = prompt("Enter Your First Name: ");


var input2 = prompt("Enter Your Last Name: ");
var userName = "<strong>Welcome " + input1 + ", " + input2 + "</strong>";
</script>

</head> </body> </html>

<body>
<h1>String Expressions</h1>

<script type="text/javascript"> document.write(userName);


</script>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Try to use a the + and += operator and prepare a string and print
it.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Define the String variable like and observe the output. Avoid
this common mistake with the string operations.
Guess the Output.
Live Preview

3.6 Quotes

Usage of Quotes in Strings


Single Quotes and Double Quotes can be used to represent String in
JavaScript.
Escape Sequence:
Sometime you need to show some special characters like single quotes or
double quotes inside the content.

var message = ‘We \’ ll be going to BootCamp soon!’;


\ is used to escape the characters in the string.
\n is used to add new line
\” to escape the double quotes.

Sample Example Download the Example


<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>String Expressions</title>
<script>

var input1 = prompt("Enter Your First Name: ");


var input2 = prompt("Enter Your Last Name: ");
var userName = "<strong>Welcome " + input1 + ", " + input2 + "</strong>";
</script>
</head>
<body>
<h1>String Expressions</h1>

<script type="text/javascript"> document.write(userName);


</script>
</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Write a paragraph with single quotes and double quote and
escape single quotes.
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Write the same paragraph from above in double quotes and
escape double quotes.

Live Preview

3.7 Boolean

Usage of Boolean Boolean Variables helps to make decisions or store a


decision based on an expression.
Boolean values can be true or false.
You can use boolean variable as a condition to check if the value is true or
false.
var result = 2 > 1;
var message = (result) ? “CORRECT”: “WRONG”;
Example:
var isTrue= “Henry” == “H3nry”;
Based on the conditional operator, the output can be stored in the boolean
primitive data type.
isTrue will hold false value.
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Boolean Expressions</title>
<script>

var result = 2 > 1;


var message = (result) ? "CORRECT": "WRONG";
</script>
</head>
<body>
<h1>Boolean Expression</h1>

<script type="text/javascript"> document.write(message);


</script>
</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Accept a number from user and if the number is 7 then show
“FOUND” and if not say “TRY AGAIN!
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Ask user to guess a word that starts with A and then match it
with the word that you guessed it.

Live Preview

3.8 Arrays

Usage of Arrays
Arrays are special type of Objects that holds one or more items called as
elements.
Each element could be primitive data type or object. length is used to
indicate the number of elements in the array. Define an Array
ARRAY LITERAL:
var arrayName = [1, 2, ‘white’, false];
ARRAY CONSTRUCTOR:
var arrayName = new Array(length / values);

Access an Array Element


arrayName[index]
Length of an Array Element
var lenofArray = arrayName.length;
Add Values to Array
var newArray = [];
newArray[0] = ‘white’;
newArray[1] = ‘red’;
Access the Values from the Array
var color1 = newArray[0];
Add new element at the end
newArray[ newArray.length] = ‘Black’;
First Element of Array
var firstElement = newArray[0];
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Boolean Expressions</title>
<script>

var colorsArray = ['white', 'black', 'green', 'blue']; console.log(colorsArray);


console.log(colorsArray.length);
console.log(colorsArray[0]);
console.log(colorsArray[1]);
console.log(colorsArray[2]);
console.log(colorsArray[3]);
colorsArray[colorsArray.length] = 'red';
console.log(colorsArray[4]);
console.log(colorsArray);
console.log(colorsArray.length);

</script>
</head>

<body>
<h1>Arrays</h1> </body>
</html>

Live Preview Exercise 1 Download the Exercise 1


Exercise 1: Create an Array with String, Number and Boolean and display
them.

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Do the following exercise with Arrays


1. Define an Empty Array
2. Add 1 Element
3. Display the Length
4. Add 2 Element
5. Show the two Elements
6. Show the Length of the Array

Live Preview

3.9 Date and Time

Usage of Date and Time Date() is a class library available to access the
date.
However, Date is not a primitive data type. You need to create a instance of
Date to access the date functions.
var today = new Date();
By default, dt will have user system date and it can be displayed with its
methods.
Date Methods

• toDateString() – Returns a date with formatted String.


• getFullyear() – Returns the 4 digit year from the Date.
• getDate() – Returns the day of the month from the Date.
• getMonth() – Fetch the month.

Examples:
var today = new Date(); alert( today.toDateString() );
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Date and Time</title>
<script>

var today = new Date(); console.log(today.toDateString());


console.log(today.getFullYear()); console.log(today.getDate());
console.log(today.getMonth());

</script>
</head>
<body>
<h1>Date and Time</h1>
<script type="text/javascript">

document.write(today.toDateString()+"<br>"); document.write(today.getFullYear()+"<br>");
document.write(today.getDate()+"<br>"); document.write(today.getMonth()+"<br>");

</script> </body>
</html>
Live Preview
Exercise 1
Download the Exercise 1 Exercise 1: Display length of the Date.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Display only day of the week from the Date.

Live Preview

4.Statements
4 Statements
4.1 if Statements

Usage of if Statements if statement are used to check a condition and make


a decision based on the result of the condition.
It can choose some action when the condition is true and also take some
action when it false.
You can nest multiple conditions together and decide to choose one action
based on multiple conditions.

Syntax:
if ( condition1 ){
// Statements
} else if( condition1 || condition2 ){
// Statements
} else {
// Statements
}
Example 1:
if( marks > 35 ){
alert(“You are Passed!”);
}else{ alert(“Try Again!”); } Example 2: if( marks > 35 && marks < 60 ){
alert(“You are Passed with Grade C”); }else if ( marks > 60 && marks < 80
){ alert(“You are Passed with Grade B”); }else if ( marks > 80 ){ alert(“You
are Passed with Grade A”); }else{ alert(“Try Again!”); } Download the
Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>if Statements</title>
<script>

var dayOfWeek = prompt("Enter the Day of Week"); var result;


dayOfWeek = dayOfWeek.toLowerCase();
result = "It's Friday!";

if( dayOfWeek == 'monday' || dayOfWeek == 'mon'){ result = "First Day of Week";


}else if( dayOfWeek == 'tuesday' || dayOfWeek == 'tue' ){ result = "Second Days of
Week";
}else if( dayOfWeek == 'wednesday' || dayOfWeek == 'wed' ){ result = "Mid Week";
}else if( dayOfWeek == 'thursday' || dayOfWeek == 'thurs'){ result = "Preparing for
Weekend";
}else if( dayOfWeek == 'friday' || dayOfWeek == 'fri'){

}else if( dayOfWeek == 'saturday' || dayOfWeek == 'sat' ){ result = "Enjoying Day!";


}else if( dayOfWeek == 'sunday' || dayOfWeek == 'sun'){ result = "Resting Day!";
}else{
result = "Cannot find that Value!";
}
</script>
</head>
<body>
<h1>if Statements</h1>

<script type="text/javascript"> document.write( result );


</script>

</body> </html>

Live Preview

Exercise 1 Download the Exercise 1


Exercise 1: Accept number 1 to 10 and check if the user entered correctly
between 1 to 10 as requested with the if Statement.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Ask user to enter the age and decides if he is kid, man (age > 21)
or senior citizen (age > 55).

Live
Preview

4.2 switch Statements

Usage of Switch Statements


switch statement are used to check a value and make a decision based on the
result of the value matching.

Syntax:
switch( variable ){
case value:
//Statement
break;
case value: //Statement break; default: //Statement break; } Example 1:
switch ( dayOfWeek ){ case ‘Mon’: alert(“Welcome Monday”); break; case
‘Tuesday’: alert(“Welcome Tuesday”); break; default: alert(“Try Again!”);
break; } Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">

<title>Switch Statements</title> <script>

var dayOfWeek = prompt("Enter the Day of Week"); var result;


dayOfWeek = dayOfWeek.toLowerCase();

switch(dayOfWeek){
case 'monday':
result = "First Day of Week"; break;

case 'tuesday':
result = "Second Days of Week"; break;

case 'wednesday':
result = "Mid Week";
break;

case 'thursday':
result = "Preparing for Weekend"; break;

case 'friday':
result = "It's Friday!";
break;

case 'saturday':
result = "Enjoying Day!";
break;

case 'sunday':
result = "Resting Day!";
break;

default:
result = "Cannot find that Value!"; }
</script>
</head>
<body>
<h1>Switch Statements</h1>
<script type="text/javascript"> document.write( result );
</script>

</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Accept number 1 to 10 and check if the user entered correctly
between 1 to 10 as requested with the Switch Statement.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Ask user to enter the age and decides if he is kid, man (age > 21)
or senior citizen (age > 55). Use the Switch Statement.

Tips:
switch(true){
case (input > 21):
//Statements
break
}
Live Preview

4.3 while Statements

Usage of While Loop


While statement are used to loop a block code and run it until a condition is
met.
Running the same block of code until the condition is satisfied. Syntax:
while( condition ) {
//Statements
}
Example 1:
var counter = 0;
while ( counter < = 10 ){
counter++;
}
Syntax:
do{
//Statement }while ( condition ); Example 1: var counter = 0; do{
counter++; } while ( counter < = 10 ); Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>While Statements</title>
<script>

var counter = 0;
while( counter <= 10){
console.log("While Counter: " + counter++);

}
counter = 0;
do{

console.log("Do Counter: " + counter++); }while( counter <= 10);


</script>
</head>
<body>
<h1>While Statements</h1>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Accept two number from user and print all the numbers between
them. Print only maximum of 10 numbers.
break; – is a keyword that can be used in the loop to break from the loop.
continue; – is a keyword that can be used in the loop to continue the loop by
skipping the below statements.
Tip:
if( counter >= 10){
break;
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Accept two number from user and print EVEN numbers only
between them. Print only maximum of 10 numbers.

Live Preview

4.4 for Statements

Usage of For Loop


for Loop are used to loop a block code and run it until a condition is met.
Running the same block of code until the condition is satisfied. Syntax:
for( counter initialization; condition; increments ) {
//Statements
}
Example 1:
for(var counter = 0; counter <= 10; counter++){
alert(counter);

Download the Example


<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>For Statements</title>
<script>

for(var counter=0; counter<=10; counter++){ console.log("For Counter: " + counter);


}
</script>

</head>
<body>
<h1>For Statements</h1>
</body>
</html>
Live Preview Exercise 1 Download the Exercise 1

Exercise 1: Accept two number from user and print all the numbers between
them. Print only maximum of 10 numbers.
break; – is a keyword that can be used in the loop to break from the loop.
continue; – is a keyword that can be used in the loop to continue the loop by
skipping the below statements.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Accept two number from user and print EVEN numbers only
between them. Print only maximum of 10 numbers. Live Preview

5.Functions, Objects & Events


5 Function, Objects and Events
5.1 Functions

Usage of Functions Functions is a block of statements that performs an


action.

You can pass parameters to functions and it can return a value from the
function using “return ” keyword.

Syntax of Function Declaration: function nameOfFunction(Parameters){


return someValue; } Example 1: function area(width, height){ return width
* height; } var size = area(10, 20); Syntax of Function Expression: var
nameOfFunction = function(Parameters){ return someValue; } Example 1:
var area = function(width, height){ return width * height; } var size =
area(10, 20); Example of Immediately Invoked Functions: var size = (
function(){ var width = 10; var height = 20; return width * height; }() );
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Functions</title>
<script>

function sum(a, b){ return a + b;


}

var size = function(width, height){ return width * height;


}

</script>
</head>

<body>
<h1>Functions</h1>
<a href="#" onclick="alert( sum(2,5) );">Add 2 + 5</a>
<br>
<a href="#" onclick="alert( size(10,20) );">Area of 10 * 20</a>
</body>
</html>

Live Preview Exercise 1 Download the Exercise 1

Exercise 1: Accept two number from users and add those two numbers
using functions.

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Accept two number from user and print EVEN numbers only
between them. Print only maximum of 10 numbers. Create functions for this
and execute it.
Live Preview

5.2 Objects

Usage of Objects Object groups variables and functions together. Variables


in objects are called as Properties. function in Objects are called as Methods.

If Hotel is an Object then numberOfRoom is a Property and


checkAvailability() is a function.
Object Literal:
var hotel = {
numberOfRooms: 10,
bookedRooms: 5,
checkAvailability(): function(){ return numberOfRooms – bookedRooms; }
}; var hotelTotalRooms = hotel.numberOfRooms; or var hotelTotalRooms =
hotel[‘numberOfRooms’]; var roomsFree = hotel.checkAvailability();
Creating an Object: var hotel = new Object(); hotel.numberOfRooms = 10;
hotel.bookedRooms = 5; hotel.checkAvailability = function(){ return
this.numberOfRooms – this.bookedRooms; } Object Function Notation:
Creating Object as a Function function hotel(totalRooms, roomLeft){
this.numberOfRooms = totalRooms; this.bookedRooms = roomLeft;
this.checkAvailability = function(){ return this.numberOfRooms –
this.bookedRooms; } }

var h1 = new hotel(10, 5); var h2 = new hotel(10, 4); Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Objects</title>
<script>

function Area(a, b) {
this.input1 = a; this.input2 = b;

this.getArea = function(){
return this.input1 * this.input2;
}
}

var input1 = prompt("Enter First Value"); var input2 = prompt("Enter Second Value"); var
result = 0;

input1 = parseInt(input1); input2 = parseInt(input2);


var a1 = new Area(input1, input2); result = a1.getArea();
console.log("area - " + result);
</script>
</head>
<body>
<h1>Objects</h1>

<script type="text/javascript"> document.write("Area - " + result);


</script>

</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Accept two number from users and add those two numbers
using Objects.
Create a MathsObj Objects and Make Add and Subtract functions.
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Accept two number from user and print EVEN numbers only
between them. Print only maximum of 10 numbers. Create Object for this
and use it.
5.3 Events
Usage of Events
Events are actions that user performs on the browsers. Functions that handle
the events are called as Event Handlers. Common Events with the elements:

• onClick
• ondblClick
• onmouseover
• onmouseup
• onmouseout

Example: <a href=”#” onmouseover=”alert(‘hello’);”>Mouse Over Me</a>


Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Events JavaScript</title>

</head>

<body>
<a href="#" onclick="alert('Welcome to JavaScript!');">Click Me</a> <br>
<a href="#" onmouseover="alert('Welcome to JavaScript!');">MouseOver

me</a>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Alert when user mouseover and mouseout events on link.

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Use onload() event on the body to greet the user welcome
message.
6.Testing
6 Testing
6.1 Debugging

Step 1: Write JavaScript Code with Errors


Write a External JavaScript file “scripts.js” and include it in the HTML file.
Try the following Errors:
1. Give the wrong javascript file link name as scripting.js instead of
scripts.js
o Verify and Fix the program using Developer Tools shown below.
Download the Exercise 1
Live Preview 1
1. Add Sum() method in the Javascript file and do not create that function.
This will cause the program to fail.
Click on the file name – scripts.js
Download the Exercise 2
Live Preview 2
Step 2: Open HTML Page Using Chrome
Download the Source code and open the HTML file using the chrome
browser and test it.
Step 3: Open Developer Tools
3 Ways to open the Chrome Developer Tool:

1. CTRL + SHIFT + I
2. F12
3. Top-Right Menu -> More Tools -> Developer Tools

Step 4: Debug Two ways to find the error file:

1. Once you open the console window it show the errors with red color.
Clicking on the link will take you to the javascript error code.

2. Click on Source Tab and open the file. It will show any errors in the file
with red cross marks.

6.2 Common Errors

Common JavaScript Errors


These are the most common JavaScript errors that you might make while
writing the JavaScript.
Forgetting the Semicolors ‘;’ at the last.
JavaScript is Case Sensitive. So make sure the names matches as it is
described.
Difference between Assignment and Comparison Operator. Example:
//Using Assignment Operator instead of Comparison Operator.
if( a = b ){
// Statement
}

Comparing Number with String.


Forgetting the ‘+ ‘ sign in the string. Example: “This is a sample ” +
message + ” Program” + message1 ” to do it!”;
Forgetting the Single Quotes Opening and Closing.
Example: ‘This is a sample ‘ + message + ‘ Program’s ‘ + message1 + ‘ to
do it!’;

Missing Parenthesis in If Statements


Example:
//Missing Parenthesis
if ( x > y) && (y > 100) {

}
Using Wrong Keywords Case.
Example:

Funtion add(){
}

Using Keywords as Variable name.


Example:

//Keywords as Variable
var name = “hello”;

Forget to close the parenthesis


Example:

function add(){
}
var total = add;
Accessing the Wrong Array Index.
Example:

var myArray = new Array(); myArray[0] = “hello”;


alert( myArray[1] );

6.3 Try Catch Block

Usage of Try Catch Blocks Exceptions in programming are referred as


Runtime Errors.

When Runtime Errors happens there is a way to catch those errors and pass
it to the application and make a clean exit from the program.

This is called as Exception Handling.


The process of making sure the code will not break and if it does it know the
reason for it and make a clean exit.
To handle Runtime errors in the JavaScript we have try-catch blocks. Using
this we can catch the errors and decide what to do next.

SYNTAX:
try{
//Statements
}catch(errorName) {
//Statments
}
Example:
try {
var firstName = “”; if( firstName == “” ) throw “Name is empty”; }catch
(error){ alert(error); }finally { alert(“Thanks for playing!”); } try {} block
will have all the statements

throw is a keyword to throw an error from the program. Once the program
throw an error it will stop processing the next steps. It will jump to catch {}
block.

catch {} block will be executed once the throw is called. The program will
execute out from the catch block safely.
finally{} block will execute every time irrespective of error or not. It is good
place to close all open connections. Handle clean exit.
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Try Catch JavaScript</title>
<script>

try{
var input1 = prompt("Enter some Number");
//Throw an error when input is empty if( input1 == "") throw "No value mentioned";
//If the above code is error then this is not executed alert("Input is correct!");

}catch(error){
//Catch the error
alert(error);

}finally{
//This will execute every time with or without error alert("Have a good Day!");
}
</script> </head>

<body>
<h1>Heading</h1>
<p>Paragraph Text</p> <ul>

<li>Item 1</li> <li>Item 2</li> <li>Item 3</li>

</ul>
</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Accept one number from user and raise error if the number is
not integer.

Use Function: isNaN() to check if the value is number or not. if(


isNaN(input1) ){
}

Live Preview Exercise 2 Download the Exercise 2 Exercise 2: Ask user to


enter number between 1 to 100. Show the following message on the page:

• If the input is between 1 to 100 – Thank the user


• If the input is greater than 100 – Ask user to enter between 1 to 100
•If the input is not number – Ask user to enter numeric values only. throw
the error message here.

Live
Preview

7.Document Object Model

7 Document Object Model


7.1 Find an Element by ID

What is DOM? Document Object Model or DOM in short is nothing but the
hierarchy representation of all the HTML elements like a tree. DOM is
created by the browser for the HTML page so that it can easily navigate and
make changes to the elements.

Document – Parent element of the DOM


Element – Each Orange box is an element
text – Each Green box is an text.
JavaScript can modify the DOM elements. By adding, removing and reading
the elements from the DOM.
Read a Value of an Element
You can read any element from the DOM using JavaScript functions:

1. getElementById(idName)
2. getElementsByTagName(tagName)
3. getElementByName(name)
4. getElementByClassName(className)

Download the Example


<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Inline JavaScript</title>
<script>

function show(){
var txtValue = document.getElementById('txtName').value; alert( txtValue );

}
</script>
</head>

<body>
<h1>Access the DOM Elements</h1> <form>

<input type="text" id="txtName" />


<input type="button" onclick="show();" Value="Show Value" /> </form>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Copy the example and change the id=”txtName” to


name=”txtName” and use this method to access the same value
getElementByName.

Tips:
var txtValue = document.getElementsByName(‘txtName’)[0].value;
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Access all the form text box elements using arrays and access them by name.
Tip:

<input type=”text” name=”txtName” />


<input type=”text” name=”txtName” />
<input type=”text” name=”txtName” />

Live Preview

7.2 Update the Data


Update the Element Data innerHTML property can be used to update data
for any element.

Adding data to this attribute will modify the DOM element and it will reflect
immediately on the page.
Example:
document.getElementById(id).innerHTML = “This is a added element”;
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Inline JavaScript</title>
<script>

function update(){ }
</script>

document.getElementById("txtValue").innerHTML =
document.getElementById("txtName").value;
</head>

<body>
<h1>Update the DOM Elements</h1>
<p id="txtValue"></p>
<form>

<input type="text" id="txtName" onkeypress="update();"/>


</form> </body>
</html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Create two Text box and if user writes the data in one text box
then display the text in other text box.
Tip:
document.getElementsByName(“txtName”)[1].value =
document.getElementsByName(“txtName”)[0].value;
Exercise 2
Download the Exercise 2

Exercise 2: Show a button and when user press ask them to type heading
then change the heading with the new value.

Live Preview

7.3 Access Form Elements

Access the Form Elements


You can access all the form elements using the DOM.

This is very helpful when you want to check what user has entered the data
before sending the data to server to save it.
It is called as Client Side Validation.
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Inline JavaScript</title>
<script>

function checkFormData(){
//Query all elements that tag name as input var inputs =
document.getElementsByTagName("input");
var message = "Form Elements\n\n";
for (var i=0; i < inputs.length; i++) {

if (inputs[i].getAttribute('type') == 'text') {
message += inputs[i].getAttribute('name') + ": "; message += inputs[i].value + "\n";
}
}
alert(message);
}
</script>
</head>

<body>
<form name="user" id="userfrm" action="#">
Your Name: <input type="text" name="name" id="txt_name" />
Your Email: <input type="text" name="email" id="txt_email" />
<input type="button" name="submit" value="Submit" onclick="checkFormData();" />
</form>
</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Read the Checkbox checked on the form using JavaScript.

Tip:
<input type=”checkbox” id=”chkbox” onclick=”showFormData()”>
document.getElementById(“chkbox”).checked
Exercise 2
Download the Exercise 2
Exercise 2: Call JavaScript function when the form is submitted.

TIP:
<form name=”search” onsubmit=”return callFunction()” >

Live Preview

8.Snippets j S it
8 Snippets JavaScript

8 Snippets JavaScript
8.1 Access the Browser URL

Usage Browser History Snippet This snippet of code will help you to
navigate the page front or back based on the page history.
You can make the page go back and front from the JavaScript. Download the
Snippet
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Snippets JavaScript</title>
<script>

function goBack(){ history.back();


}
</script>
</head>

<body>

<a href="#" onclick="goBack();">Go Back</a> <br> <a href="#"


onclick="history.forward();">Go Forward</a> </body>

</html>
Live Preview

9.Projects J S it
9.1 Form Validations

Form Validation This project will show how to validate the form using the
JavaScript. Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Form Validations JavaScript</title>
<script>

function checkFormData(){ var message = "";

//Access the TextBox


var tname = document.getElementById("txt_name").value; var temail =
document.getElementById("txt_email").value; var tage =
document.getElementById("txt_age").value;

//Access the Radio Button


var tgender1 = document.getElementById("radio1").checked; var tgender2 =
document.getElementById("radio2").checked;

//Access the Checkbox


var tchkbox = document.getElementById("chkbox").checked;

message = "Name: " + tname + "<br>"; message += "Email: " + temail + "<br>"; message +=
"Age: " + tage + "<br>"; message += "Male: " + tgender1 + "<br>"; message += "Female: "
+ tgender2 + "<br>"; message += "Agreed: " + tchkbox + "<br>";

document.getElementById("tmessage").innerHTML = message; }
</script>
</head>

<body>
<p id="tmessage"></p>
<h1>Form Validations</h1>

<form action="https://wpfreelancer.com/" method="get">

Your Name: <input type="text" name="tname" id="txt_name" /> <br><br> Your Email: <input
type="text" name="temail" id="txt_email" /> <br><br> Your Age: <input type="text"
name="tage" id="txt_age" /> <br><br>

Male <input id ="radio1" name="gender" type="radio" checked> Female <input id ="radio2"


name="gender" type="radio"> <br><br>
<input type="checkbox" id="chkbox" /> Agree to our Terms <br> <br>
<input type="button" name="submit" value="Submit" onclick="checkFormData();" />
</form>
</body>
</html>
Live Preview

9.2 Guess the Number

Guess the Number This project will ask user to guess the right number
between 1 to 10. It will keep asking the number until the user guess it.
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>Guess The Number</title>
<script>

var message = ""; var answer = 5;

do{ var input1 = prompt("Guess the Number Between 1 to 10!"); input1 = parseInt(input1);

if( input1 != answer ){ alert("Nope - Wrong.");


}

}while(answer != input1)
message = "You Guessed it Right - " + answer + " is the answer!";
</script>
</head>
<body>
<h1>Guess the Number</h1>

<script type="text/javascript"> document.write(message);


</script>

</body>
</html>
Live Preview
About this Book

About this Book

MYSQL is a Database Query language that allows web developers to access


MySQL database using PHP Libraries. MySQL is database used to store
data in table format. This book will help you understand the basics of SQL
Language and how to put it in practice to build Websites.

Audience

This tutorial has been designed to meet the requirements of all those readers
who are keen to learn the basics of MySQL.

Prerequisites

This book assumes you have no prior knowledge on Programming


knowledge and assume you are at a beginner level.

How to use this Book

This book contains SQL Language Basics, Exercises and Examples which
are part of the PHP Bootcamp Program. This bootcamp has helped many
students to become PHP Full Stack Web Developer in Just 30 days.

>>>Check out more about this program here. ..


Copyright & Disclaimer

Copyright & Disclaimer

© Copyright 2019 by SrinivasIT.com.

All the content and graphics published in this e-book are the property of
SrinivasIT.com. The user of this e-book is prohibited to reuse, retain, copy,
distribute or republish any contents or a part of contents of this e-book in any
manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or
errors. SrinivasIT.com provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this
tutorial. If you discover any errors on our website or in this tutorial, please
notify us at contact@SrinivasIT.com .

Found Typos & Broken Link

If you found any typos and broken links in the course or book, then please
let me know using this email address.
contact@SrinivasIT.com

Support

You can reach me for technical discussions and other support related queries
from here.
support@SrinivasIT.com
Thanks for your support!

Free Courses
Learn HTML in 1 Hour
Learn CSS in 1 Hour
Learn JAVASCRIPT in 1 Hour
Table of Contents

About this Book .......................................................................................... 1


Audience...................................................................................................... 1
Prerequisites ............................................................................................... 1
How to use this Book ................................................................................. 1
Copyright & Disclaimer .............................................................................. 2
Found Typos & Broken Link ...................................................................... 2
Support ........................................................................................................ 2
1 MySQL Basics .......................................................................................... 7
1.1 Introduction to Databases and SQL .......................................... 7
1.2 What is MySQL?..........................................................................10
1.3 What is phpMyAdmin? ..............................................................12
1.4 Datatypes MySQL ......................................................................15
1.5 Keywords MySQL...........................................................................16
2 phpMyAdmin ........................................................................................18
2.1 Login and Logout phpMyAdmin ..................................................18
2.2 Create Users...................................................................................20
2.3 Create Database and Table..........................................................23
2.4 Run Simple SQL Statements ........................................................29
3 MySQL Statements...............................................................................35
3.1 Create a Table ................................................................................35
3.2 Drop a Table...................................................................................35
3.3 INSERT Statements........................................................................38
3.4 SELECT Statements........................................................................38
3.5 Clause WHERE, LIMIT ...................................................................40
3.6 Operators IS NULL, LIKE, ORDER BY...........................................41
3.7 UPDATE Statements......................................................................43
3.8 DELETE Statements .......................................................................44
4 mySQL & PHP with PDO ......................................................................47
4.1 Database Connectivity ..................................................................47
4.2 Simple Query from PHP to mySQL..............................................48
4.3 Form to Add, Edit, Update and Delete ........................................52
5 mySQL & PHP with mysqli...................................................................55
5.1 Database Connectivity ..................................................................55
5.2 Simple Query from PHP to mySQL..............................................56
5.3 Form to Add, Edit, Update and Delete ........................................60

1. MySQL BASICS
1 MySQL Basics
1.1 Introduction to Databases and SQL

What is a Database? A Database is a structured ways of storing the data on


your
computer so that it can be easy searched, managed and updated. Data stored
in a file are not easy to search because it is not properly organized this is
solved by using Database Software.

Database software helps to store the data in such a way that it can retrieved
faster. Even Database software has capacity to hold large amount of data.

How Data are stored in Database?


Data in the database are stored in one or more tables. Each tables will have
data organized in row and column format.

Sample Marks Table will look like this.

Table Name: Marks


ID, SUBJECT and MARKS are called as Columns.
Value on each line are called as Rows.

What is Relational Database?


You can create relation between tables and avoid duplicating the data by
using references between the tables.
Student ID Reference is used in Marks Table to make a
relation between the tables.
Relationship of tables also helps to break a bigger table structure into small
tables and link them.
What is SQL?
SQL Stands for “Structured Query Language” it is a language used to access
the data in the database.
SQL is pronounced as ‘S-Q-L’ or ‘sequel’.
SQL Language is predefined with keywords that you can use to do the
following things:

Create a Table Delete a Table Search Table with Conditions Insert Rows
Update Rows Delete Rows SQL language can be used to perform such
actions on the database. Example: To delete a table you can say: DROP
TABLE <tablename> Usage of Database:

Instead of storing the data in files and access them. All the data are stored in
the Database.

In a Website you can store the following things:


User Information
Product Information
Product Pricing
Orders
Invoice
Enquiry
Contacts
and many more

Every website uses Database to store its information because it is easy and
faster to store and access it.

1.2 What is MySQL?

MySQL is a open source relational database management system which is


free to use.
Open source means you can even download its source code and change it for
your needs.
Relational Database means you can create relation between the tables when
you use MySQL.
Download the MySQL from: https://www.mysql.com/ With MySQL
Database Software, you can

• Insert, Update or Delete the data in Tables.


• Query the Database for a specific row based on unique data condition.
• Use SQL language to access the data in the database.
• handle large amount of data.

You have to download the MySQL database to your local machine to start
using it.
MySQL is under maintenance of Oracle. You can even purchase a license
from Oracle for business purpose.

It also runs on various platforms like Linux, Unix and Windows and it works
pretty well with PHP because PHP has many libraries to access the MySQL
Database.

How to Access the MySQL from Command Line


Step 1: Make sure you have installed WAMP Server from this guide. Step 2:
Open Command Line with CMD + R and Type cmd.
Step 3: Go to folder
“cd C:\wamp64\bin\mysql\mysql5.7.21\bin”

Step 4: Type >mysql -u root -p


Press enter when it ask for password.
There is no password.
Step 5: This is your MySQL Database

Step 6: Type ‘quit’ to exit.


1.3 What is phpMyAdmin?

How to access the MySQL Database?


Once you install the MySQL database there are three ways to access the
database:

• Command Line Client


• Graphical Dashboard called as phpMyAdmin.
• PHP Program

What is phpMyAdmin? phpMyAdmin is a web based client using which


we can access the MySQL Database and Tables.
We can perform the database operations like:

• Creating Users
• Creating Database, Tables
• Inserting, Updating and Deleting the Data

This is a Web based client using which we can perform the database
operation on the MySQL.
MySQL is the Database and phpMyAdmin is the web Client to access the
database.

How to Access the MySQL from phpMyAdmin


Step 1: Make sure you have installed WAMP Server from this guide. Step 2:
Make sure the WAMP Server is running.
Step 3: Open Browser and type this url http://localhost/phpmyadmin
Step 4: Username is root and password is blank. Press enter.
Step 5: Press the logout button to exit from the application
1.4 Datatypes MySQL

Datatypes in MySQL are divided into this 3 categories:

• Numeric
• Strings
• Date and Time

Numbers in MySQL are:

• INT
• TINYINT
• SMALLINT
• MEDIUMINT
• BIGINT
• FLOAT
• DOUBLE
• DECIMAL

String in MySQL are:

• CHAR
• VARCHAR
• BLOB (TINYBLOB, MEDIUMBLOB, LONGBLOB)
• TEXT (TINYTEXT, MEDIUMTEXT, LONGTEXT)
• ENUM

Date and Time in MySQL are:

• DATE
• TIME
• DATETIME
• TIMESTAMP

Most Commonly Used Datatypes:

• INT OR FLOAT OR DECIMAL – To Store numbers and decimals


• CHAR OR VARCHAR – To Store String
• DATETIME – To Store Date and Time

1.5 Keywords MySQL

Commonly used Keywords in MySQL SQL Statements:

• SELECT
• INSERT
• UPDATE
• DELETE
• AS
• DROP
• DESC
• TABLE
• DATABASE
• WHERE
• ISNULL
• ORDER BY

Complete list is found here from MySQL

2.phpMyAdmin
2 phpMyAdmin
2.1 Login and Logout phpMyAdmin

How to Login into phpMyAdmin Step 1: Make sure you have installed
WAMP Server from this guide. Step 2: Make sure the WAMP Server is
running.

Step 3: Open
Browser and type this url
http://localhost/phpmyadmin
Step 4: Username is root and password is blank. Press enter.
How to Logout from phpMyAdmin Step 1: Press the logout button to exit
from the application
How to Change Password into phpMyAdmin
Step 1 : Click on Home Icon

Step 2: Click on the Change Password.


Step 3: After you change password. Login again with the new password.

2.2 Create Users

How to Create user with phpMyAdmin


Step 1: Login into phpMyAdmin with the url: http://localhost/phpmyadmin
Step 2: Click on User Accounts -> Add New Account on the Home Page.
Step 3: Add the Username and Password and click on Global Privileges.
Click on GO Button at the bottom of the page.

Step
4: Check the User Created
Step 5: Press the logout button to exit from the application

Step 6: Login again with new user credentials.

2.3 Create Database and Table

What is Database & Table?


Database is a collection of Tables. One Database can have multiple tables.
One Table can have defined column and all the data is table are stored in
each row.
Create Database in phpMyAdmin
Create Database ‘schooldb’
Step 1: Open the phpMyAdmin Dashboard
Step 2: Click on Database

Step 3: Enter the new Database Name – schooldb


Step 4: Check the Database

Step 5: Create Two tables – student and marks


Step 6: Create Two tables – student
Save Button is bottom right

Step 7: Verify
the table
Step 8: Create the marks table
Step 9: Verify the Table

2.4 Run Simple SQL Statements

In this exercise, you will

• Create Table
• Insert Data in Table
• View the Table Data

Step 1: Login into phpMyAdmin Type the url:


http://localhost/phpmyadmin in the browser. Step 2: Click on Database
Step 3: Open the Database
Step 4: Click the insert link
Step 5: Insert the data

Step 6: Verify the Rows in the Table


Click on the “Browse ” link beside the table.
Step 7: Add the data for ‘marks’ table and browse it.
3. MySQL STATEMENTS

3 MySQL Statements
3.1 Create a Table

Follow this two Guide to create the table:


• 2.3 – Create Database and Table
• 2.4 – Run Simple SQL Statements
Exercise:

• Create a table name ‘fees’ with two fields o ID – INT


o MARKS – INT
• Add some data to the fees table.

3.2 Drop a Table

Dropping a table means deleting a table. DROP is a keyword to delete the


table. SQL SYNTAX: DROP TABLE <TABLENAME> SQL QUERY:
DROP TABLE ‘fees’;
Step 1: Create a new Table ‘fees’ with ID and Amount Fields Step 2:
Add some Data to the ‘fees’ Table
Step 3: Delete the ‘fees’ table
3.3 INSERT Statements

INSERT is a keyword to INSERT the data in the table. SQL SYNTAX:


INSERT INTO table_name VALUES (value1 , value2 , value3) ; SQL
QUERY: INSERT INTO fees VALUES(10, 86);
Exercise: Add some data to the fees table.

3.4 SELECT Statements

SELECT is a keyword to select the data from the tables. SQL SYNTAX:
SELECT * FROM table_name ; SQL QUERY: SELECT * FROM student;

Step 1: Login into phpMyAdmin and open the ‘studentdb’ Step 2: Enter the
SELECT SQL Query SELECT * FROM student;
Step 3: Verify the Data
3.5 Clause WHERE, LIMIT

WHERE and LIMIT are called as Clause which are used along with SQL
statement to apply the condition.

SQL SYNTAX:
SELECT * FROM table_name WHERE ID <= 100 ;
SQL QUERY:
SELECT * FROM student WHERE ID <= 100 LIMIT 2;

This query tell the to MySQL to fetch student record where ID field value is
less than 100 and fetch only two rows.

EXERCISE 1:
Fetch only 2 records from student table.
SELECT * FROM student LIMIT 2;

EXERCISE 2:
Fetch records where ID > 50 and LIMIT to 1 record.
SELECT * FROM student WHERE student.ID <= 50 LIMIT 1;
3.6 Operators IS NULL, LIKE, ORDER BY

IS NULL, LIKE and ORDER BY are called as operators that you can apply
on the condition to check and sort the records.

IS NULL will check if the field is NULL or NOT. ORDER BY will order /
sort the records based on the field. LIKE has two wild characters:

• % – The percent sign represents zero, one, or multiple characters


• _ – The underscore represents a single character

SQL SYNTAX: SELECT * FROM table_name WHERE columnN IS NOT


NULL SELECT * FROM table_name WHERE columnN LIKE pattern;

SELECT * FROM table_name WHERE columnN LIKE pattern ORDER BY


columnN;

SQL QUERY:
SELECT * FROM student WHERE student.NAME IS NOT NULL;

This query tell the to MySQL to fetch student record where NAME is not
null.
SELECT * FROM student WHERE student.NAME LIKE ‘J%’; This query
tell the to MySQL to fetch student record where NAME matches with J.
SELECT * FROM student WHERE student.NAME LIKE ‘J%’ ORDER BY
student.NAME;
This query tell the to MySQL to fetch student record where NAME matches
with J and sort the records by NAME.
EXERCISE 1:
Execute the above 3 Queries.

3.7 UPDATE Statements

UPDATE statement is used to update an existing row in the table based on a


condition specified with WHERE clause.
SQL SYNTAX:
UPDATE table_name SET column1 = value1 , column2 = value2 WHERE
condition ;
SQL QUERY:
UPDATE student
SET student.name = ‘Julie’ WHERE ID = 100;

EXERCISE 1:
Update the record name when ID = 45

UPDATE student
SET student.name = ‘Julie’ WHERE ID = 45;
EXERCISE 2:
Update the record ID = 100 where NAME = ‘WordPress’
UPDATE student SET student.id = 100 WHERE student.NAME =
‘WordPress’

3.8 DELETE Statements

DELETE statement is used to delete an existing row in the table based on a


condition specified with WHERE clause.

SQL SYNTAX:
DELETE from table_name WHERE condition ;
SQL QUERY:
DELETE FROM student WHERE student.name=’John’;
EXERCISE 1:
Delete a row where ID = 100 from student table.

DELETE FROM student WHERE student.ID = 100;

EXERCISE 2: Delete a row where name is NULL DELETE FROM student


WHERE student.NAME IS NULL;

4. MySQL with PDO


4 mySQL & PHP with PDO
4.1 Database Connectivity

What is PDO? PDO stands for PHP Data Objects it is a library that can be
used to connect to MySQL from PHP code.
PDO gives a object oriented database functions to perform the database
operations on MySQL.

The biggest advantage of using PDO is that you can change database any
time from MySQL to Oracle or Microsoft SQL and the underlying PDO
code will not change.

How to Connect to MySQL DB with PDO?


To connect MySQL DB we need following things:

• Hostname / IP of the server on which MySQL is running.


• Database Name
• Userid
• Password

We have seen how to work with MySQL with phpMyAdmin . Define the
parameters: $dns = ‘mysql:host=localhost;dbname=studentdb’; $username
= ‘root’; $password = ‘root’; $db = new PDO($dns, $username, $password);
$dns will hold the parameters separated by semicolon (;). mysql is the name
of the database localhost means mysql server is running on local machine.
dbname is the database name that we created here .

$username and $password are the user credentials to login into the MySQL.
$db will hold the connection to the MySQL and then we can execute the
SQL query to work on the database tables.
Here are the high level steps to connect to DB:

• Define the DNS variable with hostname and database name


• Create a PDO class with $dns, user name and password.
• This will create an instance using which we can access the

database.

4.2 Simple Query from PHP to mySQL

Write a Simple SELECT query using PDO Credentials:

Database Name: studentdb Table Name: student


Username: root
password: root
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>PDO - SELECT Query</title>

</head>

<body>
<h1>PDO - SELECT Query</h1>
<?php

$query = "SELECT * FROM student;";


$dns = 'mysql:host=localhost;dbname=schooldb';
$username = 'root';
$password = 'root';
try{

$db = new PDO($dns, $username, $password);


//Prepared Statement
$statement = $db->prepare($query);

//Execute the Query $statement->execute(); //close the connection to DB $statement-


>closeCursor();

//Loop all the records using fetch records while ($student = $statement->fetch()) { echo
"ID: " . $student['ID']."<br />\n";
echo "NAME: " . $student['NAME']."<br />\n"; }

}catch(Exception $e) {
$error_message = $e->getMessage();
echo "<p>Error message: $error_message </p>";
}

?>
</body> </html>
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write a Select query to fetch student where ID > 50. SELECT *
FROM student where ID > 50;

Live Preview
Exercise 2
Download the Exercise 2

Exercise 1: Write a Select query to fetch student and sort in ascending order
by name field.
SELECT * FROM student order by name;
Live Preview

4.3 Form to Add, Edit, Update and Delete

Write a Student form to Add, Edit and Delete the Entries from MySQL
DB.
Credentials:

Database Name: studentdb


Table Name: student
Username: root
password: root
Sample Example
Download the Example
Live Preview
Exercise 1
Exercise 1: Create you own form and do the Add, Edit and Delete
Operation.

5. MySQLi with PHP

5 mySQL & PHP with mysqli


5.1 Database Connectivity

What is mysqli? mysqli is a library that can be used to connect to MySQL


from PHP code.
mysqli is the just the extension of the mysql library ( i stands for improved).
mysqli is has more features and function to work with mysql and it very
specific to mysql.
The disadvantage of using mysqli is that you cannot change database once
your code written with this library.
How to Connect to MySQL DB with mysqli?
To connect MySQL DB we need following things:

• Hostname / IP of the server on which MySQL is running.


• Database Name
• Userid
• Password

We have seen how to work with MySQL with phpMyAdmin . Define the
parameters: $hostname = ‘localhost’; $db_name = ‘schooldb’; $username =
‘root’; $password = ‘root’;

@ $db = mysqli_connect($hostname, $username, $password, $db_name);


@ is the error suppressor operator that is used to suppress any error throw by
that statement.

localhost means mysql server is running on local machine. $db_name is the


database name that we created here .

$username and $password are the user credentials to login into the MySQL.
$db will hold the connection to the MySQL and then we can execute the
SQL query to work on the database tables.
Here are the high level steps to connect to DB:

• Define the DNS variable with hostname and database name


• Create a mysqli class with host, database, user name and password.
• This will create an instance using which we can access the database.

5.2 Simple Query from PHP to mySQL

Write a Simple SELECT query using PDO Credentials:

Database Name: studentdb Table Name: student


Username: root
password: root
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta
name="description" content="Page Description">
<title>mysqli - SELECT Query</title>

</head>

<body>
<h1>mysqli - SELECT Query</h1>
<?php

$query = "SELECT * FROM student";


$hostname = 'localhost';
$db_name = 'schooldb';
$username = 'root';
$password = 'root';

try{
$db = new mysqli($hostname, $username, $password, $db_name); // Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
//Select Query
$result = $db->query($query);

//Loop all the records using fetch records while ($student = $result->fetch_assoc()) {
echo "ID: " . $student['ID']."<br />\n";
echo "NAME: " . $student['NAME']."<br />\n"; }

//close the connection to DB $db->close();

}catch(Exception $e) {
$error_message = $e->getMessage();
echo "<p>Error message: $error_message </p>";
}

?>
</body> </html>
Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Write a Select query to fetch student where ID > 50. SELECT *
FROM student where ID > 50;
Live Preview
Exercise 2
Download the Exercise 2

Exercise 1: Write a Select query to fetch student and sort in ascending order
by name field.
SELECT * FROM student order by name;
Live Preview

5.3 Form to Add, Edit, Update and Delete

Write a Student form to Add, Edit and Delete the Entries from MySQL
DB.
Credentials:

Database Name: studentdb


Table Name: student
Username: root
password: root

Sample Example Download the Example Live Preview Exercise 1


Exercise 1: Create your own form and do the Add, Edit and Delete
Operation.
About this Book

About this Book

The PHP Hypertext Preprocessor (PHP) is a programming language that


allows web developers to create dynamic content that interacts with
databases. PHP is basically used for developing web-based software
applications. This tutorial will help you understand the basics of PHP and
how to put it in practice.

Audience

This tutorial has been designed to meet the requirements of all those readers
who are keen to learn the basics of PHP.

Prerequisites

This book assumes you have no prior knowledge on Programming


knowledge and assume you are at a beginner level.

How to use this Book

This book contains PHP Language Basics, Exercises and Examples which
are part of the PHP Bootcamp Program. This bootcamp has helped many
students to become PHP Full Stack Web Developer in Just 30 days.

>>>Check out more about this program here. ..


Copyright & Disclaimer

Copyright & Disclaimer

© Copyright 2019 by SrinivasIT.com.

All the content and graphics published in this e-book are the property of
SrinivasIT.com. The user of this e-book is prohibited to reuse, retain, copy,
distribute or republish any contents or a part of contents of this e-book in any
manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or
errors. SrinivasIT.com provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this
tutorial. If you discover any errors on our website or in this tutorial, please
notify us at contact@SrinivasIT.com .

Found Typos & Broken Link

If you found any typos and broken links in the course or book, then please
let me know using this email address.
contact@SrinivasIT.com

Support

You can reach me for technical discussions and other support related queries
from here.
support@SrinivasIT.com
Thanks for your support!

Free Courses
Learn HTML in 1 Hour
Learn CSS in 1 Hour
Learn JAVASCRIPT in 1 Hour
Table of Contents

About this Book .......................................................................................... 1


Audience...................................................................................................... 1
Prerequisites ............................................................................................... 1
How to use this Book ................................................................................. 1
Copyright & Disclaimer .............................................................................. 2
Found Typos & Broken Link ...................................................................... 2
Support ........................................................................................................ 2
1 PHP Basics................................................................................................ 7
1.1 Installation of PHP ....................................................................... 7
1.2 Echo.............................................................................................35
1.3 Hello Program with PHP ...........................................................41
1.4 Comments ..................................................................................46
1.5 Functions ....................................................................................50
2 Data Basics.........................................................................................55
2.1 Variables .....................................................................................55
2.2 Strings .........................................................................................59
2.3 Numbers .....................................................................................63
2.4 Arrays ..........................................................................................66
2.5 Objects ........................................................................................70
2.6 Constants....................................................................................75
2.7 Boolean .......................................................................................78
2.8 Date and Time............................................................................81
3 Expressions........................................................................................85
3.1 Assignments ...............................................................................85
3.2 Arithmetic ...................................................................................91
3.3 Comparison ................................................................................96
3.4 Logical ............................................................................................101
4 Statements.......................................................................................107
4.1 If Statements ............................................................................107
4.2 Switch Statements ...................................................................112
4.3 While Statements.....................................................................117
4.4 For Statements.........................................................................122
5 General.............................................................................................128
5.1 Exceptions ................................................................................128
5.2 Debug........................................................................................133
5.3 Files............................................................................................135
5.4 Includes & Requires.................................................................140
5.5 Libraries.........................................................................................144
6 Forms................................................................................................148
6.1 GET ............................................................................................148
6.2 POST ..........................................................................................156
6.3 Cookies......................................................................................163
6.4 Session ......................................................................................167
7 Snippets ...........................................................................................172
7.1 Regex.........................................................................................173
8 Projects.............................................................................................177
8.1 Save Student Registration Form Data to File .......................177
8.2 Online Test ...............................................................................180
8.3 Online Calculator .....................................................................182
1. PHP BASICS
1 PHP Basics
1.1 Installation of PHP

Installation of PHP To run PHP on your local system you need to install
HTTP Web Server.
PHP is not like Java or C where you can install the libraries and run PHP on
command prompt.
PHP is a server side programming and used in web. It is designed to run
from Web Server like IIS or Apache HTTP Server.

How PHP Works?


When user type the filename.php path in the browser url:
Browser will go to server where HTTP servers are running.
Web Server will listen to the request.
It will execute the PHP code on the server.
Take the output generated by the PHP Server. Send it back to the browser.
Browser displays the output. Things to Note: You need a Web Server to run
PHP code.

Server executes php on the server and returns the output of the code.
You won’t be able to see PHP code on the browser.
Browser pass the user data from browser to server and fetch the data back
from server.
Inserting into Database, Sending Email, Checking the login credentials is all
done by php program at the server.
No one can see your php code.
Why need a Web Server?

Try this exercise.


Create a sample file name index.php
Add the following PHP code.
<?php echo “Hello PHP!”; ?>
Open the index.php file in the browser.
Watch how browser just show the PHP code.

Browser does not understand PHP nor it understand how to interpret it.

That’s the job of a WebServer.


Webserver interpret the PHP code and send the output to the browser.

That is the reason you need a Web Server to execute PHP code.

Understand WAMP Server

You can choose install the following software individually: Apache –


https://httpd.apache.org/
PHP – http://php.net/software.php
MySQL – https://www.mysql.com/

phpMyAdmin – https://www.phpmyadmin.net/
Apache is the Web Server
PHP is the libraries that helps to run the php code
MySQL is the Database to store the data.
phpMyAdmin is the admin client to access your database.

Instead of installing all the software there is a package which combines all
the software together and give a Web Environment to build web
applications.
That is WAMP. – Windows Web Development Environment

WampServer is a Windows web development environment. It allows you to


create web applications with Apache2, PHP and a MySQL database.
Alongside, PhpMyAdmin allows you to manage easily your databases.

For Mac use this Software – https://www.mamp.info/en/


When you install WAMP you get:
Apache2
PHP
MySQL
phpMyAdmin

All 4 software are installed on your local machine which provides an


environment to develop web application.

Visit & Download WAMP Server


Step 1: Visit WAMP Site – http://www.wampserver.com/en/
Step 2: Click on Download from Menu
Step 3: Install 64-bit OR 32- bit based on your Windows Machine.

Step 4: Instructions Page. Click on the Download Link to download the


WAMP Server.
Step 5: Install the supported Libraries.
Step 6: It will redirect to sourceforge.net and download it from there. File
Name should be – wampserver3.1.3_x64.exe
Step 7: WAMP Server is downloaded.
Install WAMP

Step 1: Locate the downloaded Software “wampserver3.1.3_x64”

It will have this icon. Even you can find this icon in the
system tray once the software is installed.
Step 2: Double Click to Start the Installation process.
Step 3: Accept the Agreement. and Click Next. Step 4: Do not change the
default path. It will be installed in C:\WAMP64
Step 5: Click Next
Step 6: Verify the path where the software is installed and click on Install.

Step 7: Close all the Browsers and Select the Default Browser. Step 7:
Select the Notepad
Step 8: Click Finish and Note the Software Versions.
Install Microsoft VC Checker

Next Step is to check if the Microsoft VC++ Package is missing from


windows system.

Step 1: Download the VC Checker Software.


http://wampserver.aviatechno.net/files/tools/check_vcredist.exe
Step 2: It will download the check_vcredist.exe software

Step 3: Install check_vcredist.exe software.

Step 4: Click on Check


Step 5: Install the VC and then Run Again to make sure you all the
supported Libraries.
Download from here:
https://support.microsoft.com/en-us/help/2977003/the-latest-
supportedvisual-c-downloads

Verify WAMP

WAMP Server is installed in “C:\wamp64” folder.


Step 1: Run the WAMP Server
Run the file: C:\wamp64\wampmanager.exe

Goto C:\wamp64 folder and run the


WAMP Server – wampmanager.exe
See the Server running with GREEN color icon in the system tray.

Click on the
ICON and you should see this menu.

Step 2: Click on Localhost on the Menu


Browser will open the URL – localhost
You should see this page.
This confirms that WAMP server is installed properly.
Step 3: Recheck if you have the following things working:
WAMP Icon in Green color in system tray
Click on Localhost in the WAMP menu
WAMP displays the localhost page correctly.

Stop WAMP
Step 1: Click on the System Tray WAMP Icon and Select Stop Services.

Step 2:
WAMP Icon Turns to RED.

Step 3: Type “localhost” in the Browser URL This should


show error page in chrome.
This confirms that WAMP Server is Stopped.
Start WAMP

Step 1 : Click on the System Tray WAMP Icon and Select Star Services.

Step 2 :
WAMP Icon Turns to GREEN

Step 3: Type “localhost” in the Browser URL This should show


the home page for localhost
Check WAMP Version

Open the WAMP Menu from System Tray and you can find the WAMP
Version.

Verify the WAMP Folder


You should have this two folders in C:\ C:\wamp64
C:\wamp64\www
WAMP Log file is inside this folder:
C:\wamp64\logs

Check PHP Version

You can check the PHP version by opening the localhost when WAMP
server is running.
It will show the PHP Version.
Change the PHP Version
Open the WAMP Menu -> PHP -> Versions
You can change the PHP version from here.

Check MySQL Version

Open the WAMP Menu -> SQL -> Versions


You can change the SQL version from here.
Check phpMyAdmin Version

Open the WAMP Menu -> phpMyAdmin

Check Apache HTTP Version


Open the WAMP Menu -> Apache-> Versions
You can change the Apache version from here.

1.2 Echo
First PHP Program php file name should end with “.php ” extension You
should write the php code with in this starting and ending symbols. <?php ?>

<?php – tells server to interpret the code from here ?> – server will stop
interpreting the code. You should write the PHP code inside this block <?php
//PHP CODE ?> SYNTAX: <body> <?php ?> </body> All the statements
you write between the php block should end with “;” Add semicolor ‘;’ at
the end of the line. Step 1: Create the php file Goto Folder:
C:\wamp64\www Create Folder: \php\basics\echo\ex1 Final Folder:
C:\wamp64\www\php\basics\echo\ex1

Create file with name: index.php


Folder: C:\wamp64\www\php\basics\echo\ex1
Step 2: Add the code in index.php
You can use the Brackets Software to open the file.
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Page Description">


<title>Page Title</title>
</head>
<body>
<h1>Heading</h1>
<p>Paragraph Text</p>
<!-- PHP Code -->
<?php echo "Hello PHP!"; ?>

</body>
</html>
Step 3: Access the index.php from browser
Type the URL: http://localhost/php/basics/echo/ex1/index.php
Step 4: Understanding echo
echo is a function to print the data on the browser.

There is no parenthesis () required to call the method and pass data to the
method.

echo “some text to print”;


echo ‘some text to print’;

You use single quote or double quotes and statement should end with semi
colon “;”.

You even use print function


print “some text to print”;
print ‘some text to print’; Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Learning PHP"> <title>Echo - PHP</title>


</head>
<body>
<h1>How to Print on the Browser with PHP</h1>
<p>You can use echo and print functions to print!</p>

<!-- PHP Code -->


<?php echo "This is message you see printed with echo function"; ?>
<p><?php echo "I am inside the paragraph"; ?></p>

<h2> <?php print "Called from h2 tag"; ?>


</h2>
</body> </html>
Live Preview

Exercise 1
Download the Exercise 1

Exercise 1: Put the echo inside the <head> <script> tag and print alert(‘This
is called from php’);
See if the alert works?

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Write all the below HTML content using the php echo.
<h1>Heading</h1>
<p>Paragraph Text</p>
<ul>

<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>

</ul>

Live Preview

1.3 Hello Program with PHP

Hello Program
You should know the following things:
How to write and Execute the php Code.
How to start and stop WAMP Server.
How to view the php file from the browser.
Importance of ‘www’ folder in WAMP Folder
You can execute the php code only from the ‘www’ folder inside the
c:\wamp64 folder.
Write a simple hello program with the following files:
index.php
css include
js include
Use css style file
Write one Function in the Javascript and use it.
Print some text with the php echo function.
Sample Example
Download the Example
index.php
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Learning PHP"> <title>Hello World Program!</title>
<!-- Include CSS file -->
<link rel="stylesheet" type="text/css" href="styles.css" media="screen" />
<!-- Include JS File -->
<script type='text/javascript' src="scripts.js"></script>
</head>
<body>
<h1>Welcome to PHP Application</h1>

<div>
<!-- on hover on this link to get a red line -->
<a href="#" onclick="greet('Welcome to PHP'); ">Click Me!</a> </div>
<hr>

<div>
<?php

echo "Hello World PHP! This is printed with the two and
multiple lines without any issues.";

?> </div>
</body> </html>
styles.css
a:hover{
text-decoration: underline; text-color: red;

}
h1 { text-align: center;
}

scripts.js
function greet(message){ alert(message);
}

Live Preview

Exercise 1
Download the Exercise 1
Exercise 1: Print the <body> tag with echo.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Write the complete HTML page with echo.
Understand that you can write anything on the page with echo.

Live Preview

1.4 Comments

Usage of Comments You can use the special notation to comment the code
inside the php.

Comments helps to document about the code with a single or multiple line.
Comments are ignored by the Web Server and it is not displayed and not sent
to the browser.
You will not see php comments in the final HTML output.
There are two types of Comments in PHP:

Single Line Comments


Multi Line Comments
// – This is Single Line Comments. Use to comment one line. # – This is
Single Line Comments. Use to comment one line. /* – is used to indicate the
comments are starting. */ – is used to indicate the comments are ended.
Anything between /* and */ will not be executed by the server. Browser will
never see php comments because it is ignored by the server. SYNTAX:
<body> <?php // This is a Single Line Comments

# This is also a Single Line Comments /* This is a multi line comments


which you cannot see on the browser */ ?> </body> Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Learning PHP"> <title>Comments PHP</title> </head>
<body>
<?php
//This is Single Line Comments
# This is also a Single Line Comments

/*
* This is a multi line comments * can go many lines.
*/

?> </body> </html>


Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Put the php opening tag on top and start the multi line comments
and then close it at the end of HTML.
Guess the output.
Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Start the opening /* at the start of the HTML page and do not
close it. See if it raise any issue.

Live Preview

1.5 Functions
Usage of Fuctions
Functions is a block of statements that performs an action.

You can pass parameters to functions and it can return a value from the
function using “return ” keyword.

Syntax of Function Declaration:


function nameOfFunction(Parameters){
return someValue;
}
Example 1:

function area($width, $height){ return width * height; } echo “Area: ” .


area(10,20); . – Dot character is used to append two strings together. Sample
Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Learning PHP"> <title>Functions PHP</title>


</head>
<body>
<?php

// Print message using functions function printMessage(){


echo "<h1>Welcome to PHP</h1>"; }
//Return value from functions function add($a, $b){
return $a + $b;
}
// using "." to append data.
echo "Addition of two value: " . add(5, 10 );
?>
<?php printMessage(); ?>
</body> </html>

Live Preview
Exercise 1
Download the Exercise 1

Exercise 1: Define a add function in <head> section and use them in the
<body> section.

Live Preview
Exercise 2
Download the Exercise 2
Exercise 2: Create two functions and call one function from another
function.
Live Preview

2. DATA BASICS
2 Data Basics
2.1 Variables

Usage of Variables Variables are used to store information which are used
inside the program.
Variables in php are defined with dollar ($) sign in front of it.

Here are the rules for defining the Variables:


Variable should start with dollar($) sign. Example : $message. Letters,
numbers and underscore is allowed inthe variable name. After $ it should not
be a number. Example: $123name is wrong. Variables are case sensitive.
$message and $Message are not same.
Examples of Variables:
$index = 0;
$firstName = ‘WPFreelancer’;
$firstName = “WPFreelancer”;

$price = 10;
$price = 10.50;
$result = true;
$fullName = $firstName;
$ is used to indicate it is a variable.
= is the assignment operator used to assign the value to the variable. ;
semicolor is used to end the assignment statement.
Showing variable with echo
$siteName = “WPFreelancer”;
echo “This is the $siteName for WordPress”;
echo “This is the site name” . $siteName;

You can add the variables inside the double quotes only with the variable
names.

“.” DOT symbol can be used to add the variable to the strings. Sample
Example
Download the Example
<!DOCTYPE html> <html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Page Description"> <title>Variables</title>


<?php

//Declaring & Initalizing a Variable $message = "";


//Assigning value to the Variables $message = "Say Hello to Variables!";
//Displaying the Variables via the Javascript
echo "<script>console.log('" . $message . "');</script>";
?>
</head>

<body>
<h1>Variables</h1> <?php
$counter = 100; ?>
</body> </html>

echo "This is counter: $counter <br>"; echo "counter: ". $counter . "<br>"; echo 'This is the message -
$message <br>'; echo "This is the message - $message <br>";

Live Preview

Exercise 1
Download the Exercise 1

Exercise 1: Define all the Variables and Initialize them in the head section
and then display them in the body section.
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Write a function to add two strings with a “,” and return the new
string. call this function from body.

Live
Preview

2.2 Strings
Usage of String
Strings in PHP can be enclosed with Single Quote or Double Quotes. You
can use Single quotes inside the double quotes and vice-versa. . – DOT
Symbol is used to concatenate two strings together.

Variable when used inside the Double Quote then it will resolve into the
variable value.

This is called as Interpolation .


Interpolation of Variables only happens with Double Quotes and it does not
work with Single Quotes.

That’s why you must always use Single Quotes and only use Double Double
quotes when you need interpolation feature.

Define a Variable with NULL


$message = NULL;
or
$message = null;
NULL or null is a special keyword that is used to define a empty variable.
String Examples
$firstName = ‘WPFreelancer’;
$firstName = “WPFreelancer”;
$fullName = $first . ” – ” . $last;
$fullName = “$first – $last”;
$places = “”; //Empty String
$numPrice = 10.20;
$SubTotal = “Price: ” . $numPrice;
Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>String</title>
</head>
<body>
<h1>String</h1>
<?php

$fullName = 'WPFreelancer'; $site = "http://$fullName.com/"; echo "Visit us at $site <br>";

$message = "Welcome to"; echo $message . " " . $site; ?>


</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Convert a string to uppercase and lowercase. Display the text on
body.

Lowercase Function: strtolower ( $variable );


Uppercase Function: strtoupper ( $variable );
Example: $site = strtolower( $site );
Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Substring “WP” from “WPFreelancer” word using the String


function.
substr($variable, startIndex, length);
Example: $newValue = substr($fullName, 0, 2);

Live Preview

2.3 Numbers

Usage of Numbers Numbers can also be called as Integers. Integers are


positive or negative numbers.

Floating number is represented with number separated with “.” as decimals.


So, there are two types of numbers in PHP:
Integers
100
-200
Floating Point
10.34
Numbers are not wrapped with quotes or they do not include “,”

You can append the – (minus) symbol in front of the number to indicate it is
negative number.

Most common methods used with Integer:


round() – This will round the decimals
intval() – This will convert string integer to integer.
Examples:
$price = 10;
$total = 10.20;

Sample Example
Download the Example
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Numbers</title>
</head>

<body>
<h1>Numbers</h1> <?php

$length = 10; $breath = 10;

$area = $length * $breath;


echo "Area: $length x $breath = $area"; ?>
</body>
</html>

Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Write a function to round a given decimal number and display
the output.
Tips: Use the round(value)

Live Preview
Exercise 2
Download the Exercise 2

Exercise 2: Convert String to Integer and add two string numbers and add
two integers numbers.
Live Preview

2.4 Arrays

Usage of Arrays Arrays is a data type that holds one or more items called as
elements.

Each element could be combination of data types.


length is used to indicate the number of elements in the array. Every element
of the array can be accessed with an index number. First element of Array
starts with 0 index.
Define an Array
$arrayName = array( $value1, $value2 );
Examples:
$colorName = array(‘red’, ‘white’, ‘yellow’);

$newColors = array();
$newColors[0] = $colorName[0]; $newColors[1] = $colorName[1];

$age = array(10, 40, 34);


$studentage[0] = $age[0];
$studentage[1] = 50;

Print Arrays
print_r($arrayName);
Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description">
<title>Arrays</title>
</head>

<body>
<h1>Arrays</h1>
<?php

//Define an Array $colorNames = array('red', 'green', 'white');

//Print an Array
print_r($colorNames); echo "<br>";

//Loop thru the arrays


foreach ($colorNames as &$value) { echo $value . "<br>";
}
//Define an Empty Array $age = array();
$age[0] = 10;
$age[1] = 20;
$age[3] = 30;

//Print Array print_r($age);


?>
</body> </html>

Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Create an Array with String, Number and Boolean and display
them.
Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: Do the following exercise with Arrays


Define an Empty Array
Add 1 Element Display the Length
Add 2 Element
Show the two Elements
Show the Length of the Array
Use count( $arrayName) method to show the length of an array.
Live Preview
2.5 Objects

Usage of Classes and Objects Class is a collection of Variables and


Functions together.

Object is an instance of a Class used to store values in the class variables and
access them via the functions.
Instead of defining methods and variables separately you can create a class
and store them.

You need to create an instance of class to access it.


-> symbol is used to access the variable or methods in the object.

$this is a special object that will help to access the existing object of a class.

Class Syntax:
class Student{
private $id, $name, $age;

public function __construct($id, $name, $age){


$this->id = $id;
$this->name = $name;
$this->age = $age;
}

public function getName(){


return $this->name;
}

public function setName($name){


$this->name = $name;
}

public function getStudentDetails(){


$details = “ID: ” . $this->id . ” NAME: ” . $this->name . ” AGE:” .
$this>age;
return $details;
}

}
Create Instance of Class

$studentObj = new Student(1, “WP”, 20);


echo $studentObj->getStudentDetails();
Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Page Description"> <title>Classes and


Objects</title>
<?php
class Student{
private $id, $name, $age;

public function __construct($id, $name, $age){ $this->id = $id;


$this->name = $name;
$this->age = $age;

public function getName(){ return $this->name;


}
public function setName($name){ $this->name = $name;
}

public function getStudentDetails(){ $details = "ID: " . $this->id . " NAME:


" . $this->name . " AGE:" . $this->age;
return $details;
}
} ?>
</head>

<body>
<h1>Classes and Objects</h1>
<?php

$studentObj = new Student(1, "WP", 20); echo $studentObj-


>getStudentDetails(); ?>
</body> </html>

Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Create a Product Class with productName and price variables


and create one function to access the price.
Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: Create a Calculator class and pass two values and create add and
minus function.

Live Preview
2.6 Constants

Usage of Constant Constant are like variables but once you define the
constant with a fixed value you cannot change it later.
Constant variables values are fixed and cannot be changed later. define() is a
method used to define a constant. constant does not need $ dollar because it
is not like a variable. Example:
define(‘AGE’, 20);
echo AGE;
You don’t need $ to access it.
Typically, constant is defined in UPPERCASE to differentiate easy between
variables and constants.
Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Page Description">


<title>Constants</title>
<?php

//Define a Constant
define('MESSAGE', "Welcome to PHP!"); define('AGE', 20);

?> </head>

<body>
<h1>Constants</h1>
<?php

echo MESSAGE . ". I am " . AGE . " years old!"; ?>


</body>
</html>
Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Define String, Number and Boolean Constant and display them.

Live Preview

Exercise 2

Download the Exercise 2


Exercise 2: Try to change the value of Constant and observe the error.

Live Preview
2.7 Boolean

Usage of Boolean Boolean Variables helps to make decisions or store a


decision based on an expression.

Boolean values can be true or false.


You can use boolean variable as a condition to check if the value is true or
false.

$result = 2 > 1;
$message = ($result) ? “CORRECT”: “WRONG”;
Sample Example

Download the Example


<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description">
<title>Constants</title>
</head>

<body>
<h1>Constants</h1>
<?php

$result = 2 > 1;
$message = ($result) ? "CORRECT" : "INCORRECT"; echo "Is 2 > 1? -
$message";

?>
</body>
</html>

Live Preview

Exercise 1
Download the Exercise 1

Exercise 1: Guess the Output.

Live Preview

Exercise 2

Download the Exercise 2


Exercise 2: Create a Constant and use the constant to check the condition.

Live Preview
2.8 Date and Time

Usage of Date and Time


date() is a class library available to access the date.
We need to pass the format of the date to get the system date. $today =
date(‘Y-m-d’); //2018-01-01
$today = date(‘l, F, d, Y’); //Thusday, Jun 21, 2018
By default, $today will have user system date.
TimeStamp:
$todaytime = time();
echo $todaytime();
Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Date and
Time</title>
</head>
<body>
<h1>Date and Time</h1>
<?php
echo "Today is " . date('Y-m-d');
echo "<br>";
echo "Today is " . date('d/M/Y');
echo "<br>";
$formatdate = date('l, F d, Y');
echo "Full Length Date: " . $formatdate;
?>
</body>
</html>

Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Print tomorrow date with this function


strtotime(‘tomorrow’);
Format the Date with date function
echo date( 'd/M/Y', strtotime('+5 days'));

Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: Print the ‘first day of next month ‘ and format with date
function.
Tip:
$futuredate = strtotime('first day of next month');

Live Preview

3. EXPRESSIONS
3 Expressions
3.1 Assignments
Usage of Assignment Expressions

Operators are used to perform some operation on the variables and they are
represented with some symbols.
Expressions are evaluated into a result value or final value or single value.

There are couple of Expressions:


Assignment Expressions
Arithmetic Expressions
Comparison Expressions
Logical Expressions
We will look at Assignment Expressions in this topic.

Expressions uses Operators to perform the activity.


= is the assignment operator which assigns the value to the variable.
message = “something”; is a assignment expression that assign value to the
message variable.
Compound Assignment Operators

Compound assignment operators helps to do more than one operators job. It


combines two operators together to perform an action.
Compound Assignment Operators are:
.= +=
-=
*=
/=
%=
$message = ‘WP’. ‘Freelancer’; OR

$message = ‘WP’;
$message .= ‘Freelancer’; counter += 1;
counter = counter + 1;
counter -= 1;
counter = counter – 1;
counter *= 1;
counter = counter * 1;
Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8"> <meta name="viewport" content="width=device-


width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Assignment
Expressions</title>
</head>

<body>
<h1>Assignment Expressions</h1>
<?php

$firstName = "WP";
$lastName = "Freelancer";
$fullName = $firstName . ", " . $lastName; echo "Name $fullName <br>";
$counter = 10;
echo "Counter: $counter <br>"; $counter += $counter;
echo "Counter+=: $counter <br>"; $counter -= 10;
echo "Counter-=: $counter <br>";

?>
</body> </html>

Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Guess the difference between the two assignments. $counter++


and $counter += counter;

Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: What is the result of $counter -= $counter and $counter -= 10;


when $counter = 10;
Live Preview
3.2 Arithmetic

Usage of Arithmetic Expressions


Expressions are evaluated into a result value or final value or single value.

There are couple of Expressions:


Assignment Expressions
Arithmetic Expressions
Comparison Expressions
Logical Expressions
We will look at Assignment Expressions in this topic.

Expressions uses Operators to perform the activity.


+ is the arithmetic operator which is used to perform mathematics
calculations.

Arithmetic Operators are:


+

*
/
%
++

//Increment by 1
counter++ ;
counter = counter + 1;
//Decrement by 1
counter— ;
counter = counter – 1;

Order of Precedence:
++

*/%
+–
Anything mentioned in () will get higher precedence over anything. (5 + 2) *
2; //Result – 14
Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Arithmetic
Expressions</title>
</head>
<body>
<h1>Arithmetic Expressions</h1> <?php
$counter = 10;

echo "Counter: $counter <br>"; $counter++;


echo "Counter++: $counter <br>";

$counter = 10;
echo "Counter: $counter <br>"; $counter--;
echo "Counter--: $counter <br>";
$counter = (10 - 5) * 2;
echo "(10 - 5) * 2: $counter <br>";

?>
</body> </html>

Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Find a 15 is even or odd using Modulus (%) symbol. $counter =


15%2;
Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: Try to apply the ++ to the following things: 1++; echo


“$counter++”;
++1;
$message = “Hello”;
$message++;
$result = true;
$result++;
Some of the things won’t work so comment them and run the code.

Live Preview
3.3 Comparison

Usage of Comparison Expressions


Expressions are evaluated into a result value or final value or single value.

There are couple of Expressions:


Assignment Expressions
Arithmetic Expressions
Comparison Expressions
Logical Expressions
We will look at Comparison Expressions in this topic.

Expressions uses Operators to perform the activity.


Comparison expression always evaluate into a true or false value.

> is the comparison operator which compares the two values. message
variable will be have a true or false.
Comparison Operations:
< – Less than
> – Greater than
== – Equal to === – Equal value and Equal Data Type
!== – Not Equal Value and Equal Data Type
!= – Not Equal
>= – Greater than and Equal
<= – Less than and Equal
Conditional (Ternary) Operator

PHP has a conditional operator that assigns a value to a variable based on


some condition.
$variablename = ($condition) ? value1:value2
$counter = (10<=10) ? 10 : 0;
Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Comparison
Expressions</title>

</head>
<body>
<h1>Comparison Expressions</h1> <?php

$counter = 10 == 10;
echo $counter; //1 = true and 0 = false

echo "<br>";
$result = 15 <= 21;
$message = ($result)? "YES": "NO"; echo $message;

?>
</body> </html>
Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Learn how to compare NULL in the string with === operator.

Live Preview

Exercise 2

Download the Exercise 2


Exercise 2: Find empty string from 2 strings.
Live Preview
3.4 Logical

Usage of Logical Expressions


Expressions are evaluated into a result value or final value or single value.

There are couple of Expressions:


Assignment Expressions
Arithmetic Expressions
Comparison Expressions
Logical Expressions

We will look at Logical Expressions in this topic.

Expressions uses Operators to perform the activity.


Logical Operators are used to check the if the condition is true or false based
on many conditions.

&& is the logical operator which checks left side and right side value and
decides if the condition is true or false.

(5 > 3) – true
(8 < 5) – false
true && false = false

result variable will have false boolean value.


Logical Operations:
&& – AND
|| – OR
! – NOT
Order of Precedence

Order of precedence decides which operates evaluates first. NOT


AND
OR
Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Logical
Expressions</title>
</head>

<body>
<h1>Logical Expressions</h1> <?php

$input1 = 10;
$input2 = 20;
$result = ($input1 < $input2) || ($input1 == $input2);

echo $input1 . " <= " . $input2 . " is " . $result; ?>
</body> </html>
Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Guess the Output from below code.

Live Preview

Exercise 2

Download the Exercise 2


Exercise 2: Guess the output from the below code.

Live Preview

4. STATEMENTS

4 Statements
4.1 If Statements

Usage of if Statements if statement are used to check a condition and make


a decision based on the result of the condition.
It can choose some action when the condition is true and also take some
action when it false.
You can nest multiple conditions together and decide to choose one action
based on multiple conditions.

Syntax:
if ( condition1 ){
// Statements
} else if( condition1 || condition2 ){
// Statements
} else {
// Statements
}
Example 1:

if( $marks > 35 ){ echo “Your’re Passed!”;


}else{
echo “Better Luck Next Time!”;
}
Example 2:
if( $marks > 35 && $marks < 60 ){ echo “You are Passed with Grade C”;
}else if ( $marks > 60 && $marks < 80 ){ echo “You are Passed with Grade
B”; }else if ( $marks > 80 ){
echo “You are Passed with Grade A”; }else{
echo “Try Again!”;
}

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Page Description"> <title>If


Statements</title>
<?php
$dayOfWeek = "Wednesday";
$result = "";
$dayOfWeek = strtolower($dayOfWeek);

if( $dayOfWeek == 'monday' || $dayOfWeek == 'mon'){ $result = "First Day


of Week";

}else if( $dayOfWeek == 'tuesday' || $dayOfWeek == 'tue' ){


$result = "Second Days of Week";
}else if( $dayOfWeek == 'wednesday' || $dayOfWeek == 'wed' ){
$result = "Mid Week";
}else if( $dayOfWeek == 'thursday' || $dayOfWeek == 'thurs'){
$result = "Preparing for Weekend"; }else if( $dayOfWeek == 'friday' ||
$dayOfWeek == 'fri'){
$result = "It's Friday!";
}else if( $dayOfWeek == 'saturday' || $dayOfWeek == 'sat' ){
$result = "Enjoying Day!";
}else if( $dayOfWeek == 'sunday' || $dayOfWeek == 'sun'){
$result = "Resting Day!"; }else{
$result = "Cannot find that Value!"; }
?>
</head>

<body>
<h1>If Statements</h1>
<?php

echo "This is the result: " . $result;

?>
</body> </html>
Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Set the inputVariable number between 1 to 10 and check if that


variable is between 1 to 10 with if Statement.

Live Preview

Exercise 2

Download the Exercise 2


Exercise 2: Enter the age of the user in the InputVariable and decides if he is
kid, man (age > 21) or senior citizen (age > 55).

Live Preview
4.2 Switch Statements

Usage of Switch Statements switch statement are used to check a value and
make a decision based on the result of the value matching.

Syntax:
switch( $variable ){
case value:
//Statement
break;
case value:
//Statement
break;
default:
//Statement
break;
}
Example 1:
switch ( $dayOfWeek ){
case ‘Mon’:
echo “Welcome Monday”;
break;
case ‘Tuesday’: echo “Welcome Tuesday”; break;
default:
echo “Try Again!”;
break;
}

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Page Description"> <title>Switch


Statements</title>
<?php

$dayOfWeek = "Friday";
$result = "";
$dayOfWeek = strtolower($dayOfWeek);

switch($dayOfWeek){ case 'monday': $result = "First Day of Week"; break;

case 'tuesday':
$result = "Second Days of Week"; break;

case 'wednesday':
$result = "Mid Week";
break;

case 'thursday':
$result = "Preparing for Weekend"; break;

case 'friday':
$result = "It's Friday!";
break;

case 'saturday':
$result = "Enjoying Day!";
break;

case 'sunday':
$result = "Resting Day!";
break;

default:
$result = "Cannot find that Value!"; }
?>

</head> <body>
<h1>Switch Statements</h1>
<?php

echo "This is the result: " . $result; ?>


</body>
</html>

Live Preview

Exercise 1
Download the Exercise 1

Exercise 1: Set InputVariable number between 1 to 10 and check if the


variable is between 1 to 10 as requested with the switch Statement.

Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: Set a Variable to user age and decides if he is kid, man (age >
21) or senior citizen (age > 55). Use the Switch Statement.

Tips:
switch(true){
case ($input > 21):
//Statements
break;
}
Live Preview
4.3 While Statements

Usage of While Loop While statement are used to loop a block code and run
it until a condition is met.

Running the same block of code until the condition is satisfied.

Syntax:
while( condition ) {
//Statements
}
Example 1:
$counter = 0;
while ( $counter < = 10 ){
$counter++;
}
Syntax:
do{
//Statement
}while ( condition );

Example 1:
$counter = 0;
do{
$counter++;
} while ( $counter < = 10 );

break; – break is the keyword used to break the loop and come out of the
loop and execute statements after the while loop.

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">

<meta name="description" content="Page Description"> <title>Boolean


Expressions</title>
<script>

var result = 2 > 1;


var message = (result) ? "CORRECT": "WRONG";
</script>

</head> <body>
<h1>Boolean Expression</h1>

<script type="text/javascript"> document.write(message);


</script>
</body>
</html>
Live Preview

Exercise 1
Download the Exercise 1

Exercise 1: Define CONSTANTS INPUT1 and INPUT2 and print all the
numbers between them. Print only maximum of 10 numbers.

break; – is a keyword that can be used in the loop to break from the loop.
continue; – is a keyword that can be used in the loop to continue the loop by
skipping the below statements.

Tip:

if( $counter >= 10){


break;
}

Live Preview
Exercise 2

Download the Exercise 2

Exercise 2: Define TWO CONSTANT and print EVEN numbers only


between them. Print only maximum of 10 numbers.

Live Preview
4.4 For Statements

Usage of For Loop


for Loop are used to loop a block code and run it until a condition is met.

Running the same block of code until the condition is satisfied.

Syntax:
for( counter initialization; condition; increments ) {
//Statements
}

Example 1:
for($counter = 0; $counter <= 10; $counter++){ echo $counter;
}

for($counter = 0, $input1 = 10; $counter <= 10; $counter++, $input1++){


echo $input1;
}

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>For
Statements</title>
</head>

<body>
<h1>For Statements</h1>
<?php

for($counter=0; $counter<=10; $counter++){ echo "For Counter: " .


$counter . "<br>" ; }
?>
</body> </html>

Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Define two constant number with default value and print all the
numbers between them. Print only maximum of 10 numbers.
break; – is a keyword that can be used in the loop to break from the loop.
continue; – is a keyword that can be used in the loop to continue the loop by
skipping the below statements.

Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: Define two constant with default value and print EVEN
numbers only between them. Print only maximum of 10 numbers.
Use the Loop like this:

Live Preview

5. GENERAL
5 General
5.1 Exceptions

Usage of Try Catch Blocks There are 3 types of error you can find in PHP:
Syntax Errors
Runtime Errors
Logic Errors

Syntax errors is where you forgot to follow the rules of PHP. It will cause
error when you execute the program.

Runtime Errors could be when it is running the program the PHP


interpreter could not understand how to proceed and throws and error.

Logic Errors are logically error that are cause because the program
instructions are not logically correct.
Exceptions in programming are referred as Runtime Errors.

When Runtime Errors happens there is a way to catch those errors and pass
it to the application and make a clean exit from the program.

This is called as Exception Handling.


The process of making sure the code will not break and if it does it know the
reason for it and make a clean exit.

To handle Runtime errors in the PHP we have try-catch blocks. Using this
we can catch the errors and decide what to do next.

SYNTAX:
try{
//Statements
}catch(Exception $exceptionObj) {
//Statments
}
Example:
try {
$firstName = “”;
if( $firstName == “” ) throw new Exception( “Name is empty” ); }catch
(Exception $e){
echo “Message: ” . $e->getMessage();
}finally {
echo “This is from the Finally Block”;
}
try {} block will have all the statements

throw is a keyword to throw an error from the program. Once the program
throw an error it will stop processing the next steps. It will jump to catch {}
block.
catch {} block will be executed once the throw is called. The program will
execute out from the catch block safely.

finally{} block will execute every time irrespective of error or not. It is good
place to close all open connections. Handle clean exit.
Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description">
<title>Exceptions</title>
</head>

<body> <h1>Exceptions</h1> <?php


try{
throw new Exception("Error in the try block!");
}catch(Exception $e){
echo "Exception: ". $e ->getMessage();
}finally{
echo" <br> This is from the Finally Block!";
}
?>
</body> </html>

Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Define one constant number and raise error if the number is not
integer.
Tip:
if( !is_numeric(INPUTVALUE ) )

Live Preview

Exercise 2

Exercise 2: Define a number between 1 to 100. Show the following message


on the page:
If the input is between 1 to 100 – less than 100.
If the input is greater than 100 – greater than 100.
If the input is not number – throw an error
Live Preview
5.2 Debug

Step 1: Write PHP Code with Errors


Try the following Errors:
$inputValue = 10;echo inputValue;
echo “This is a String” + “another String”;

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description">
<title>Debugging</title>
</head>

<body>
<h1>Debugging</h1> <?php

$inputValue = 10; echo inputValue;


?>
</body> </html>

Live Preview 1

Exercise 1:
Add Sum() method in the php file and do not create that function. This will
cause the program to fail.
Exercise 2:
Write echo statement before the sum() method and echo after the sum()
method.

Find out the error by seeing the echo messages.


Step 2: Debug
Using echo you need to write the trace logs.
See which the last echo that was executed.

5.3 Files
Usage of Files

You can read files on the server using the PHP libraries. Modes used during
opening the file:
rb – Open the file for reading purpose.
wb – Create a new file and if already exists then it overwrite it. ab – Create
the file and append the data is already existed. xb – Create a new file and if
already exists then it does not create. Here are the methods to open and close
a file
fopen ($path, $mode)
fclose ($file)
feof ($file) – To check if the file is at the end.
Method to read and write into the file:

fread ($file, $length) – length is used to specify number of bytes to read.

fgets ($file) – Read a line


fwrite ($file, $data) – Write the $data value to the file.
Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8"> <meta name="viewport" content="width=device-


width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Files</title>
</head>

<body>
<h1>Files</h1> <?php

//Create a local file and name it "readme.txt"

/*
* READ A FILE - rb mode
*
*/

$file = fopen('readme.txt', 'rb'); $line = "";


while( !feof($file) ){

$line = fgets($file);
echo $line;
}
fclose($file);

/*
* WRITE A FILE - wb mode *
*/

$file = fopen("newfile.txt", "wb");


fwrite( $file, "<br><h1>It is a long established fact that a reader
will be distracted by the readable content of a page when looking at its
layout.</h1>");
fclose( $file );
?>
</body> </html>
Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Write a new file newfile.txt with some content. Read the same
file and display the output on the browser.

Live Preview

Exercise 2

Download the Exercise 2


Exercise 2: Append some text to an existing file with ‘ab ‘ mode.
Live Preview
5.4 Includes & Requires

Usage of Includes and Requires


PHP allows to break the code into small pieces of file and then include then
in the main page.

These are statements that can be used:


include
include_once
require
require_once include and require both help to include the file into another
file.

If the included file is not available then include statement will ignore and
continue to execute the other part of the code. if the included file is not
available then require statement will stop the execution of the program.
require_once or include_once will not import if the file is already included.
Sample Example

Download the Example

File: index.php

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description">
<title>Includes</title>
</head>

<body>
<h1>Includes</h1> <?php
include 'functions.php'; echo add(1, 2);
require 'display.php'; ?>

</body>
</html>
File: functions.php
<?php

function add($a, $b){


return $a + $b;
}
?>
File: display.php
<?php
echo '<br><h1>This is displayed from display.php</h1>'; ?>

Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Use the same code from above and delete the display.php and
functions.php in this exercise and see the error. Observe the Warning and
Fatal Error. Warning is coming from include and Fatal Error from require.

Live Preview
Exercise 2

Download the Exercise 2

Exercise 2: Put all the HTML code in index.html and include that file in the
index.php

Live Preview
5.5 Libraries

Usage of Libraries You can create a library file and put all the functions
that you commonly use in this library file.

This is the common practice for any web development where you break the
main program into smaller chunks of code and then include them in the main
program.

You can use include statement to import this functions file in your page so
that you can access those functions.
Sample Example

Download the Example

<!DOCTYPE html> <html>


<head>
<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initialscale=1.0">


<meta name="description" content="Page Description">
<title>Libraries</title>
</head>

<body>
<h1>Libraries</h1> <?php

include 'calculator.php';
define('INPUTVALUE1', 50); define('INPUTVALUE2', 23);
echo 'Calculator : '. INPUTVALUE1 . ' AND ' . INPUTVALUE2 . '<br>';

echo 'Addition: '. add(INPUTVALUE1, INPUTVALUE2) . '<br>'; echo


'Minus: '. minus(INPUTVALUE1, INPUTVALUE2) . '<br>';

echo 'Multiply: '. multiply(INPUTVALUE1, INPUTVALUE2) . '<br>';


?>
</body> </html>
FileName: functions.php <?php

function add($a, $b){ return $a + $b;


}

function minus($a, $b){ return $a - $b;


}

function multiply($a, $b){ return $a * $b;


}

?>

Live Preview

Exercise 1
Exercise 1: Create your own Library and use it. Continue using it for other
projects as well.
Follow this practice to split the project into small files and include them.

6. FORMS
6 Forms
6.1 GET

Usage of Form GET Method GET is type of method used by the form to
pass the form data to the page that is mentioned in the action of the form.
GET method will send the data in the url.
When you define a form here are the important things:
action attribute – This define to which file this form data has to be sent to.

method attribute are of two types – GET and POST.


GET means data is visible in the URL bar.
POST means data is hidden.

Using GET we can send limited data and using POST we can send huge
data.

<input> type has a name attribute which helps to define the name of the
element. This name is like a variable that holds the data what user enters.
name attribute for form element is posted to the next page.

<input type=”submit” > will show a submit button when clicked the form
will be submit the data the file. This action is taken care by the browser.

How to Read the GET Variables from the URL


If the URL is something like:

http://site.com/display.php?input_text =hello&input_email =test@tes t.com


$text = $_GET[‘input_text ‘];
$emailid = $_GET[‘input_email ‘];
URL will have the name=value pairs separated with &.

$_GET[] is an array that gets created automatically with the GET parameters
which you can access it and check if any value is there or not.

$_GET[] is super global variable which is always available even it is empty


it is available.
When you click the submit button the form data is passed to display.php
which read the parameters and display the output. Browser will also go from
index.php page to display.php page.
Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Forms -
GET</title>
</head>

<body>
<h1>Form - GET</h1>
<form action="display.php" method="get">
<fieldset>

<legend>Student Enquiry Form</legend> <p>


<label for="input_text">Text:</label>

<input name ="input_text" type="text" placeholder="Text">

</p>
<p>
<label for="input_email">Email:</label>

<input name ="input_email" type="email"


placeholder="test@domain.com">

</p>
</fieldset>
<p><input type="submit"> <input type="reset"></p>

</form>
</body>
</html>
FileName: display.php

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Forms -
GET</title>
</head>
<body>

<h1>Form - GET</h1>
<a href="index.php">Back to Home Page</a><br> <?php

$name = $_GET['input_text']; $email = $_GET['input_email'];

echo "Name: $name and Email: $email"; ?>


</body>
</html>
Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Create a Form that accepts two numbers and show the
calculation of those two numbers on another page.
Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: Show the result on the same page and redirect to same page.

Tips: Check if the values are not empty


if( !empty( $_GET['input_text1'] ) && !empty( $_GET['input_text2'] ) ){

Live Preview
6.2 POST

Usage of Form POST Method


POST is type of method used by the form to pass the form data to the page
that is mentioned in the action of the form.
POST method will send the data as an attachment. It is not visible in the
URL.
When you define a form here are the important things:
action attribute – This define to which file this form data has to be sent to.

method attribute are of two types – GET and POST.


GET means data is visible in the URL bar.
POST means data is hidden.

Using GET we can send limited data and using POST we can send huge
data.

<input> type has a name attribute which helps to define the name of the
element. This name is like a variable that holds the data what user enters.
name attribute for form element is posted to the next page.

<input type=”submit” > will show a submit button when clicked the form
will be submit the data the file. This action is taken care by the browser.

How to Read the POST Variables


POST variable are not visible in the URL.

$text = $_POST[‘input_text ‘];


$emailid = $_POST[‘input_email ‘];

$_POST[] is an array that gets created automatically with the POST


parameters which you can access it and check if any value is there or not.

$_POST[] is super global variable which is always available even it is empty


it is available.
When you click the submit button the form data is passed to display.php
which read the parameters and display the output. Browser will also go from
index.php page to display.php page.
Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Forms -
POST</title>
</head>

<body>
<h1>Form - POST</h1>
<form action="display.php" method="post">

<fieldset>
<legend>Student Enquiry Form</legend> <p>

<label for="input_text">Text:</label> <input name ="input_text"


type="text" placeholder="Text">
</p>
<p>
<label for="input_email">Email:</label> <input name ="input_email"
type="email" placeholder="test@domain.com">

</p>
</fieldset>
<p><input type="submit"> <input type="reset"></p>

</form>
</body>
</html>
FileName: display.php

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Forms -
POST</title>
</head>
<body>

<h1>Form - POST</h1>
<a href="index.php">Back to Home Page</a><br> <?php

$name = $_POST['input_text']; $email = $_POST['input_email'];

echo "Name: $name and Email: $email"; ?>


</body>
</html>

Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Create a Form that accepts two numbers and show the
calculation of those two numbers on another page. Use POST Method.
Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: Show the result on the same page and redirect to same page. Use
POST Method.

Tips:
Check if the values are not empty

if( !empty( $_POST['input_text1'] ) && !empty(


$_POST['input_text2'] ) ){
Live Preview
6.3 Cookies

Usage of Cookies
Cookies are information that you can store at clients browser.

Cookies are stored in a file at the client system in name=value pair format.
Cookies helps to track what user is doing on the web page and send that
information to server so that server knows what client did on the web page.
For every request, browser sends the cookies to server and if there are any
changes to cookies then that information is also sent to the server.

Cookies helps to store information and capture the user actions on the web
page inside it. This information is then sent to server. Cookies last until the
browser is closed. We can also manually set the expiration time for any
cookie.

Some of the browser disable cookies in that case cookies will not work and
also user can choose to change browser setting to not store cookies.

Cookies can help to change the view of the page based on the user actions.
How to Set a Cookie

$name = ‘WPFreelancer.com’;
$value = 20;
$expire = strtotime(‘+1 year’);
$path = ‘/’;
//Its a name=value pair.
setcookie($name, $value, $expire, $path);

How to Get a Cookie


$_COOKIE[$cookie_name]
How to Delete a Cookie

By setting the time last year all the cookies with that name are deleted.
$expire = strtotime(‘-1 year’);
setcookie(‘WPFreelancer.com’, ”, $expire, ‘/’);

Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description">
<title>Cookies</title>
</head>

<body>
<h1>Cookies</h1> <?php

$cookie_name = "user";
$cookie_value = "WPFreelancer";

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");


if(!isset($_COOKIE[$cookie_name])) { echo "Welcome '" . $cookie_value .
"'. Nice to meet you!";
} else {
echo "Hey, '" . $cookie_value . "' you are back<br>"; echo "Value is: " .
$_COOKIE[$cookie_name];
}

?>
</body> </html>
Live Preview

Exercise 1

Download the Exercise 1

Exercise 1: Ask user to enter the cookie name on one page and check on the
other page if the cookie is new or old.

Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: Add and check the cookie from same page.


Live Preview
6.4 Session

Usage of Sessions

Sessions is an array that is stored at the server based on the session id.
session id are generated when the user first time visit the site and this session
id are stored in the cookie.

So, every time user make request to the server, this cookie is passed to the
server with the sessionid and based this session id server is able to maintain
an active session of the user.

If a session is already created for that specific user then PHP will not create
a duplicate session.

By default, PHP uses a cookie to store a session ID in each browser. Then,


the browser passes the cookie to the server with each request.

Start Session
session_start();
is used to start a session.
Create a Session Variable

session_start();
$_SESSION[“firstname”] = “WPFreelancer”;
Read a Session Variable
session_start();
echo $_SESSION[“firstname”];
Delete a Session Variable

session_start();
if(isset($_SESSION[“firstname“])){
unset($_SESSION[“firstname“]);
}

Sample Example
Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description">
<title>Sessions</title>
</head>

<body>
<h1>Sessions</h1> <?php

session_start();
//Create a Session
$_SESSION["firstname"] = "WPFreelancer";
echo $_SESSION["firstname"];
?>

</body> </html>

Live Preview

Exercise 1

Download the Exercise 1


Exercise 1: Delete the session and print it again.

Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: Create a form and accept a session value and store it and display
it.
Live Preview

7. Snippets
7 Snippets
7.1 Regex

Usage of Regex Regular Expression are special searching pattern that is


very powerful to search for matching patter in text strings.

To start using the Regular expression we need to get the data between
forward slash and then use the method preg_match() on the data and this
pattern to search.

You create a pattern and then use method preg_match() to match on the data.

preg_match() method will return true or false.


SYNTAX:
preg_match($pattern, $data);
$pattern = “/WP/’;
$sitename = “WP Freelancer”;
$found = preg_match($pattern, $sitename);
$found will have true or false.
Some patters:
. – Any Single Character
\w – Any Letter, number or underscore
\W – Any character
\d – Any Digit
\s – White Space Character
\S – Any Character that is not whitespace. Sample Example

Download the Example

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta name="description" content="Page Description"> <title>Regular
Expressions</title>
</head>

<body>
<h1>Regular Expressions</h1> <?php

$pattern = '/WP/';
$sitename = "WPFreelancer";
$found = preg_match($pattern, $sitename); echo $found;

?>
</body> </html>

Live Preview

Exercise 1

Download the Exercise 1


Exercise 1: Search incase sensitive search for the same string. Regular
Expression: $pattern = ‘/wp/i’;

Live Preview

Exercise 2

Download the Exercise 2

Exercise 2: Match a pincode p-104848 in the string. Regular Expression:


$pattern = ‘/p-\d/’;

Live Preview

8. PROJECTS
8 Projects
8.1 Save Student Registration Form Data to File

In this Project, you will write a simple application where user will his details
and when submitted the data is save in a text file in append mode.

Download the Exercise 1


Live Preview

EXERCISE 1:
The above program will throw error when checkbox is not checked. This is
on purpose.
You need find out first if the parameter exists in that array $_GET and then
assign the value to variable.
Use the empty method to check if the variable is empty before inserting.

EXERCISE 2:
Make a function to save the content and save it in functions.php Include the
functions.php file and call this function.

8.2 Online Test

In this Project, you will write a simple application online test with some
question. Once user provide the answer he immediately verify the result.

Download the Exercise 1


Live Preview

EXERCISE 1:
Change the $_GET to $_POST and perform the same operation.

EXERCISE 2:
Display the result on the next page.

8.3 Online Calculator

In this Project, you will write a simple calculator application where user will
enter the values and our program will calculate various math formulas.

Download the Exercise 1


Live Preview

EXERCISE 1:
Add some Math formulas and add to the table.

EXERCISE 2:
Add some styling to the table.
About this Book

About this Book

WORDPRESS is a CMS Software that is used to build and configure


Website. WORDPRESS is used to develop content rich website. This book
will help you understand how to development with WORDPRESS and also
learn how to work with Software.

Audience

This tutorial has been designed to meet the requirements of all those readers
who are keen to learn to build website with WordPress.

Prerequisites

This book assumes you have no prior knowledge on Programming


knowledge and assume you are at a beginner level.

How to use this Book

This book contains WORDPRESS Basics, Exercises and Examples which


are part of the PHP Bootcamp Program. This bootcamp has helped many
students to become PHP Full Stack Web Developer in Just 30 days.

>>>Check out more about this program here. ..


Copyright & Disclaimer

Copyright & Disclaimer

© Copyright 2019 by SrinivasIT.com.

All the content and graphics published in this e-book are the property of
SrinivasIT.com. The user of this e-book is prohibited to reuse, retain, copy,
distribute or republish any contents or a part of contents of this e-book in any
manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or
errors. SrinivasIT.com provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this
tutorial. If you discover any errors on our website or in this tutorial, please
notify us at contact@SrinivasIT.com .

Found Typos & Broken Link

If you found any typos and broken links in the course or book, then please
let me know using this email address.
contact@SrinivasIT.com

Support

You can reach me for technical discussions and other support related queries
from here.
support@SrinivasIT.com
Thanks for your support!

Free Courses
Learn HTML in 1 Hour
Learn CSS in 1 Hour
Learn JAVASCRIPT in 1 Hour
Table of Contents

About this Book .......................................................................................... 1


Audience...................................................................................................... 1
Prerequisites ............................................................................................... 1
How to use this Book ................................................................................. 1
Copyright & Disclaimer .............................................................................. 2
Found Typos & Broken Link ...................................................................... 2
Support ........................................................................................................ 2
1 WordPress Basics .................................................................................10
1.1 Welcome to WordPress?...........................................................10
1.2 What is WordPress?...................................................................12
1.3 What is Content Management System ...................................13
1.4 Website vs CMS Website...........................................................15
1.5 WordPress.org vs WordPress.com ..........................................18
1.6 Five Types of Website built with WordPress ..........................19
1.7 Five Types of Website cannot built with WordPress .............23
1.8 Alternative to WordPress CMS.................................................24
1.9 Benefits of Using WordPress....................................................26
2 Accounts Creation ................................................................................29
2.2 Create an Account with Gravatar ................................................38
2.3 Create an Account with Akismet..................................................43
3 WordPress Installation.........................................................................49
3.1 Install WordPress on Local Machine ...........................................49
3.2 Learnwp.xyz Website ....................................................................65
3.3 Login and Logout WordPress.......................................................65
3.4 Create Your Profile ........................................................................68
3.5 Gravatar Settings...........................................................................71
3.6 Create and Delete Users from WordPress .................................73
3.7 Check the WordPress Version & Upgrade..................................80
3.8 Allow or Block Subscribers to your Site ......................................82
3.9 Allow or Block Comments on your Site ......................................85
3.10 Allow or Block Google to Index your Site .................................86
4 WordPress Clean Up ............................................................................88
4.1 Clean up Themes...........................................................................88
4.2 Clean up Plugins ............................................................................92
4.3 Clean up Sample Pages ................................................................93
4.4 Clean up Sample Posts .................................................................96
4.5 Clean up Sample Comments........................................................98
4.6 Change the Permalinks URL.........................................................99
4.7 Clean up the Side Bars................................................................101
5 WordPress Settings ............................................................................104
5.1 General .........................................................................................104
5.2 Writing...........................................................................................106
5.3 Reading .........................................................................................108
5.4 Discussions...................................................................................111
5.5 Media ............................................................................................114
5.6 Permalinks....................................................................................115
5.7 Managing Users...........................................................................118
6 Plugins .................................................................................................122
6.1 What are Plugins? ........................................................................122
6.2 Install Jetpack Plugin and Link with WordPress.com ..............123
6.3 Plugins to avoid Spam Comments ............................................129
6.4 Plugins to increase your site speed ..........................................131
6.5 Plugins to add Google reCaptcha to Login Page .....................133
6.6 Plugin for Site Security................................................................137
6.7 Plugin to Change Footer .............................................................138
6.8 Plugin for SEO ..............................................................................138
6.9 Plugin for Contact Forms............................................................139
6.10 Add Social Share Plugin ............................................................140
6.11 Image Size Reducer Plugin .......................................................141
6.12 Plugin to Backup your Site .......................................................142
7 Themes ................................................................................................145
7.1 What are Themes?.......................................................................145
7.2 Download and Install a Theme ..................................................146
7.3 Site Customization ......................................................................150
7.4 Site Title and Tagline ...................................................................152
7.5 Site Logo .......................................................................................155
7.6 Create Menu ................................................................................156
7.7 Header Customization ................................................................159
7.8 Footer Customization .................................................................161
8 Pages....................................................................................................170
8.1 What are Pages? ..........................................................................170
8.2 Create About, Contact and Portfolio Pages..............................171
8.3 Edit the URL of the Page .............................................................175
8.4 Edit, Revision and Status of Page ..............................................177
8.5 Public, Private and Password Protect your Page.....................180
9 Text Editor ............................................................................................184
9.1 Visual Editor vs Text Editor..........................................................184
9.2 Formatting the Text......................................................................186
9.3 Create Headings ...........................................................................188
9.4 Create List Items...........................................................................189
9.5 Link other Pages and Posts .........................................................190
10 Posts, Categories & Tags .................................................................193
10.1 What are Posts? .........................................................................193
10.2 Posts Vs Pages ...........................................................................194
10.3 Categories vs Tags.....................................................................194
10.4 Create Categories......................................................................195
10.5 Create Post.................................................................................198
10.6 Create Tags ................................................................................200
11 Media .................................................................................................203
11.1 What are Media Files?...............................................................203
11.2 Upload Media to your Site .......................................................204
11.3 Embed Image, Audio and Video to a Page .............................207
11.4 Add a PDF Download Link ........................................................208
12 Sidebar and Widgets........................................................................211
12.1 Add Search Bar to Side Bar ......................................................211
12.2 Add Text Widgets to Side Bar ..................................................214
12.3 Add Subscribe Box to Side Bar ................................................216
12.4 Add Site Categories and Featured Post to Side Bar..............219
13 WordPress Customization...............................................................223
13.1 Add Custom CSS file to your Site.............................................223
13.2 Add your Own Logo to the Login Page ...................................227
13.3 Add Google Custom Fonts to your Site ..................................229
13.4 Add Google Analytics Custom Code........................................230
13.5 Remove Emoji unwanted js file from your site......................232
13.6 Add Fonts Awesome to your Site ............................................233
14 Do this Exercises ..............................................................................237
14.1 Restore a page from Revision..................................................237
14.2 Add, Approve and Delete Comments .....................................237
14.3 Change Logo of your Site .........................................................237
14.4 Change the H1 fonts size from Custom CSS ..........................237
14.5 Create Page and Add to the Menu..........................................237
14.6 Create Post and Display it on the Side Bar ............................237
14.7 Display a Welcome Note on Side Bar Menu ..........................237

1. WordPress B i
1 WordPress Basics
1.1 Welcome to WordPress?

Welcome to WordPress!

This might be the first time you ever heard of this word WordPress or you
might have read about WordPress somewhere on Internet or you heard about
WordPress from your friend.

Not sure what is your definition about WordPress but I want you to
remember this definition about WordPress.
WordPress is a Software that is used to build website. Do you know that
there are different types of Website? You know we can arrange Websites into
different categories.

Well, first thing you need to know that we cannot build any kind of website
with WordPress there are some specific types of website we can build with
WordPress.

Is this shocking to you?

You will learn about what kind of website we can build with WordPress in
Introduction to WordPress section. So, don’t skip that section if you need to
know what kind of website you can build with WordPress.

But I have a good news for you!


You can learn WordPress and build website without any prior knowledge on
website development.

Maybe this your first baby step in Website development. So the learning
curve has just started and it will take lot of time & effort to become expert in
website building. So, have patience when you are learning this skill or any
new skill.

So, What you will be doing using WordPress most of the time? Less coding
and more of Configuration!

You will find yourself writing less code and doing more of configuration
when working with WordPress. That’s why we say WordPress is a software
that we will use to configure our website.

Building Website with WordPress is so much faster rather than writing


everything from scratch. To start building website first thing you will learn is
how to configure things with WordPress and understand the WordPress
terminology.

It is like learning Microsoft Word to write a document and understand the


terms of that software and the features of it.

So, You will be spending time learning the things you can do with
WordPress and most of the time it is configuration of website and using add-
ons features.

For simple websites, You won’t be writing too much of coding unless it is
absolutely required to customized.

Once you learn this skill then you will be building website with WordPress
Software and will be publishing content on the site or selling some stuff
online.

This topic will take some time to master the skill so spend some time and
learn it.
More important practice more than reading. You wont learn Microsoft Word
by reading a book rather you learn it by doing it. So, follow the steps and do
the exercise.

Welcome To WordPress!
Let’s Learn to Build Website with WordPress!

1.2 What is WordPress?

What is WordPress? WordPress is a software that can help you build


website. Visit WordPress Site here -> https://wordpress.org/

Imagine you have decided to build a website and trying to find the options.
Without the use of the software like WordPress, you might need to build
your website using WEB programming language like HTML and CSS.

With WordPress, you can build a powerful website without even writing a
single piece of code. Wow right?
WordPress was developed to save our time in building the website. You can
actually build a decent website in just 20 minutes.

There are 3 great things about WordPress:


It is FREE to use.
30% of entire website in internet is build with WordPress. 60 million
people have used WordPress.
Is it not inspiring to know these facts about WordPress?

WordPress is famous I mean really really famous in the Web Industry.


Nothing can beat them in their space.
Why WordPress is FREE?

WordPress is not built by any one company or person. It is not owned by one
group. Actually, WordPress is built by the developers like us all around the
world. Many people have contributed for the development of this software.

This is called as Open Source Project. Project where everybody are


contributing for FREE.
So, WordPress is FREE to use software and you don’t have to buy the
license for using it.
WordPress is a Open Source Project that’s why it is FREE.

1.3 What is Content Management System

WordPress is a Content Management System (CMS)

You will heard this word CMS repeatedly when you are reading about
WordPress or talking to your friends about WordPress or in any training
videos.

So, before we move on let’s understand this word CMS . It is Important!


What is Content Management System (CMS)?

If you are a Traveller or Technology expert and you want to write about your
travel experience or new learnings you are doing in the technology space.

Typically, you will start writing your experience using Microsoft Word.
After a while you get a decent amount of content sitting on your laptop and
now you felt like putting all this content in your own website so that it might
benefit others.

You want to build a website, write digital content and manage it. This is a
perfect case for developing your website with WordPress which is a Content
Management System.

The things you write in a computer is called as Digital Content. Content


Management System (CMS) help to manage your digital content.
What can we do we CMS?
CMS is software using which we can do the following things:

• Create New Content


• Edit Existing Content
• Delete Content
• Manage History and Version of the Content
• Organizing Content based on the Categories
Publish Content to WEB or Any other formats. CMS is a software that
manages digital contents.

WordPress is one of the famous CMS software that helps to manage our
digital content and publish to Web. So, WordPress can also be called as Web
Content Management System (WCMS).

WordPress is not the only WCMS software available.


Joomla and Drupal are also the famous WCMS software to manage and
publish digital contents.
You will read more about alternative to WordPress in upcoming topic.
So, understand the main purpose of using WordPress.
WordPress helps to manage our content and publish it to Web.

If you want to build a website which does not need to manage any content
then WordPress may not be the right choice for you. But you can still use
WordPress even if you are not using it CMS features.

You can even build website with WordPress to sell items and collect
payment using third party software which can be used in WordPress. So, the
purpose of using WordPress is to create content on your site and publish it.
Because WordPress helps to manage the content it is called as Content
Management System (CMS).

1.4 Website vs CMS Website

Website vs CMS Website Website is a word that is commonly used for


anything on the web that is accessed via a domain name or URL Link
Like yahoo.com or google.com or wpfreelancer.com
So, instead of saying the domain name (like yahoo.com) or URL
(wpfreelancer.com) you can use the word website to address it. Website are
also used to refer to a site which has some pages that does not change much.
Like static – thing that does change.

A perfect example of Website could be a one page company profile which


has only one and all the details of the company. You can call it as Website .
Website is a collection of pages that can be accessed with same domain
name. It is mostly static pages.
But remember every type of site on the web can also be called as Website .
Because it is a very generic term and it is used commonly by everyone.

Anyone can say yahoo.com is a website. But there is a type of Website.


Website can be Blogging Website, eCommerce Website or Simple
WordPress Website.
So, you see website is a term most commonly used to refer to site with a
domain name.
CMS Website

CMS stands for Content Management System and WordPress is a CMS


Software which helps to build website that can manage your content on web.

CMS purpose is very straight forward it helps to capture your content, store
it and you can edit or delete it later.
WordPress software has all the features to manage your contents. Some of
the core features of managing content will be:

• Revision and Restore of the Content


• Visibility of the Content
• Organizing of the Content
• Styling of the content with lists, bold, headings and underlines.
• Add, Edit and Delete Content.

CMS Software like WordPress can do this task very well. Blog vs
eCommerce Blog

Any Website that is using CMS like WordPress and updating the contents on
the website then it generally called as Blog . When someone says I have
Blog or I read this blog . They means it is a website which has some content
updated periodically. A News website is a perfect example of Blogging site
where content on that site is updated regularly.
Blog is a website where contents of the sites are regularly updated like news.

If you are planning to building a website, install WordPress on it and manage


content on that website then you should start calling it as a Blog .
WPFreelancer.com is perfect example of Blog because the contents to this
site is regularly added on various web related topics. eCommerce
Website where you are buying or selling things or doing a business then that
kind of website is called as eCommerce site .
Example like Airbnb, Amazon, Alibaba are perfect example of eCommerce
site.

So, if you want to build a website, sell fashion designer clothes and collect
payments from customers then you should call that website as eCommerce
Site .

You can still install WordPress on your site and convert that site into
eCommerce site easily. It is done by some Add-on that is available for us to
use.

You don’t need to write coding here there are add-on that will take care of
showing the products, collecting payments from your website.
eCommerce is a website where you buy and sell products.

eCommerce + Blog will make your site more powerful because you can sell
clothes and write about some fashion tips to keep customer coming back to
your site.

So, having eCommerce on WordPress will give you that advantage.

1.5 WordPress.org vs WordPress.com

What is WordPress.org? WordPress.org is the place where you find the


WordPress software and all the free stuff to build website with WordPress.

All the things at WordPress.org is FREE to use because it is community


where people share things they developed using WordPress.

WordPress.org is the official site for WordPress Software. WordPress news,


new updates, add-on features can be found here along with plenty of third
party software for WordPress. It is a place where you find WordPress
Software and get to know about WordPress.
What is WordPress.com?
WordPress.com is not WordPress.org.

WordPress.com is a Web hosting platform like many other goDaddy.com,


DreamHost, SiteGround.
You can host your website on WordPress.com with some fees. You deploy
your WordPress software on WordPress.com. WordPress.com provides space
with some built in options to backup your code, security and other various
website options.
The WordPress.com hosting service has 5 plans:

• Free – Very limited.


• Personal – $36 per year
• Premium – $99 per year
• Business – $299 per year
• VIP – starting at $5000 per month

Free Hosting on WordPress.com? WordPress.com does provides Free


hosting and give free sub domain name which looks something like this.
yourname.wordpress.com
With the previous Exercise, you should have already created an account with
WordPress.com and deployed your site.

WordPress.com provides limited 3 GB space and restricted environment to


work with WordPress software with the FREE hosting.

It is good for educational purpose but not for your business.

1.6 Five Types of Website built with WordPress

Do you think you can guess at least 1 thing you can do with WordPress?
If you guessed Blogging – That is 100% correct.
We can do many thing on your website with WordPress Software. Lets see
the 5 things you can with WordPress.

1. Build a Blogging Site and Publish Contents.


2. Sell things on your Website and Collect payments.
3. Create Online Training Website and start collecting money from
subscribers.
4. Create One Page website for any Person, Shop or Company.
5. You can even create a Forum Site and build a community for a specific
group.

Always remember that WordPress is a Content Management System (CMS)


and true power of WordPress is to manage the Digital content and publish it.

With WordPress Software, you build Blogging, eCommerce, Forum and


Portfolio site where focus is on the Content.
So, you should also know when to use WordPress for your website design.

Not everything can be solved with WordPress. Because it is less coding and
easy to build website does not mean that you should start using WordPress
for all your Website.

Never always think WordPress is the starting point to build Website. You
should know why you are using WordPress software.

Because it is easier and faster to build website with WordPress and also with
many add-on support you should not be tempted towards WordPress.

Instead you should always understand what is the purpose of using


WordPress and is it a perfect fit for your website?

Remember as your business grows you will have different business


requirements and not everything can be fit into WordPress. In the end, You
will end up doing so much of customization to your site that it will become
extremely difficult to maintain.

So, be very careful and be aware what is the purpose of your building a
website and why you choose WordPress.
Here are some of the questions that help you to choose WordPress:

• Are you going to publish lots of blogs on your website for visitors to read?
• Do you want to sell something online and collect payments?
• Do you want build a Portfolio Website or One Page Website that all
information about your profile?
• Do you want to create a Forum or community for people to discuss on
specific topic?
• Do you want to share files like music, PDF or code on your Website?

If answer to this question is ‘YES’, then you can use WordPress Software on
your Website.

Examples of WordPress Site:


You can find the Website built with WordPress:
https://wordpress.org/showcase/
Blogging Sites:

Blogging site is simple to understand from all. In this type of website, you
will write contents about things you are great at or comfortable writing at.

If you like photography then you will build website and start uploading your
photos. You also might want to write content about tips & techniques on
how to take awesome photos in dim lights.

Examples of Blogging Site:

• WPFreelancer.com
• Beyonce.com
• Youngadventuress.com

News Site: News site is also a perfect example for building website with
WordPress.
In News Site, you get lots of content that need to be updated, editing and
deleted. It is the one perfect case of CMS.

News could be anything like General public news, Technology news,


Celebrity or something interesting that anyone will be interested to read
about.

Some of the famous news site built with WordPress:

• Newyorker.com
• Globalnews.ca
• Techcrunch.com
Forum Site: Did I told you before that you install add-ons to your
WordPress site?

These add-on are very powerful components and it help to solve a specific
needs that we need on our website.

One of the famous add-on that you can install on your website is Forum
Support. Once you install this add-on then you get to use all the feature of a
standard forum.

Some of the examples of Forum site:


• Hardwarezone.com.sg
• Bbpress.org/forums/forum/showcase/
Company Profile Site:

If you learn this one skill of building company profile with WordPress then I
can guarantee that you can go out and start taking orders for Website
Development.

This one skill of building company profile with WordPress is the easiest of
all and important skill.
Company profile are mostly static and contents on this site does not change
regularly.

One Page Company Profile will have only one page and all the links on the
page are pointed to the same page. Even About and Contact us page.

You can split those page to individual pages as well.

1.7 Five Types of Website cannot built with WordPress

Do you want to guess again…? I am not sure what you have guessed here
but you need to understand when you should not use WordPress.
There will be times you might be building on WordPress using lots of add-
on support and customization to your site.

If you are challenged on the support and maintenance of the website then
you should take a step back and think is this the right platform that I want to
run my business on?

So, here are the 5 website you should build on WordPress :

• Website that required you to perform some transactions at database. Eg. Airbnb where you need to
confirm the booking and maintain users activity.
• If you are trying to integrate your website with other sites for any transaction purpose then you
should not use WordPress. Eg. Flight booking from your site to actual Flight Company site.
• You want to build a page that does not redirect to another page but does all the transaction on the
same page.
• Admin based Website for monitoring systems, showing users activity etc.
• If your site has to much dependency on database operation and need to performs some file reading,
call other services or maintain high level of security.

If this list is too much for you to understand then remember that if your site
has to perform some work at the server level and you need to perform
some serious calculation or transaction then stay away from WordPress.

You should be looking at other alternative programming language like PHP,


Laravel, Ruby on Rails, Angular, ReactJS or NodeJS to build your website.

1.8 Alternative to WordPress CMS

There two most famous CMS Alternative to WordPress:


• Joomla
• Drupal
Joomla
Drupal
1.9 Benefits of Using WordPress

WordPress Summary: Visit WordPress Site: https://wordpress.org/

WordPress is a Content Management System (CMS) that helps to manage


your digital contents and publish it to WEB.
With WordPress, you will be doing more of customization and less of
coding. So, you need to learn WordPress software and how to use it. With
WordPress you can build personal blogging site, news site, Forum Site and
Company profile.
Many famous companies has used WordPress to build a solid website.

WordPress is Open Source and it is FREE to use.


Benefits of WordPress:

This is the last topic in this section. So, let’s wrap by understanding what are
the benefits of using WordPress.

• WordPress is Open Source and FREE to use.


• WordPress is easy to learn and anyone without much programming
language can use this software to build website.
• 60 million people and 30% of entire website uses WordPress.
• You will have many blogs, tutorials, discussion and even support from
many experts when you run into trouble.
• You can convert your blogging site into eCommerce site by simply
installing an Adds-on.
• WordPress has 45,000 add-ons for most of the website needs. You can find
plenty of Website Design templates for your WordPress site. So, you can
focus on content rather than designing of the website.

You will learn all the features of WordPress step by step in the upcoming
topic.
You will find yourself doing lots of customization, settings and focusing
more on content management.
WordPress Software is designed to manage your Content well. This is the
end of Section 1 – WordPress Basics. Next Section, You will create accounts
that will be used in your website.
2. ACCOUNT CREATION

2 Accounts Creation

2.1 Create an Account with WordPress.com


Purpose of Account WordPress.com provides some add-on plugins that you
can use on your website.
JetPack is one of those Add-On that you can install on your website which
helps to track your site analytics with some useful features. In order, for us
to use this add-on we need to connect our site with WordPress.com .
You need to have an account with WordPress.com so that you can use all
these FREE features on your site.
Create Account With WordPress.com
Prerequisite
• Valid Email ID
Step 1: Visit WordPress Site
Visit WordPress.com Site – > https://wordpress.com/
Step 2: Register
Click on “Getting Started” on Top Right Corner.

Enter your Site Details

Here are the Details of the Fields:


Name of your Site: Learn WordPress
About Site: Course to Learn WordPress
Primary Goals: Share Ideas
Comfortable: 1

Enter the Site URL Name:


Name Used: learnwpxyz.wordpress.com
Select Free from Below
Enter Email ID and UserName
Click Continue
Verify the Email from Inbox

Visit the Site with the URL:


URL: learnwpxyz.wordpress.com
Step 3: Final Step
You have successfully created an account with WordPress.com To verify
login do the following step:

• Signout from the WordPress.com


• Login again into the WordPress.com
• Verify all the credentials are working fine.
Verification of Credentials You should able to login and logout from
WordPress.com using the credentials.
References Visit – learnwpxyz.wordpress.com Exercise:

• Create your Account on WordPress.com


• Verify the WordPress.com Account from your Email.
• Write a Simple Post and Publish It.

2.2 Create an Account with Gravatar

What is Gravatar? Gravatar is your global profile pic linked with your
email id. This profile pic is called a GRAVATAR. Gravatar means Globally
Recognized Avatar.

It your profile pic that anybody can use to recognize you and display it.
You have to upload your profile pic along with the WordPress.com email ID.
Anyone can pull up your profile pic with your email ID from Gravatar.

Create an Account with Gravatar: Step 1: Visit Gravatar Site Visit the
URL: https://en.gravatar.com/
Step 2: Sign in with WordPress.com Account
Click on the “Sign In” Link on the Top Right Corner of the page.
Step 3: Link your WordPress.com Link the WordPress.com account that
you created in previous step. Authorize the Gravatar to access your
WordPress.com Account.

Step 4: Verify the Email on Gravatar Dashboard


Make sure you have the right email ID visible on the Gravatar Dashboard.
Step 5: Add your Profile Pic Click on the Right Side Top Icon and Select
“Add an Image”
Upload Your Image:
Select the Image and Upload it.
Next Two steps:
• Crop the Image
• Set Rating as ‘G’ General
Step 6: Verify the Image
You should now have an profile pic added to your email id
successfully on Gravatar.
Exercise:
• Create your own Gravatar Account and Upload your Image.

2.3 Create an Account with Akismet

What is Akismet? Askismet is a add-on that you can install on your website
to stop spam comments on your site.
There are many automated bots on the web that will find blogs and post
there links on your blogs comments.
If you don’t block them you will end up having plenty of unwanted
comments on your site.
This is a must to have plugin that should install on every WordPress site.
Create an Account with Akismet
Prerequisite:
• Valid WordPress.com Account

Step 1: Visit Akismet Site


Visit the Akismet Site: https://akismet.com/
Click on SignIn Button on the Right Top Corner.

Step 2: Approve the Account


Next, It will ask you to Authorize the account with WordPress.com account.
Make sure the email ID is same you want to connect.

Step 3: Select the Free Package


Select the Free package to generate an API key that you can use in your
WordPress Site.
Pull the bar to make it Zero.
Thank You Note!
Step 3: Verify the API Key Akismet will generate a API key that you will
use it when we add this Add-on to our site in the next section.

Take note of the API key as we need to use it on our site to activate this add-
on.
Exercise:
• Create your own account with Akismet.
• Get the Free API key from Akismet.

1. WORDPRESS INSTALLATION
3 WordPress Installation
3.1 Install WordPress on Local Machine

Prerequisite You need the following software Installed and Working:

• Install WAMP Server on your local machine


• Verify the PHP Code with WAMP Server
• Verify phpMyAdmin is working properly

Before you move on to other steps make sure you are able to run WAMP
server, PHP, MySQL and phpMyAdmin properly. WordPress runs on
WebServer and needs PHP and MySQL software. So, make sure they are
working fine.

Download WordPress Software


Step 1: Visit WordPress Site
Visit WordPress Site: https://wordpress.org/

Click on the Download WordPress button on the right top corner of the page.
This will land in the latest version of WordPress page. Click on the
Download Button.
This will start downloading the WordPress<version>.zip file on your local
computer.
Find the WordPress Software on your Local Machine
Create Database with phpMyAdmin
Now we have the WordPress software. Let’s create a database that
WordPress will use to create the tables.
Step 1: Open phpMyAdmin Dashboard
Make sure the WAMP Server is running and it is GREEN color.

Open the Google


Chrome and Type the
URL: http://localhost/phpmyadmin/

You should see the Login page of phpMyAdmin


Once you enter the Login and Password. You should be inside the
phpMyAdmin Home Dashboard
Step 2: Create Database for WordPress to use
Create a Database that WordPress will use.
See this guide on how to create database using phpMyAdmin Database
Name: learnwpdb
This should create the database – ‘learnwpdb’ and do not create any table
inside it.
WordPress will use this database to create the tables.
Verify the Database on the Database Page. Click on Database
Upload WordPress Software to WAMP Server We have downloaded the
WordPress software and also we have create ‘learnwpdb’ database.

Next Step is to install WordPress on WAMP Server.


Step 1: Open the www folder inside the WAMP Folder
Create Folder ‘learnwp’ inside the WAMP Server Folder
Folder Path: C:\wamp64\www\learnwp
Step 2: Copy the WordPress Software inside the new Folder Unzip the
WordPress contents inside the learnwp folder.

You can open the WordPress zip file and then drag and drop all the files
inside the learnwp folder.
Make sure the files and folders are like this.
Configure Database in WordPress
Before we install WordPress lets configure our database setting inside the
WordPress configure file.
Step 1: Create a copy of wp-config-sample.php
Create a copy of wp-config-sample.php -> wp-config.php
Open the wp-config.php and Provide the database details Database Name,
Username and Password
define(‘DB_NAME’, ‘learnwpdb’);

/** MySQL database username */


define(‘DB_USER’, ‘root’);
/** MySQL database password */
define(‘DB_PASSWORD’, ‘root’);

Save the file and close it. Install WordPress Before we install WordPress.
Lets do a quick recap

• Started the WAMP Server


• Downloaded WordPress Software
• Create Database using phpMyAdmin
• Copied the WordPress Software to a new folder in

WAMP/WWW folder.
• Created a WordPress Config File
• Copied the Database details to the Config File.

Lets now run the WordPress Software from the localhost. Open the URL:
localhost/learnwp/ This will open the WordPress Installation Page.

Make sure you do the configuration properly because you will see this page
only one time.

Click Continue Provide the Site Title, Username and Password.


Use the same email id we used to create the wordpress.com account.

Click Install WordPress.


Congratulations! WordPress is Installed on your local machine.
Click on Log In.
Enter the username and password (root/root)
You will now land into WordPress Dashboard Page.

Verify the Installation Now, we will try to logout and login again into
WordPress Dashboard. Step 1: Logout from the WordPress Dashboard
Click on the Top Right Corner and in the drop down menu click on Logout.

This is the logout Screen.

Step 2: Visit the Site Now Visit the site without login by typing this url in
the browser. http://localhost/learnwp
Step 3: Login into Admin Dashboard
Type this url to login into the Admin Dashboard of your WordPress Site.

http://localhost/learnwp/wp-admin/
or
http://localhost/learnwp/login/
This will show the login screen.
Enter the Username and Password and enter into the site.

Here is your WordPress Software installed on your Local Machine.


Exercise:
• Download and Install WordPress on your local Machine
• Login into the Admin Dashboard of WordPress.

3.2 Learnwp.xyz Website


learnwp.xyz learnwp.xyz is the site which I use to do this hands-on and
once it is done you can then visit that page to see how the page looks like.

For simple exercise I will use the WordPress on localhost and for those
which you might need a live demo I will do it on this site
– learnwp.xyz .

All the Live Demo will be on – learnwp.xyz


All the example sample will be from https://learnwp.xyz/ site. So make you
visit them to see more details about the exercise.

3.3 Login and Logout WordPress

Prerequisite You need to have WordPress Installation on local machine to


do this exercise.
• Learn how to install WordPress on Local Machine
• Make sure the WAMP Server is running.

Login into WordPress Step 1: Visit the site on localhost Open the Chrome
Browser and type the url. Visit: http://localhost/learnwp/login
Enter the Username and Password to enter into the WordPress site.

Logout from WordPress


Step 1: Click on the Right side top corner icon
Click on the right top corner to show this menu
Click on the Logout link.
3.4 Create Your Profile

Step 1: Login into WordPress Admin Dashboard


Login into the WordPress Admin Dashboard with this URL.
http://localhost/learnwp/wp-admin/
Click on the Right Top Menu and Select -> Edit My Profile

Your Profile Page:

Step 3: Modify & Save the Profile Details


Modify the Display name from root to LearnWP
Save the settings

Step 4: Verify the Changes


Verify the name changed from root to LearnWP

3.5 Gravatar Settings

In section 2, you have created an account with Gravatar and uploaded your
profile pic there.
Did you notice that when you configured WordPress with your email ID it
automatically pulled the logo from Gravatar.
This is because WordPress link with Gravatar to fetch the profile pic that you
have uploaded into the Gravatar site.

It is all connected.
Login Into Gravatar Site
Visit the Gravatar site URL: https://en.gravatar.com/

Verify the Gravatar Settings in WordPress Login into the WordPress Site:
localhost/learnwp/login Goto Your Profile Settings:

Verify the Gravatar settings in your Profile Picture.

If you like to change the Profile Picture then you should change in Gravatar
not in WordPress.
Remember this setting because it is the most important and many people get
confused how it is linked.

3.6 Create and Delete Users from WordPress

Create a User for WordPress


You can manually creates users for WordPress who can login in the
dashboard and access the options based on the roles provided to them.

Lets create an Admin User.


Click on Users -> All Users

This will show all the users that can access this site dashboard and their
roles.
This users are not users who can access the site but these users can login into
the dashboard.
Click on “Add New” to create user

Enter the user credentials:


New User Created:

Change Password for a User


Click on the User Profile and Click Edit

Change the password at the Account Management


Click on Update User to update the user.
Logout and Login with New User
You can test the user credentials by logout and login again with new user.
Here is the new User Profile

Delete User from WordPress Go to Users and Click on delete to remove


the user.
Move the content to Admin and Delete the User not the post.
User is deleted
3.7 Check the WordPress Version & Upgrade

How to Update your WordPress Software


Login into your Admin Dashboard and Click on Dashboard -> Updates
This will open the Updates Available for your Site.
You can see the current version and also you can check again from
WordPress site if any new updates available for WordPress. If available, it
will ask you to install the update.
Because we just installed the WordPress on localhost there is no new update
on WordPress.

3.8 Allow or Block Subscribers to your Site

Who are Subscribers? Subscribers are users who can register on to your
site have limited access to your site.
They won’t be create content or change settings but they are just registered
and can change there profile only.
If you like to enable login feature on your WordPress then this setting will
help.
With this setting, you can block anyone registering onto your site and you
don’t to give access to the WordPress dashboard.
Subscribers Settings:
You can allow or disable subscribers from the Settings -> General Check or
UnCheck the checkbox to control the subscribers registering for your site.

Exercise 1:
• Select the checkbox and allow subscribers to register for your site.
• Logout out of WordPress
• Browser this URL -> http://localhost/learnwp/wplogin.php?action=register
• You should be redirected to Register Page.

Exercise 2:

• Un-Select the checkbox and disable subscribers to register for your site. Do
not check the checkbox.
• Logout out of WordPress
• Browser this URL -> http://localhost/learnwp/wplogin.php?action=register
• You should be redirected to page that says registration is disabled.
3.9 Allow or Block Comments on your Site

You can allow or disable comments on your site from this settings. Goto
Settings -> Discussions
You can change this setting to add or remove the comments from the posts.
3.10 Allow or Block Google to Index your Site

You make setting in WordPress to allow or disable search engine like google
to index your page or not.
If you disable this feature then you website will not appear on google search
engine.
By default it is turned on means your site will be indexed by google and it
will be visible on google search results.
Settings:
Goto Settings -> Reading

By Default, this is turned off means google can index your site.
You can change this settings to discourage the search engine index your site
as well.
Become PHP Full Stack Web Developer in Just 30 Days

1. Clean Up
4 WordPress Clean Up
4.1 Clean up Themes

What are Themes? Themes are the add-on design for your site. Themes
control the look and feel of your site.
Theme are collection of files like php, css and js which modifies your site
design.
You can find many vendors that sell themes based on your requirement this
way you can focus on content rather than design of the site.

WordPress also give some Free themes that you can use. These are some
famous Vendors that sells themes.

• StudioPress
• ThemeGrill
• myThemeShop

You need to have at least one theme for your site which manage the site
design.
View the Themes
Goto Appearance -> Themes
This is the Theme Setting page. You can even install theme that you
purchased from outside.
Change Themes
Click on Activate Theme to use the new Theme.
Delete Unused Themes
Choose the Twenty Seventeen theme and click on Theme Details to open
theme details page.
Click on Delete theme and theme will be removed

You can see that Twenty Seventeen theme is deleted now.

4.2 Clean up Plugins

What are Plugins? Plugins are small piece of add-on that does one specific
task.

If you want a notification bar on top of your page then you install
notification plugin.
Similarly if want to stop spam comments then you install akismet plugin.
Each plugin perform one specific task so that you don’t have to write that
feature from scratch.
Delete the unused Plugin
Goto Plugins -> Installed Plugins
You can find that plugin is deleted.

4.3 Clean up Sample Pages

What are Pages?


Pages are like static page that does not change much. Some of the example
of pages are:

• Contact Page
• About Page
• Terms and Condition Page
Page are not news or updates but they are contents which does not change.
Delete the Pages
Click on Pages -> All Pages
Click on Trash to delete the page
Delete the Page from the Trash as well:

Page will be deleted from the Trash as well.

4.4 Clean up Sample Posts

What are Posts? Posts are like content that are published very often.

Contents like news, blogs and notifications or updates which change very
often are called as posts.
Delete Posts
Goto Posts -> All Posts
Click on Trash to move the file to trash.
Exercise:
• Try to delete the file from Trash Permanently as you did for pages.

4.5 Clean up Sample Comments

Delete the Comments Comments are small notes that people can type
below the posts to show they views on the posts or ask questions on that
topic. You can choose delete them from the comments section
Goto Comments and Click on Trash to delete the comments
Exercise:
• Remove the comments from Trash as you did in the Pages Section.
• Make sure nothing is in Trash Section.

4.6 Change the Permalinks URL

What are Permalinks?


Permalinks are settings that helps to change the URL pattern you want to see
in the browser URL.
Change the Permalinks
Click on Settings -> Permalinks
Change the Settings to Custom Settings
– /%category%/%postname%/
Click Save Changes.

4.7 Clean up the Side Bars

What are Sidebars?


Sidebars are the column on the left or right side of the page.
Delete the things from Sidebars
Goto Apperance -> Widgets
Click on Meta -> Delete

5 WordPress Settings
5.1 General
General Settings: Goto Settings -> General in the WordPress Dashboard
Things you can do in General Settings:

1. Change Site Title


2. Change Site Tagline
3. Change the Site Address from HTTP to HTTPS
4. Change the Email Address – This is used for Admin Purpose.
5. Allow Subscribers to register on your site or disable it.
6. Change Site Language
7. Change the Timestamp that is used to show on the articles on the site.
8. Change the Timezone as well.
5.2 Writing

Writing Settings:
Goto Settings -> Writing to open the Writing Settings
Things you can do under Writing Settings:

1. Set the Default Post Category – This setting will help you to set the
category under which you can place your post by default.
2. Post Format is set to Standard.
3. Post via Email Setting helps you send email to given email address and it
will create a post in your site.

5.3 Reading
Reading Settings:
Goto Settings -> Reading
Things you can do with Reading Settings

1. Mostly used to control how many posts to show on the blog browsing
page or category page.
2. Show small snippet of your blog or show the complete blog.
3. Discourage the Search Engine from indexing the site.

5.4 Discussions
Discussion Settings: Goto Settings -> Discussions
Things you do in Discussions:
Discussions is the place where you control how the comments should be
managed on your site.

Here are some of the settings available:


1. Enable or Disable comments on each articles
2. Restrict user to enter his emailid and name before adding the comments.
3. Users should be registered or not.
4. Limit the number of comments to be displayed
5. Get Notification when user comments on your blog.
6. Moderate the comments to approve or reject the comments before they
appear on below the posts.
7. Blacklist IP who cannot comment.
8. Show the users avatar based on their emailid. This is the same avatar you
uploaded into the Gravatar.
9. You can even set default gravatar when that user does not have a gravatar
image.
5.5 Media
Media Settings: Goto Settings -> Media
Things you can do with Media Settings

1. When you upload the media to the WordPress like images, video, audio,
pdf or zip file.
2. Here you can decide what should the size of the image that WordPress can
use to compress.
3. Also choose WordPress to organize them into year and month folder.

5.6 Permalinks
Permalinks Setting:
Goto Settings -> Permalinks
Things that can be done with Permalinks
Permalinks are the url format that you see in the URL bar. You can change
the URL format.

This is the recommended format to have good SEO


– /%category%/%postname%/
5.7 Managing Users

Managing Users: We have already learned how to create and delete users in
WordPress .
You can manage the users from the Users Section.
Things you do in Users:
• You can create, edit and delete the users from here.
• Maintain your Profile details from here.
All Users: Users settings will show the list of all the users who can login into
your site. It will also show their email and their role.
If you guest users who write contents on your site then it will show list of the
posts they have written.

Add New:
Add new users from this settings.
Your Profile: This option is available for all the subscribers on your site.
This settings is very common and specific to your userid.
Once you change the settings here it will affect only to your profile but does
not affect the global site settings.
6 Plugins
6.1 What are Plugins?

What are Plugins? Plugins are small add-on that does a specific job. It is a
collection of php files that has some functions.

Plugins are developed and released in the WordPress.org site and with the
WordPress software we can search and install those plugins on our site.

Plugins are small piece of program that helps to perform a specific task.
However, plugins are free to use on your site.
If you face any issue with that plugin on your site then it is your
responsibility to keep it or remove it.
But If you have purchase premium plugin then developers of that plugin will
support and fix the issue.
Once you install the plugin you can update the plugin from the WordPress
dashboard.
Only Admin can install or delete a Plugin on your site.
Most famous plugins are used to:

• Increase Site Speed


• Site Analytics
• Stop the SPAM Comments
• Secure your Site from Virus Attacks
• Add Contact Form to your site
• Reduce Media Size
• Backup your Site

You can find plugin for most common needs you have for your WordPress
Site.
Most of the time you will be adding and deleting the plugin instead of
writing the feature for yourself.

6.2 Install Jetpack Plugin and Link with WordPress.com

What is Jetpack Plugin?


Jetpack is a plugin developed by WordPress.com site and it one of the
famous plugin that is installed on more than 1+ million WordPress site.

This plugin is all in one plugin that helps to manage:

• Design
• Marketing
• Security

This plugin provides many features on your site that you activate or
deactivate based on your usage.
It also has some FREE features and some features are paid ones. You can
visit the plugin from
here: https://wordpress.org/plugins/jetpack/
Purpose of JetPack Plugin
Most important features of JetPack Plugin:

• Site Analytics
• Edit Custom CSS
• Connect your site with WordPress.com
• Subscribe Option

There are many other awesome feature that is available with this plugin.

Note
You need to do this exercise on hosting service.
How to Install JetPack Plugin
Step 1: Open the Plugin
Goto Plugins -> Add New Plugin
Step 2: Install the Plugin
Click on Install Button and Click on Activate Button
Step 3: Configure the Plugin Now you need to configure the Plugin. Click
on the ‘Setup the JetPack’

Click on Approve
Select the Free Option.
You JetPack is Installed and then Click on Activate the Recommended
Features.
This is the main screen for JetPack Plugin. Now JetPack will track your site
analytics and you see the visitors using this dashboard.

6.3 Plugins to avoid Spam Comments

What is Akismet Plugin? Akismet Plugin helps to identify the SPAM


comments and block it.

This plugin will not post those comments directly to your post instead it will
ask you to manually approve it.
This was you know which comments are spam and which comments are
real.
You can also configure to auto delete the SPAM comments so that you don’t
have do this maintenance job.

Plugin Link: https://wordpress.org/plugins/akismet/


Purpose of Akismet Plugin
Akismet helps to identify and remove the spam comments.

How to Install Akismet Plugin


Note
You need to do this exercise on hosting service.
Step 1: This plugin is pre installed
You will find that Akismet is already installed on your WordPress by default.

Step 2: Activate the Plugin


Click on Activate button to activate the plugin.
Step 3: Configure the Plugin
Click on Connect with JetPack button.
Save the Changes:
You can find the Akismet under the JetPack.

6.4 Plugins to increase your site speed

Install W3 Total Cache Plugin W3 Total Cache Plugin will increase your
site speed by caching your page and decrease the files of css and js.

Download Link: https://wordpress.org/plugins/w3-total-cache/ Step 1: Goto


Plugin and Type ‘W3 Total Cache”
Install and Activate this Plugin
Step 2: Verify if the Plugin is installed
6.5 Plugins to add Google reCaptcha to Login Page

Purpose of this Plugin This plugin will help to add Google reCaptcha at the
Login Page like this.
With plugin not automatic program break the password from the login page.

Get the reCaptcha Keys from Google


Step 1: Goto Google reCaptcha
Visit https://www.google.com/recaptcha/intro/v3beta.html
Click on the MyreCaptcha

Enter the details of your site and Register


It will generate the Site Key and Secret. Remember those as we need to enter
in the plugin.

Install Google reCaptcha Plugin Goto Plugin and Enter “Google


reCaptch” word

Url for the Plugin: https://wordpress.org/plugins/simple-googlerecaptcha/


Install and Activate the Plugin
Enter the Site Key and Secret Key and Save it.
Logout from the WordPress and You can see the Google reCaptcha
You can find this Plugin Settings under the
Settings -> reCaptcha
6.6 Plugin for Site Security

Purpose of this Plugin:


This plugin will help to keep you site secured by scanning the request and
files regularly.

It is like an anti virus software for your computer. This plugin also acts an
Firewall for your site. Install the Plugin: Plugin details:
https://wordpress.org/plugins/wordfence/ Type the Word “WordFence” in the
Plugin and Install it.

6.7 Plugin to Change Footer


6.8 Plugin for SEO

Purpose of this Plugin:


This plugin will help to configure the SEO for the posts that you write. It
will analyse the post and also let you know if the page is good for SEO or
not.
Install Yoast Plugin:
Plugin URL: https://wordpress.org/plugins/wordpress-seo/
I hope by now you know how to install and activate the plugins.

6.9 Plugin for Contact Forms

Purpose of Plugin
This plugin will help to create forms on any post or page with a short code.

Simple plugins using which you can create a form with form fields like input
box and submit buttons and also configure the email to receive the data.

Install the Plugin


Plugin Page: https://wordpress.org/plugins/wpforms-lite/
Search for “WPForms” and Install the Plugin
In Another topic we will create a form and use it in the Contact Form.

6.10 Add Social Share Plugin

Purpose of Plugin:
This plugin will help to show social share buttons on every post and help to
improve the user engagement on your site.

Install Social Share Plugin:


Type the Word: Social Share Warfare
Plugin URL: https://wordpress.org/plugins/social-warfare/
6.11 Image Size Reducer Plugin

Purpose of Image Optimizer Plugin:


Image Optimizer plugin will optimize and reduce the size of the image when
uploaded into the WordPress Site.
This is a important plugin that help to reduce the image size once you upload
it.
The page speed will increase when the size of the image is small and this
plugin will help to reduce it.

Install Image Optimizer Plugin


Plugin Name: Smush Image
Plugin URL: https://wordpress.org/plugins/wp-smushit/
6.12 Plugin to Backup your Site

Purpose of the Plugin:


This Plugin helps to take back up of the entire wordpress site incase if your
site crash then we can use this back to restore of our site. You can even
upload the site back automatically to your Dropbox account.

Install the Plugin:


Plugin Name: “Updraftplus”
Plugin URL: https://wordpress.org/plugins/updraftplus/
7.Themes

7 Themes
7.1 What are Themes?

What are Themes? Themes are the design and layout of your site.

In a typical web application, you develop everything from scratch HTML,


CSS and JS but in WordPress you will install themes which take care of your
site design and layout.

Once you have the theme then you can customize the theme by changing
some of the features of it.
You can find themes for different purpose like

• Blog Themes
• eCommerce Themes
• Corporate Themes
• News Themes.

You can purchase or use a free theme on your site and you will be ready to
start working on the content.
This way you don’t have to spend much time on coding and focus more on
generating good content.
These are some famous Vendors that sells themes.

• StudioPress
• ThemeGrill
• myThemeShop

Next section, we will install a theme for our site.

7.2 Download and Install a Theme

Download Premium StudioPress Theme This is one of my favorite theme


and also considered the famous theme for WordPress.
The theme is from StudioPress
Download the two Zip Files:
1. StudioPress Framework
2. StudioPress Eleven40 child Theme

Install the StudioPress Themes


Step 1: Site before the theme
This is how the site looks like before the theme.
learnwp.xyz
Step 2: Install the StudioPress Framework Theme Click on Appearance -
> Themes
Click on Add -> New

Click on Upload Theme

Add the Genesis Zip File that you downloaded from above
Click on Install Now and you should success message as below.
Do not activate the theme.
Step 3: Install the StudioPress Eleven40 Theme Do the same steps and
install the child theme Eleven40 theme.
Activate this Theme
Step 4: Site After the theme
This is how the site looks after the theme

7.3 Site Customization

Site Customization Settings: Once you have installed the theme you can
customize the theme to your needs.
Every theme gives some options to customize the theme and it is specific to
each theme design what they allow you to customize on it.

Customization Option:
Goto Apperance -> Customization
Here you can customize the theme.
Here you can customize the theme
In the next section, you will start configuring the site.

7.4 Site Title and Tagline

Change the Site Title and Tagline from Customization Options: Goto
Appearance -> Customization
Click on Site Identity
Change the Site Title and Identity and Publish it.
Verify the changes on the Live Site.

7.5 Site Logo


Change the Logo at the Site Identity Page and Publish the changes.
Verify the Logo of the site.

7.6 Create Menu

Create 3 Menu Items:

1. Home
2. About
3. Contact

Link the menu items “#” as of now then later we change it to the actual
pages.
Create Menu
Goto Appearance -> Menu
Create a new Menu
Specify the location of the menu

Go to Custom Links -> Add URL as ‘#’ and Name of the Menu Then click
on Add to Menu
Then Save the Menu
This how the menu looks like on Home Page.
7.7 Header Customization

Change the Header Image from here: Goto Customization -> Header
Image Choose the image with the exact size image specification and upload
it here.
Publish the site once you have uploaded the Image.
7.8 Footer Customization

Lets add some contents to the Footer of the Site. Footer 1: We will add
some description to the page. Footer 2: Add Featured Posts Footer 3: We
add Header Menu

Steps to Create the Footer


Goto Appearance -> Widgets
You see the 3 Footer Section
Footer 1: Drop the Text and Add Some Text Find text and click to see the
sub menu and add it to Footer 1 Click on Add Widget
Open the Footer 1 and Add Some Content.
Add Featured Post to Footer 2 and Save the menu
This how it looks

Add Menu to Footer 3 and Save the Menu


This how this looks
Finally, all the footers
Visit the site
Once you save the footer, it will look like this on the final site.

8.Pages
8.1 What are Pages?

What are Pages? Pages are like static page that does not change much.
Some of the example of pages are:

• Contact Page
• About Page
• Terms and Condition Page

Page are not news or updates but they are contents which does not change.
Static HTML pages and pages in WordPress are exactly same. To publish the
news or notifications or blogs you should NOT use pages.

8.2 Create About, Contact and Portfolio Pages

Create 3 Pages:

• About
• Contact
• Portfolio
Create About Page Goto Pages -> Add New
Enter the Title and Some Text
Press “Publish” Button

View the Page:


Observe the Page URL and Details:
URL: https://learnwp.xyz/about/

Create Contact & Portfolio Page Similarly, Create the Contact and
Portfolio Page. Visit URL for sample:

• https://learnwp.xyz/contact/
• https://learnwp.xyz/portfolio/
Create Page from Admin Bar:

Add the Pages to Menu


Goto Appearance -> Menu
Remove the default menu
Add the Pages:

Reorder the items and Save the Menu.


Check the Menu at the Site:

8.3 Edit the URL of the Page

Permalinks Permalinks are the URL of the page that you can change any
text you want.
Once you set the Permalink for a page then that url will be displayed on the
Browser URL.
Permalinks Settings
You can change the format of the Permalinks in the Settings -> Permalinks.
You have learned to change the Permalinks format from here. Once you
change the format of the Permalinks then for every page you get a defined
format that you can edit.

Page Permalink
Create a new Page – learn-permalinks.
Title : Learn how to change the Permalinks
Permalink: learn-permalink

When you create this page, WordPress automatically create the permalink.

You can click on “Edit” button to change it to learn-permalink and then


Publish the page.
This is the page URL: https://learnwp.xyz/learn-permalink/
This is how you change the URL of the page. You should never rely on
default URL given by WordPress.
Always verify and add your own easy to read URL.

8.4 Edit, Revision and Status of Page

Page Status
Page status helps to keep the content in three modes:

• Published
• Pending Review
• Draft

Published means release the article on the live site and it is visible to
everyone on the site.
Pending Review means the article need to be reviewed before posting it to
the live site.
Draft means the article is not complete and still need to add contents.
You can change this setting on the right side of the page in the publish box.

It has the 3 options:


Published Date:
You can even choose when the article to be published on the live site.
It is like a news you want to get published on the site on a specific date.
You can do that by writing the article in advance and set the published date
to time when you want to appear on the site.

8.5 Public, Private and Password Protect your Page


Visibility Settings:
There are 3 visibility settings you can apply on the page:

• Private
• Public
• Protected

Private is only Visible to the Author Public are visible to everyone on the
site.

Protected means you can assign a password to the page and user has to enter
password to access the page.
How to change the Visibility Settings
You can find this visibility option on the right side of the page
Here are 3 options:
9. Text Editor

9 Text Editor
9.1 Visual Editor vs Text Editor
There are two tabs in the Text Editor :

One is Visual and another one is Text.


Visual Editor:

In Visual Editor you cannot type HTML elements. If you try to type HTML
element then page will display the HTML elements.
It is WYSIWYG editor means what you see is want you get editor.

Visual Editor is like Microsoft Word where you type the text and style the
text and drop media in the content.
In Visual Editor CSS does not work means if you have CSS rule it won’t be
displayed in the editor.

CSS will be showed when you publish the page and see the live page. So,
use Visual Editor when you want to write content and format some basic
text.
Text Editor:
Text editor is the background HTML code that gets generated when you
write in the Visual Editor.

You can write the HTML code directly in the text editor.
This is the best way to copy paste the HTML code inside your editor.

Do not copy paste any HTML in the visual editor rather do it in Text Editor.
Also, WordPress might add unnecessary tags you can review them in the text
editor and delete them.
9.2 Formatting the Text

Formatting the Text: If you know Microsoft Word then formatting in


Visual editor is similar to the Microsoft Word.

Starting from Left:

1. Bold the text


2. Italics
3. List Bullets
4. List Numbers
5. Quotes
6. Left Align
7. Center
8. Right Align

Here is the example of page that has all this:


URL: https://learnwp.xyz/text-formatting/
9.3 Create Headings

Instead of Writing the HTML tags you can use the Visual Editor to create the
Headings.
Example:

This is Heading 1 Example


This is Heading 2 Example

This is Heading 3 Example

This is Heading 4 Example


This is Heading 5 Example
This is Heading 6 Example
Text Editor:

9.4 Create List Items

You can create two type of Lists in Visual Editor:


• List with Bullets
• List with Numbers Example Bullets:

• List Item 1
• List Item 2
• List Item 3

Example Numbers:
1. List Item 1
2. List Item 2
3. List Item 3

9.5 Link other Pages and Posts

Creating Links: You can create links in the Visual Editor by selecting the
word and clicking on link icon.
Start Here – Table of Contents
You can choose the gear icon and more options will open.

10.Post, Categories & Tags


10 Posts, Categories & Tags
10.1 What are Posts?

What are Posts? Posts are opposite to Pages. They are dynamic Pages and
pages that keep updating.

Perfect example of posts are news and blogs on new topic that you write
everyday or every week.
You can publish continuous post on your site so that readers of your site can
come and read the latest posts on your site.

Posts are special type of contents that can be organized into folders, shared
on social media and even share with your subscribers whenever it is
released.

Contents created as Posts are more to share your views on specific topic or
write about an how to do guide.
These articles you are reading are posts not pages.
In the Next section, you will learn to create posts and organize them into
folders.
You cannot store pages into folders but you can store posts into categories.

10.2 Posts Vs Pages

Posts vs Pages: Pages:

• Does not change regularly.


• Mostly used for Contact, About, Terms and Conditions, Privacy Policy and
Support.
• Pages cannot be organized into folders.
• Pages does not sub links a/b/c/page.
• You can create as many pages as you want.
• You can link pages into posts or menu.

Posts:

• Posts are contents that get updated regularly.


• You sort the latest posts and display them on the sidebars.
• Posts mostly represents news, blogs or support guides.
• Posts are stored in folders called as Categories.
• Every posts must be stored in any one Categories.

10.3 Categories vs Tags

What are Categories? Categories are folders that are used to organize your
posts. Posts must be stored in one of the categories.
Categories are used to differentiate the contents based on the topic it belongs
to.

Categories can be made visible in the URL via the permalinks. Whatever the
name that you give to categories will be visible in the URL.

What are Tags?

Tags are short keywords that you can attach to your posts. These are not
SEO keywords but small meta words which are used to identify what is the
post about.

You can add duplicate tags or multiple tags to any post you want. Once you
have good collection of posts and tags then you can show which tags are
more commonly used on your site.
Tags gives a good indication of what is your site more focused on.

10.4 Create Categories

Create Categories: You have create categories before you choose to write
the post.

This way it helps to organize your site into write group and later you can
choose to display the categories in the sidebars to show what kind of articles
you write on your site.

Step to Create Categories:


Click on Posts -> Categories
This is a Default Category:

Lets create a ‘wordpress’ category.


Click on Add new Category Button

10.5 Create Post


Create Posts and Save in the Category Click on Posts -> Add New
Observe the below image for following things:

• Add Tags in the tags section


• Add Category in the Category Section
• URL has Category
Final Post looks like this:
URL : https://learnwp.xyz/wordpress/welcome-to-wordpress- course/

10.6 Create Tags

Create Tags:
URL: https://learnwp.xyz/wordpress/how-to-create-posts/
Exercise:
• Create a Post and Name is ‘How to Create a Tag’
• Add some content in it.
• Add the following tags

o how to create tags


o posts
o wordpress
o learning
o basics

• Save and Publish the page.


11.Media

11 Media
11.1 What are Media Files?

Media Files: Media files in WordPress are:

• Images
• Audio File
• Video File
• PDF
• Zip File
Upload an Image: Goto Media -> Add New
In Next Section, we will upload an Image

11.2 Upload Media to your Site

Upload an Image
Goto Media -> Add New
Upload an Image

Embed the Image in the Post: URL: https://learnwp.xyz/wordpress/add-


media-to-post/ Create a Post and Embed a Image in the Post.

Add the Image:


Check the Post:

11.3 Embed Image, Audio and Video to a Page

You can Add Image, Audio and Video by just dragging and dropping the
file.
See this example post: https://learnwp.xyz/wordpress/add-imageaudio-and-
video/
You can even embed Youtube Video, Vimeo Video in the post.

11.4 Add a PDF Download Link

You can Add PDF file to your Post as well. SAMPLE URL :
https://learnwp.xyz/wordpress/add-pdf-to-post/ View the Sample Post from
here:

Post:
12.Sidebar &

12 Sidebar and Widgets


12.1 Add Search Bar to Side Bar
Step to Add Search Bar to Sidebar: Goto Apperance -> Widgets
Find the Search Widget and add to Primary Sidebar
Check the Search in the Widget
Check on the Live site:

12.2 Add Text Widgets to Side Bar

Step to Add Text Widget Goto Widgets. Add the Text Widget to Side bar
Move it to Up and Add Welcome Text.
Verify the Text on the Page:

12.3 Add Subscribe Box to Side Bar

Subscribe Box Widget:


This Widget helps to accept the email ID of the user and you can send
regular emails about your post to the user email ID.
You can even schedule to send email when a new Post is created and
published on your site.
Add this Widget to sidebar:
Check the Widget Name and Position
Verify the Site
12.4 Add Site Categories and Featured Post to Side Bar
Add Site Categories and Features Post: Site Categories:
Top Post Categories:

Site Categories and Featured Posts


Verify on the site:
13.wordPress C t i ti

13 WordPress Customization
13.1 Add Custom CSS file to your Site

High Level Steps to add Custom CSS:

1. Create custom.css file on your local machine


2. Upload the custom.css file to Hosting Server
3. Edit the functions.php file to add the custom.css stylesheet for every page.
4. Verify the custom.css file loaded.

Step 1: Create custom.css file: This custom css should change the menu bar
color to red when this is included in HTML page.
Here is the custom.css file:
.site-header{
background-color: red;
}

Step 2: Copy the custom.css to Hosting Server


Step 3: Edit the functions.php code
Code to add the custom.css to HTML page.
Goto Appearance -> Editor
Add the below code:
add_action('wp_enqueue_scripts', 'custom_style_sheet', 99);
function custom_style_sheet() {
wp_enqueue_style( 'custom-styling', get_stylesheet_directory_uri() . '/ custom.css ',
array(), '1.0.3');

}
Copy the code at the last and save the file.

File Updated.
Verify the update in the Website Source Code:
13.2 Add your Own Logo to the Login Page

High Level Steps to Add Logo:

• Copy the logo file to the Hosting server


• Change the functions.php to load the custom logo
• Verify the login page.

Step 1: Copy the logo to Hosting Server


Download this login.zip and replace the image file with yours.
Step 2: Change Functions.php
Add the following code to functions.php file
Goto Appearance -> Editor
// Login CSS
add_action('login_enqueue_scripts', 'login_style_sheet');
function login_style_sheet() {
wp_enqueue_style( 'login-styling', get_stylesheet_directory_uri() .
'/login/loginstyles.css', array(), '1.0.2');
}
13.3 Add Google Custom Fonts to your Site

High Level Steps:


1. Select the Google Font and Size
2. Add the Google Font code to functions.php
Step 2: Open Functions.php and Modify the google fonts
Change in StyleSheet styles.css file also.
Google Fonts are just loaded from functions.php file but it is referenced in
the CSS file.
If you change the fonts in functions.php then you should also change the
new font name in the css file.
styles.css file content fonts reference example:

13.4 Add Google Analytics Custom Code

There is a detailed step by step guide on how to configure Google Analytics


to your site. Refer to that guide in the next section. Here I will show you
where you can upload the Google Analytics code that is provided by the
google to add your site.
Goto Genesis -> Theme Settings
Copy the Google Analytics code here:

13.5 Remove Emoji unwanted js file from your site


You will find this emoji code for every new wordpress installation.

Add this code in functions.php to remove the emoji


remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action(
'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );
Functions.php file
After the code applied in functions.php

13.6 Add Fonts Awesome to your Site

FontsAwesome library is a very famous styles that has very good collection
of fonts that can be used in your content writing.
Font Awesome Site: https://fontawesome.com/
How to include fonts awesome from functions.php
// Load Font Awesome
add_action( 'wp_enqueue_scripts', 'enqueue_font_awesome' ); function
enqueue_font_awesome() {

wp_enqueue_style( 'font-awesome',
'//maxcdn.bootstrapcdn.com/fontawesome/latest/css/font-awesome.min.css' );
}
Functions.php

Fonts Awesome added to the file


Sample Post to use the fonts-awesome:
URL: https://learnwp.xyz/wordpress/show-fonts-awesome-icon/
14.Excercise

14 Do this Exercises

14 Do this Exercises
14.1 Restore a page from Revision 14.2 Add, Approve and
Delete Comments 14.3 Change Logo of your Site 14.4 Change
the H1 fonts size from Custom CSS 14.5 Create Page and Add
to the Menu 14.6 Create Post and Display it on the Side Bar 14.7
Display a Welcome Note on Side Bar Menu

You might also like