Web Development Learn HTML CSS Javascri - Srinivas Vanamala
Web Development Learn HTML CSS Javascri - Srinivas Vanamala
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 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.
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 .
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
1. WEB BASICS
1. Web Basics
1.1 - What is a Protocol?
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.
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 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.
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.
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.
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.
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.
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.
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
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.
2. HTML BASICS
2. HTML Basics
2.1 – What is HTML?
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.
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.
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
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.
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.
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.
3. TEXT ELEMENTS
3 TEXT ELEMENTS
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
<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>
<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 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 Emphasis.
This is Underline.
This is Italics.
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.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
<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
<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
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
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
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
4. LISTS
4 Lists
4.1 – Definition List
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create one HTML page and create something like below.
Live Preview
UnOrdered List
• List Item 1
• List Item 2
• List Item 3
Learn HTML5
Why Learn HTML5?
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>
<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>
#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
7. EMBED CONTENTS
7 EMBED CONTENTS
• 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.
• 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.
<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
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 ">
<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
<footer>True friend!</footer>
</article>
</section>
</body>
</html>
German Shepherd
Best bread in Dog Family
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
<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
<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.
Live Preview
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>
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>
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>
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>
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
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:
• 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.
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Create a form like this below
Live Preview
■ <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
</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
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
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
Live Preview
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
9 META TAGS
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.
</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
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">
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
<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>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
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 ©.
<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>
© – ©
ELEMENT:
• <p>Paragraph Text with One Space</p>
• <p>Paragraph   Text with Two Spaces</p>
• <p>Paragraph   Text with Four Spaces</p>
• <p>Copyright: © – ©</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
Live Preview
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 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.
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 .
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
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 .
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.
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>
</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
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.
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>
/* This is a multi-line comment in CSS. This is different than the HTML comments.
Anything inside this block will be ignored.
Live
Preview
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
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.
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
styles.css file is linked inside the index.html file with <link> tag in the
<head> section.
FileName: index.html
<!DOCTYPE html> <html>
</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; }
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
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.
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
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>
</head>
Sample Example
Download the Example
There are three files:
• index.html
• mynewstyles.css
• anotherstylesfile.css
</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 */
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
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
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
<head> <meta charset="utf-8"> <!-- Make sure mynewstyles.css file exists in the same
folder -->
} </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 */
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
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 .
<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>
/* selector {
/* 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
<head>
<style type=”text/css”>
*
{
border-style: solid;
border-color: red;
}
</style>
</head>
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>
<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
When you find any selector that has rule applied on the HTML tags then it is
called as Type Selector.
<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 {
/* Specify the HTML TAG as the Selector. */ /* Apply the rule to specified tag as
selector. */
p
{ color: red;
}
h1
{ color: blue;
}
font-style: italic; }
</style>
<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
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.
/* .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
</style>
</head>
<body>
<div class=”redcolor”> <p>This is red color paragraph</p> </div> </body>
Sample Example
Download the Example
<!DOCTYPE html> <html>
div.color-red
{ color: red;
}
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.
<head>
<meta charset="utf-8">
/*
#selector {
/* 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>
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
Example:
h1#redcolor { color: red; }
This id is only applicable to h1 tag.
Live Preview
2.7 ID Multiple Selector
</style>
</head>
<body>
<div id=”redcolor”> <p>This is red color paragraph</p> </div> </body>
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>
/* selector.class-selector {
div.color-red
{ color: red;
}
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
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>
/* selector[class] {
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
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.
<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>
/* selector>selector {
/* Direct child element of the parent element. */ /* Only <a> tag inside the <p> tags
are affected. */
<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
<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>
/* selector selector {
</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
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 {
/* Adjacent Siblings not nested but one after the other. */ /* First <a> tag after the
<h1> tags are affected. Not Inside but after. */
</style>
</head>
<body>
<h1>Adjacent Sibling Selector - HTML TAG</h1>
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
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>
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>
/* selector + selector {
</style>
</head>
<body>
<h1>Adjacent Sibling Selector - HTML TAG</h1>
<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.
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
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>
</style>
</head>
<body>
<h1>Pseudo Class Selector - HTML TAG</h1>
</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
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>
</style>
</head>
<body>
<h1>Pseudo Elements</h1> <h1>Exclamation Mark is added by CSS</h1>
<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.
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; }
<!-- 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> </body>
</html>
Live Preview
Exercise 1
Download the Exercise 1
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.
<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>
}
/* Overwrite background-color style from parent. */ h1{ text-decoration: underline;
background-color: black; }
</head>
<body> <h1>Heading!</h1>
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
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>
{ color: red;
}
{ color: red;
}
#text-red { color:red;
}
.text-red { color: red;
}
h1#text-red{ color: red; }
h1.text-red{ color:red;
}
<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
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.
Browser will always give important to the rules that has !important at the
end of the rule.
<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
{ color: red!important;
}
#text-blue { color:blue;
}
.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
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">
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
<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 */
</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.
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.
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">
<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.
height: 250px; //This make the box 250 px of height width: 250px; //This
make the box 250 px of width
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">
} </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 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">
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.
<head>
<meta charset="utf-8">
} </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">
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
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>
.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.
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.
clear: both – property will clear the floating of boxes next to each other.
Sample Example
Download the Example
<!DOCTYPE html> <html>
<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>
</body> </html>
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
.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>
</div>
<hr>
<div class="clearfix">
</div>
<hr>
<div class="clearfix">
Exercise 1: Draw a table with two columns and display content as below.
Exercise 2: Put the Image in the center and text in the center without table.
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> </head>
<body>
</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
ul{
background-color: #333; list-style-type: none; width: 200px;
}
li a{ display: block; /* Make the links appear below each other */
} </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>
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.
/* Default Page & Font Styles - Because we love to see nice design. */
h1 { text-align: center;
}
} </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.
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).
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
By default without CSS, browser will lay all the element one after the other.
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.
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"> -->
/* Page Styles */
/* Exercise Section */
.box { height: 150px; width: 150px; background-color: #5bc0de; top: 50px; left: 50px;
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
/* Page Styles */
body {
background: rgba(0,0,0,.1);
}
/* Exercise Section */
.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
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>
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
width: 100px; /* Cannot add width and height when display is inline. */
height: 100px;
}
}
</style> </head>
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.
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>
<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>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>
<style>
body {
width: 940px; margin: 0 auto; font: "Georgia", Arial, sans-serif;
section{ float: right; width: 700px; padding-left: 20px; border-left: 2px dotted
#b2a497;
</div> </aside>
<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>
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>
body {
width: 940px; margin: 0 auto; font: "Georgia", Arial, sans-serif;
<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>
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>
section{ float: left; width: 500px; padding-left: 20px; padding-right: 20px; border-
left: 2px dotted #b2a497; border-right: 2px dotted #b2a497;
</figure> <div>
</ul>
</div> </aside>
<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>
<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>
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
Audience
This tutorial has been designed to meet the requirements of all those readers
who are keen to learn the basics of JAVASCRIPT.
Prerequisites
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 .
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
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:
browser.
• Animation Effects
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
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>
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">
<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
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.
SYNTAX:
<head>
<script>
// This will alert the user – Single Line Comments
alert(‘This is alerted on the browser’);
</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">
<script> /*
This is a multi-line comment in JS. This is different than the HTML comments. Anything
inside this block will be ignored.
<body>
<h1>Heading</h1> <p>Paragraph Text</p> <ul>
</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
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=”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
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>
</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
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
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>
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
Braces – { } – Flower brackets are used to define the scope like starting
point and ending point and we write the code inside this block.
{
y = sum(1, 2);
alert(“value of y” + y);
}
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’);
<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>
</ul>
</body>
</html>
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
• strFirstName
• $var
• index_1
• crashReport
InValid Identifiers:
• 1PhoneNumber
• false
• long
• package
<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>
<body>
<a href="#" onclick="ALERT('Welcome to JavaScript!');">Click Me</a>
</body>
</html>
Live Preview
Exercise 1
Download the Exercise 1
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”;
//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”;
+ symbol is used to attach a variable to the string and display it. Write
Variables on HTML Document
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>
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:
<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>
</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.
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.
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
Reserved Words These are the list of the reserved words that you should
not use to define variables, functions, objects or properties.
1. Assignment Expressions
2. Comparison Expressions
3. Arithmetic Expressions
4. Logical Expressions
• +=
• -=
• *=
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>
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
> is the comparison operator which compares the two values. message
variable will be have a true or false.
Comparison Operations:
<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>
<script type="text/javascript">
document.write("Compared: " + counter + "<br>"); document.write("Result Value: " +
resultValue);
</script>
</body>
</html>
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
1. Assignment Expressions
2. Comparison Expressions
3. Arithmetic Expressions
4. Logical Expressions
• + – 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
• ++
• —
• * / %
• + –
<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>
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
1. Assignment Expressions
2. Comparison Expressions
3. Arithmetic Expressions
4. Logical Expressions
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
• && – AND
• || – OR
• ! – NOT
• NOT
• AND
• OR
<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.
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()
<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>
<body>
<h1>String Expressions</h1>
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
<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>
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
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);
<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>
</script>
</head>
<body>
<h1>Arrays</h1> </body>
</html>
Live Preview
Exercise 2
Download the Exercise 2
Live Preview
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
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>
</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
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>
</body> </html>
Live Preview
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
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">
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
<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{
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
<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>
</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
You can pass parameters to functions and it can return a value from the
function using “return ” keyword.
<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>
</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>
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
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;
</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
<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
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
1. CTRL + SHIFT + I
2. F12
3. Top-Right Menu -> More Tools -> Developer Tools
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.
}
Using Wrong Keywords Case.
Example:
Funtion add(){
}
//Keywords as Variable
var name = “hello”;
function add(){
}
var total = add;
Accessing the Wrong Array Index.
Example:
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.
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>
</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.
Live
Preview
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.
1. getElementById(idName)
2. getElementsByTagName(tagName)
3. getElementByName(name)
4. getElementByClassName(className)
<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>
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:
Live Preview
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>
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
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>
<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>
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>
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>
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>
do{ var input1 = prompt("Guess the Number Between 1 to 10!"); input1 = parseInt(input1);
}while(answer != input1)
message = "You Guessed it Right - " + answer + " is the answer!";
</script>
</head>
<body>
<h1>Guess the Number</h1>
</body>
</html>
Live Preview
About this Book
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 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.
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 .
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
1. MySQL BASICS
1 MySQL Basics
1.1 Introduction to Databases and SQL
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.
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.
Every website uses Database to store its information because it is easy and
faster to store and access it.
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.
• 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.
• Numeric
• Strings
• Date and Time
• INT
• TINYINT
• SMALLINT
• MEDIUMINT
• BIGINT
• FLOAT
• DOUBLE
• DECIMAL
• CHAR
• VARCHAR
• BLOB (TINYBLOB, MEDIUMBLOB, LONGBLOB)
• TEXT (TINYTEXT, MEDIUMTEXT, LONGTEXT)
• ENUM
• DATE
• TIME
• DATETIME
• TIMESTAMP
• SELECT
• INSERT
• UPDATE
• DELETE
• AS
• DROP
• DESC
• TABLE
• DATABASE
• WHERE
• ISNULL
• ORDER BY
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
4: Check the User Created
Step 5: Press the logout button to exit from the application
Step 7: Verify
the table
Step 8: Create the marks table
Step 9: Verify the Table
• Create Table
• Insert Data in Table
• View the Table Data
3 MySQL Statements
3.1 Create a Table
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:
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.
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’
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.
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.
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:
database.
</head>
<body>
<h1>PDO - SELECT Query</h1>
<?php
//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
Write a Student form to Add, Edit and Delete the Entries from MySQL
DB.
Credentials:
We have seen how to work with MySQL with phpMyAdmin . Define the
parameters: $hostname = ‘localhost’; $db_name = ‘schooldb’; $username =
‘root’; $password = ‘root’;
$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:
</head>
<body>
<h1>mysqli - SELECT Query</h1>
<?php
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"; }
}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
Write a Student form to Add, Edit and Delete the Entries from MySQL
DB.
Credentials:
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 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.
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 .
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
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.
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?
Browser does not understand PHP nor it understand how to interpret it.
That is the reason you need a Web Server to execute PHP code.
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
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
Verify WAMP
Click on the
ICON and you should see this menu.
Stop WAMP
Step 1: Click on the System Tray WAMP Icon and Select Stop Services.
Step 2:
WAMP Icon Turns to RED.
Step 1 : Click on the System Tray WAMP Icon and Select Star Services.
Step 2 :
WAMP Icon Turns to GREEN
Open the WAMP Menu from System Tray and you can find the WAMP
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.
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
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
</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.
You use single quote or double quotes and statement should end with semi
colon “;”.
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
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
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">
<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:
<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.
*/
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.
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
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.
$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">
<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.
That’s why you must always use Single Quotes and only use Double Double
quotes when you need interpolation feature.
<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
Live Preview
Exercise 1
Download the Exercise 1
Exercise 1: Convert a string to uppercase and lowercase. Display the text on
body.
Live Preview
2.3 Numbers
You can append the – (minus) symbol in front of the number to indicate it is
negative number.
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
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.
$newColors = array();
$newColors[0] = $colorName[0]; $newColors[1] = $colorName[1];
Print Arrays
print_r($arrayName);
Sample 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
//Print an Array
print_r($colorNames); echo "<br>";
Live Preview
Exercise 1
Exercise 1: Create an Array with String, Number and Boolean and display
them.
Live Preview
Exercise 2
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.
$this is a special object that will help to access the existing object of a class.
Class Syntax:
class Student{
private $id, $name, $age;
}
Create Instance of Class
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<body>
<h1>Classes and Objects</h1>
<?php
Live Preview
Exercise 1
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
//Define a Constant
define('MESSAGE', "Welcome to PHP!"); define('AGE', 20);
?> </head>
<body>
<h1>Constants</h1>
<?php
Exercise 1
Exercise 1: Define String, Number and Boolean Constant and display them.
Live Preview
Exercise 2
Live Preview
2.7 Boolean
$result = 2 > 1;
$message = ($result) ? “CORRECT”: “WRONG”;
Sample Example
<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
Live Preview
Exercise 2
Live Preview
2.8 Date and Time
<!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
Live Preview
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.
$message = ‘WP’;
$message .= ‘Freelancer’; counter += 1;
counter = counter + 1;
counter -= 1;
counter = counter – 1;
counter *= 1;
counter = counter * 1;
Sample Example
<!DOCTYPE html>
<html>
<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
Live Preview
Exercise 2
Order of Precedence:
++
—
*/%
+–
Anything mentioned in () will get higher precedence over anything. (5 + 2) *
2; //Result – 14
Sample 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;
$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
Exercise 2
Live Preview
3.3 Comparison
> 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
<!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
Exercise 1: Learn how to compare NULL in the string with === operator.
Live Preview
Exercise 2
&& 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
<!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
Live Preview
Exercise 2
Live Preview
4. STATEMENTS
4 Statements
4.1 If Statements
Syntax:
if ( condition1 ){
// Statements
} else if( condition1 || condition2 ){
// Statements
} else {
// Statements
}
Example 1:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<body>
<h1>If Statements</h1>
<?php
?>
</body> </html>
Live Preview
Exercise 1
Live Preview
Exercise 2
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;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
$dayOfWeek = "Friday";
$result = "";
$dayOfWeek = strtolower($dayOfWeek);
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
Live Preview
Exercise 1
Download the Exercise 1
Live Preview
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.
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.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
</head> <body>
<h1>Boolean Expression</h1>
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:
Live Preview
Exercise 2
Live Preview
4.4 For Statements
Syntax:
for( counter initialization; condition; increments ) {
//Statements
}
Example 1:
for($counter = 0; $counter <= 10; $counter++){ echo $counter;
}
<!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
Live Preview
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
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.
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.
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>
Live Preview
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
<!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
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.
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:
<!DOCTYPE html>
<html>
<head>
<body>
<h1>Files</h1> <?php
/*
* READ A FILE - rb mode
*
*/
$line = fgets($file);
echo $line;
}
fclose($file);
/*
* WRITE A FILE - wb mode *
*/
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
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
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
Live Preview
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
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
<body>
<h1>Libraries</h1> <?php
include 'calculator.php';
define('INPUTVALUE1', 50); define('INPUTVALUE2', 23);
echo 'Calculator : '. INPUTVALUE1 . ' AND ' . INPUTVALUE2 . '<br>';
?>
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.
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.
$_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.
<!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>
</p>
<p>
<label for="input_email">Email:</label>
</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
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
Exercise 2: Show the result on the same page and redirect to same page.
Live Preview
6.2 POST
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.
<!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>
</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
Live Preview
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
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
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);
By setting the time last year all the cookies with that name are deleted.
$expire = strtotime(‘-1 year’);
setcookie(‘WPFreelancer.com’, ”, $expire, ‘/’);
Sample 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";
?>
</body> </html>
Live Preview
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
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.
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
Live Preview
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
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.
<!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
Live Preview
Exercise 2
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.
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.
In this Project, you will write a simple application online test with some
question. Once user provide the answer he immediately verify the result.
EXERCISE 1:
Change the $_GET to $_POST and perform the same operation.
EXERCISE 2:
Display the result on the next page.
In this Project, you will write a simple calculator application where user will
enter the values and our program will calculate various math formulas.
EXERCISE 1:
Add some Math formulas and add to the table.
EXERCISE 2:
Add some styling to the table.
About this Book
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
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 .
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
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.
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.
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.
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!
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.
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.
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.
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.
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).
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).
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:
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.
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.
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.
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.
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.
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.
• 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.
• 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.
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.
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?
• 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.
This is the last topic in this section. So, let’s wrap by understanding what are
the benefits of using WordPress.
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
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.
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
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
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.
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.
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’);
Save the file and close it. Install WordPress Before we install WordPress.
Lets do a quick recap
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.
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.
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.
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 .
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.
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:
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.
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
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
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.
• 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:
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.
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.
5 WordPress Settings
5.1 General
General Settings: Goto Settings -> General in the WordPress Dashboard
Things you can do in General Settings:
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.
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.
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:
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.
• 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.
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.
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.
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.
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.
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.
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.
7 Themes
7.1 What are Themes?
What are Themes? Themes are the design and layout of your site.
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
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
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.
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.
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
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.
Create 3 Pages:
• About
• Contact
• Portfolio
Create About Page Goto Pages -> Add New
Enter the Title and Some Text
Press “Publish” Button
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:
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.
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.
• 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 :
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
Instead of Writing the HTML tags you can use the Visual Editor to create the
Headings.
Example:
• List Item 1
• List Item 2
• List Item 3
Example Numbers:
1. List Item 1
2. List Item 2
3. List Item 3
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.
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.
Posts:
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.
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.
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.
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
11 Media
11.1 What are Media Files?
• Images
• Audio File
• Video File
• PDF
• Zip File
Upload an Image: Goto Media -> Add New
In Next Section, we will upload an Image
Upload an Image
Goto Media -> Add New
Upload an Image
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.
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 &
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:
13 WordPress Customization
13.1 Add Custom CSS file to your Site
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;
}
}
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
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
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