HTML Introduction
Learn HTML from the basics, including its purpose, structure, elements, tags, attributes, text, links, lists, images and tables.
HTML stands for HyperText Markup Language. It is the standard markup language used to create and structure web pages. HTML defines different parts of a web page such as headings, paragraphs, links, images, lists, tables and forms.
HTML is not a programming language because it does not contain programming logic such as conditions, loops or functions. Instead, HTML uses elements, tags and attributes to describe the structure and content of a web page.
Why Do We Use HTML?
Create Web Pages
HTML provides the basic structure required to create websites and web applications.
Structure Content
HTML organizes content into headings, paragraphs, sections, lists, tables and other elements.
Create Links
HTML allows users to navigate between pages and websites using hyperlinks.
Add Multimedia
HTML supports images, audio, video and other types of multimedia content.
HTML Installation & Setup
HTML does not require a separate compiler or server to get started. You only need a text editor or code editor and a web browser.
Using Visual Studio Code
Visual Studio Code is a popular source-code editor used for developing websites. It provides features such as syntax highlighting, code completion and extensions.
Step 1: Download and install Visual Studio Code.
Step 2: Open VS Code and create a folder for your HTML project.
Step 3: Create a new file and save it with the
.html extension, such as index.html.
Step 4: Write your HTML code and save the file.
Step 5: Open the HTML file in a browser to view the output.
my-html-project/
│
└── index.html
Using Notepad++
Notepad++ is a lightweight text editor that can also be used to create HTML pages. It is simple and suitable for beginners.
Step 1: Download and install Notepad++.
Step 2: Open Notepad++ and create a new file.
Step 3: Write your HTML code.
Step 4: Save the file with the
.html extension, for example index.html.
Step 5: Open the HTML file using a web browser.
Your First HTML Program
The following example shows the basic structure of an HTML document.
<!DOCTYPE html>
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<h1>Hello, HTML!</h1>
<p>Welcome to my first web page.</p>
</body>
</html>
Hello, HTML!
HTML Elements
An HTML element is a complete structure that usually consists of an opening tag, content and a closing tag. HTML elements are the building blocks of a web page.
<p>Hello World</p>
<h1>Welcome to HTML</h1>
In <p>Hello World</p>,
<p> is the opening tag,
Hello World is the content and
</p> is the closing tag.
HTML Tags
HTML tags are keywords enclosed inside angle brackets
< >. They tell the browser how the content should
be structured.
Most HTML elements have opening and closing tags. Some elements are void elements and do not require a closing tag.
<h1>Welcome</h1>
<p>This is a paragraph.</p>
<img src="image.jpg" alt="Image">
<br>
HTML Text
HTML provides different elements for displaying and organizing text. Headings are used for titles and sections, while paragraphs are used for blocks of text.
<h1>HTML Tutorial</h1>
<p>
HTML is used to create and structure web pages.
</p>
HTML Formatting
HTML formatting elements can be used to give special meaning or visual
emphasis to text. Common elements include
<b>, <strong>,
<i>, <em> and
<mark>.
<b>Bold Text</b>
<strong>Important Text</strong>
<i>Italic Text</i>
<em>Emphasized Text</em>
<mark>Highlighted Text</mark>
Important Text
Italic Text
Emphasized Text
Highlighted Text
HTML Pre
The <pre> element displays preformatted text.
It preserves spaces, indentation and line breaks exactly as written.
<pre>
Hello
HTML World
</pre>
Hello
HTML World
HTML Attributes
HTML attributes provide additional information about an element.
They are written inside the opening tag using the format
name="value".
Common attributes include id, class,
href, src, alt and
title.
<a href="https://example.com"
title="Visit Example">
Visit Website
</a>
HTML Font
Font styling is mainly handled using CSS in modern HTML development. CSS can control the font family, size, weight, style and color.
<p style="font-family: Arial;
font-size: 20px;
font-weight: bold;
color: blue;">
Hello HTML
</p>
<font> element is obsolete.
Use CSS properties for font styling.
HTML Text Links
The <a> element is used to create hyperlinks.
The href attribute specifies the destination of the link.
<a href="https://www.google.com">
Google
</a>
HTML Comments
HTML comments are used to add notes or explanations inside the source code. Comments are not displayed in the browser.
<!-- This is an HTML comment -->
<p>This paragraph is visible.</p>
HTML Lists
HTML lists are used to display groups of related items. The common types are unordered lists, ordered lists and description lists.
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
<ol>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ol>
HTML Images
The <img> element is used to display images on a
web page. The src attribute specifies the image location,
while alt provides alternative text.
<img
src="image.jpg"
alt="Nature Image"
width="300"
>
HTML Image Links
An image can be made clickable by placing the
<img> element inside an
<a> element.
<a href="https://example.com">
<img
src="image.jpg"
alt="Example Image"
width="200"
>
</a>
HTML Tables
HTML tables are used to organize information into rows and columns.
The <table> element creates the table,
<tr> creates a row,
<th> creates a heading cell and
<td> creates a data cell.
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>Course</th>
</tr>
<tr>
<td>Dhanush</td>
<td>20</td>
<td>HTML</td>
</tr>
</table>
| Name | Age | Course |
|---|---|---|
| Dhanush | 20 | HTML |
HTML Forms
Learn how to create HTML forms, collect user information, use different input controls and apply form attributes.
HTML forms are used to collect information from users. Forms are commonly used for login pages, registration pages, contact forms, search boxes, feedback forms and online applications.
The <form> element acts as a container for different
form controls such as text fields, password fields, radio buttons,
checkboxes, dropdown lists, text areas and submit buttons.
HTML Forms Introduction
The <form> element is used to create an HTML form.
Form controls are placed inside the form to allow users to enter or select
information.
A basic form can contain a label, input field and submit button.
<form>
<label>Name:</label>
<input type="text">
<button type="submit">
Submit
</button>
</form>
HTML Form Structure
A form normally contains labels, input controls and buttons. The
<label> element describes the input field, while the
<input> element allows the user to enter information.
<form>
<label for="username">
Username:
</label>
<input
type="text"
id="username"
name="username"
>
<button type="submit">
Submit
</button>
</form>
Using the for attribute in the label and matching it with
the input's id helps users identify the corresponding input
field and improves accessibility.
HTML Inputs
The <input> element is one of the most commonly used
form elements. It allows users to enter or select different types of
information.
The type attribute determines the kind of input control
displayed by the browser.
<input type="text">
<input type="email">
<input type="number">
<input type="date">
<input type="file">
<input type="checkbox">
<input type="radio">
HTML Text Fields
A text field is used to collect single-line text from the user. It is commonly used for names, usernames, cities, addresses and other short text values.
Text fields are created using
<input type="text">.
<label for="name">
Full Name:
</label>
<input
type="text"
id="name"
name="name"
placeholder="Enter your name"
>
HTML Password
The password input is used to collect passwords and other sensitive information. When the user types into a password field, the browser hides the characters instead of displaying them as normal text.
Password fields are created using
<input type="password">.
<label for="password">
Password:
</label>
<input
type="password"
id="password"
name="password"
placeholder="Enter your password"
>
HTML Semantic Elements
Semantic elements clearly describe the meaning and purpose of the content they contain. They make HTML documents easier to understand for developers, browsers and assistive technologies.
Common semantic elements include
<header>, <nav>,
<main>, <section>,
<article> and <footer>.
<header>
Website Header
</header>
<nav>
Home | About | Contact
</nav>
<main>
<section>
Main Content
</section>
</main>
<footer>
Copyright 2026
</footer>
Header
Represents introductory content or the header area of a page or section.
Navigation
The <nav> element contains navigation links
to other pages or sections.
Main
Represents the main content of a web page.
HTML Form Elements
HTML provides several elements for collecting different types of user information. Each element is designed for a particular purpose.
<input>
Used for different types of user input such as text, email, password, number, date, radio buttons and checkboxes.
<textarea>
Used when users need to enter multiple lines of text.
<select>
Creates a dropdown list from which users can select an option.
<button>
Creates buttons that can submit forms or perform other actions.
<input type="text">
<textarea>
Enter your message
</textarea>
<select>
<option>India</option>
<option>USA</option>
</select>
<button type="submit">
Submit
</button>
HTML Form Input Types
HTML provides many input types that allow developers to collect different kinds of data. The input type determines the appearance and behavior of the input field.
<input type="text">
<input type="password">
<input type="email">
<input type="number">
<input type="date">
<input type="radio">
<input type="checkbox">
<input type="file">
<input type="color">
<input type="range">
<input type="submit">
<input type="reset">
Common Input Types
Text
Used to collect normal single-line text.
<input type="text">
Used to collect an email address. Browsers can perform basic email-format validation.
<input type="email">
Number
Used to enter numeric values.
<input type="number">
Date
Allows users to select a date.
<input type="date">
Radio Buttons
Radio buttons are used when the user needs to select one option from a
group of choices. Radio buttons in the same group should have the same
name attribute.
<p>Select Gender:</p>
<input type="radio" name="gender" value="male">
<label>Male</label>
<input type="radio" name="gender" value="female">
<label>Female</label>
Checkboxes
Checkboxes allow users to select one or more options. They are commonly used for preferences, interests and agreement options.
<p>Select Skills:</p>
<input type="checkbox" name="skill" value="html">
<label>HTML</label>
<input type="checkbox" name="skill" value="css">
<label>CSS</label>
<input type="checkbox" name="skill" value="javascript">
<label>JavaScript</label>
Dropdown List
The <select> element creates a dropdown list.
Individual options are created using the
<option> element.
<label for="course">
Select Course:
</label>
<select id="course" name="course">
<option value="html">
HTML
</option>
<option value="css">
CSS
</option>
<option value="javascript">
JavaScript
</option>
</select>
Textarea
The <textarea> element is used to collect multiple
lines of text. It is useful for messages, feedback, comments and
descriptions.
<label for="message">
Message:
</label>
<textarea
id="message"
name="message"
rows="5"
cols="30"
placeholder="Enter your message"
>
</textarea>
HTML Form Attributes
Form attributes provide additional information about forms and input controls. They can control where form data is sent, how it is submitted, whether a field is required and what information is displayed to the user.
Some commonly used form and input attributes are
action, method, name,
value, placeholder, required,
readonly, disabled and
maxlength.
Action Attribute
The action attribute specifies the URL or server endpoint
where the form data should be sent when the form is submitted.
<form action="/submit-form">
<input type="text" name="username">
<button type="submit">
Submit
</button>
</form>
Method Attribute
The method attribute specifies how form data is sent to
the server. The two commonly used methods are GET and
POST.
<form action="/login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">
Login
</button>
</form>
Placeholder Attribute
The placeholder attribute displays a temporary hint inside
an input field. It disappears when the user starts entering information.
<input
type="text"
placeholder="Enter your username"
>
Required Attribute
The required attribute specifies that a field must be
completed before the form can be submitted.
<input
type="email"
name="email"
required
>
Readonly and Disabled
The readonly attribute prevents the user from modifying
the value, but the value can still be submitted with the form.
The disabled attribute prevents the user from interacting
with the control, and a disabled form control is not submitted with
the form.
<input
type="text"
value="Harish"
readonly
>
<input
type="text"
value="Disabled Field"
disabled
>
Complete HTML Form Example
The following example combines several HTML form elements and attributes into a simple registration form.
<form action="/register" method="post">
<label for="name">
Name:
</label>
<input
type="text"
id="name"
name="name"
placeholder="Enter your name"
required
>
<br><br>
<label for="email">
Email:
</label>
<input
type="email"
id="email"
name="email"
placeholder="Enter your email"
required
>
<br><br>
<label for="password">
Password:
</label>
<input
type="password"
id="password"
name="password"
required
>
<br><br>
<label for="course">
Course:
</label>
<select id="course" name="course">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JavaScript</option>
</select>
<br><br>
<button type="submit">
Register
</button>
</form>
<form> element acts as the container, while elements
such as <input>, <textarea>,
<select> and <button> provide
different ways to enter or select data. Form attributes such as
action, method, required and
placeholder control the behavior of forms.
CSS Basics
Learn the fundamentals of CSS including syntax, selectors, styling methods, backgrounds, box model, margins and padding.
CSS stands for Cascading Style Sheets. It is used to control the appearance and layout of HTML elements on a web page. CSS can change colors, fonts, spacing, borders, backgrounds, sizes and the overall layout of a website.
HTML is mainly responsible for the structure of a web page, while CSS is responsible for its presentation and visual appearance. By combining HTML and CSS, developers can create attractive and well-organized websites.
<style> element, or in a separate
.css file.
CSS Introduction
CSS provides styling rules that tell the browser how HTML elements should look. For example, CSS can change the color of a heading, increase the size of text, add a background image or create spacing around an element.
<h1>Welcome to CSS</h1>
<style>
h1 {
color: blue;
font-size: 32px;
}
</style>
Welcome to CSS
Why Is CSS Important?
Styling
CSS allows developers to change colors, fonts, backgrounds, borders and other visual properties of HTML elements.
Layout
CSS can control the position, size, spacing and arrangement of elements on a web page.
Responsive Design
CSS can be used to create layouts that work properly on desktops, tablets and mobile devices.
Reusable Styles
External CSS files allow the same styles to be reused across multiple HTML pages.
CSS Syntax
CSS syntax consists of a selector followed by a block of one or more declarations. Each declaration contains a property and a value.
selector {
property: value;
}
For example, the following rule changes the color and font size of
all <p> elements.
p {
color: blue;
font-size: 18px;
}
Here, p is the selector,
color and font-size are properties, and
blue and 18px are their corresponding values.
CSS Selectors
CSS selectors are used to select the HTML elements that should receive a particular style. Different selectors can be used depending on the elements or groups of elements that need to be styled.
Element Selector
The element selector selects all HTML elements of a particular type.
p {
color: green;
}
This rule applies the green color to every
<p> element.
Class Selector
A class selector is used to style one or more HTML elements that have
the same class attribute. A class selector begins with
a dot ..
.highlight {
color: red;
font-weight: bold;
}
<p class="highlight">
Important Text
</p>
ID Selector
An ID selector is used to target an element with a specific
id. It begins with the hash symbol #.
#heading {
color: purple;
font-size: 30px;
}
<h1 id="heading">
CSS Tutorial
</h1>
Universal Selector
The universal selector * selects all HTML elements on
the page.
* {
margin: 0;
padding: 0;
}
Types of CSS
CSS can be applied to HTML documents in three main ways: Inline CSS, Internal CSS and External CSS.
Inline CSS
CSS is written directly inside the HTML element using the
style attribute.
Internal CSS
CSS is written inside a <style> element
within the HTML document.
External CSS
CSS is stored in a separate .css file and linked
to the HTML document.
Inline CSS
Inline CSS is written directly inside an HTML element using the
style attribute. It is useful when a specific style needs
to be applied to only one element.
<p style="color: blue; font-size: 20px;">
This is Inline CSS
</p>
This is Inline CSS
Internal CSS
Internal CSS is written inside the <style> element
in the <head> section of an HTML document. It is
useful when the styles are specific to a single HTML page.
<html>
<head>
<style>
h1 {
color: blue;
}
p {
font-size: 18px;
}
</style>
</head>
<body>
<h1>Internal CSS</h1>
<p>This style is inside the HTML page.</p>
</body>
</html>
External CSS
External CSS is written in a separate file with the
.css extension. The CSS file is connected to the HTML
document using the <link> element.
External CSS is the preferred approach for larger websites because the same stylesheet can be reused across multiple HTML pages.
<!-- index.html -->
<head>
<link rel="stylesheet" href="style.css">
</head>
/* style.css */
h1 {
color: blue;
}
p {
font-size: 18px;
}
Styling Background
CSS provides several properties for styling the background of an HTML
element. Backgrounds can contain colors or images and can be controlled
using properties such as background-color,
background-image, background-repeat,
background-position and background-size.
Background Color
The background-color property is used to set the background
color of an element.
body {
background-color: lightblue;
}
.box {
background-color: yellow;
}
Background Image
The background-image property is used to display an image
as the background of an element.
.banner {
background-image: url("image.jpg");
}
Background Repeat
By default, a background image may repeat to cover the available area.
The background-repeat property controls this behavior.
.box {
background-image: url("image.jpg");
background-repeat: no-repeat;
}
Common values include no-repeat,
repeat-x and repeat-y.
Background Position
The background-position property controls the position of
the background image inside an element.
.box {
background-image: url("image.jpg");
background-repeat: no-repeat;
background-position: center;
}
Background Size
The background-size property controls the size of the
background image. A common value is cover, which scales
the image to cover the complete element.
.banner {
background-image: url("image.jpg");
background-size: cover;
background-position: center;
}
CSS Box Model
The CSS box model describes how the browser calculates the space occupied by every HTML element. Each element is treated as a rectangular box.
The box model consists of four main parts: content, padding, border and margin.
Content
The actual text, image or other content inside the element.
Padding
The space between the content and the border.
Border
The line surrounding the padding and content.
Margin
The space outside the border that separates an element from other elements.
.box {
width: 200px;
padding: 20px;
border: 5px solid black;
margin: 30px;
}
The browser calculates the final size of an element using its content, padding and border. The margin creates space outside the element.
CSS Margin
The margin property is used to create space outside an
element. It controls the distance between an element and neighboring
elements.
.box {
margin: 20px;
}
Margin can be applied to individual sides using
margin-top, margin-right,
margin-bottom and margin-left.
.box {
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 40px;
}
Margin Shorthand
The margin shorthand property can specify all four sides in one declaration.
/* Top Right Bottom Left */
.box {
margin: 10px 20px 30px 40px;
}
When four values are provided, they are applied in the order top, right, bottom and left.
CSS Padding
The padding property creates space between the content of
an element and its border. Unlike margin, padding is inside the border.
.box {
padding: 20px;
border: 2px solid black;
}
Padding can also be applied to individual sides using
padding-top, padding-right,
padding-bottom and padding-left.
.box {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
}
Padding Shorthand
Padding shorthand allows developers to specify multiple sides using a single declaration.
/* Top Right Bottom Left */
.box {
padding: 10px 20px 30px 40px;
}
Margin vs Padding
| Property | Location | Purpose |
|---|---|---|
margin |
Outside the border | Creates space between elements |
padding |
Inside the border | Creates space between content and border |
Complete CSS Example
The following example combines selectors, background styling, margin, padding, border and other CSS properties to create a styled HTML box.
<div class="box">
Welcome to CSS
</div>
<style>
.box {
width: 300px;
padding: 20px;
margin: 30px;
background-color: lightblue;
border: 2px solid blue;
color: darkblue;
text-align: center;
}
</style>
CSS3
Learn CSS3 features including borders, border radius, backgrounds, text effects, text shadows, fonts, white-space, word wrapping and word breaking.
CSS3 is the modern version of CSS that introduced many powerful features for creating attractive and interactive web page designs. It provides properties for styling borders, backgrounds, text, fonts and controlling how content behaves inside elements.
CSS3 allows developers to create modern interfaces without depending on images or additional styling technologies for many common visual effects. Features such as rounded corners, shadows, gradients, custom fonts and text wrapping make web pages more flexible and visually appealing.
CSS3 Introduction
CSS3 introduced many new styling capabilities that make it easier to design modern websites. Developers can use CSS3 to create rounded corners, shadows, gradients, responsive layouts and advanced text effects.
Borders
CSS provides properties for controlling border width, style, color and radius.
Backgrounds
CSS can add background colors, images, gradients and control their position and size.
Text Effects
CSS provides properties for controlling text alignment, spacing, decoration, transformation and shadows.
Fonts
CSS allows developers to control font family, size, weight, style and other font properties.
CSS3 Borders
The border property is used to create a visible boundary
around an HTML element. A border can have different widths, styles and
colors.
The basic border syntax contains three important values: border width, border style and border color.
.box {
border: 2px solid blue;
}
Border Width
The border-width property controls the thickness of the
border.
.box {
border-width: 5px;
}
Border Style
The border-style property defines the appearance of the
border. Common values include solid,
dashed, dotted, double and
none.
.solid {
border: 3px solid blue;
}
.dashed {
border: 3px dashed green;
}
.dotted {
border: 3px dotted red;
}
.double {
border: 5px double purple;
}
Border Color
The border-color property controls the color of the
border.
.box {
border-style: solid;
border-width: 2px;
border-color: orange;
}
Border Radius
The border-radius property is used to create rounded
corners on an HTML element. It is commonly used for cards, buttons,
input fields and containers.
.box {
width: 250px;
padding: 20px;
border: 2px solid blue;
border-radius: 15px;
}
Circular Element
Setting border-radius to 50% can create a
circular shape when the element has equal width and height.
.circle {
width: 100px;
height: 100px;
background-color: blue;
border-radius: 50%;
}
CSS3 Backgrounds
CSS provides several properties for controlling the background of an element. Backgrounds can use colors, images, gradients and different positioning options.
Background Color
The background-color property adds a color behind the
content of an element.
.box {
background-color: lightblue;
}
Background Image
The background-image property allows an image to be used
as the background of an element.
.banner {
background-image: url("background.jpg");
}
Background Repeat
By default, background images may repeat. The
background-repeat property controls whether the image
should repeat.
.banner {
background-repeat: no-repeat;
}
Common values are:
no-repeat– prevents the image from repeating.repeat– repeats the image in both directions.repeat-x– repeats the image horizontally.repeat-y– repeats the image vertically.
Background Position
The background-position property specifies where the
background image should be positioned.
.banner {
background-position: center;
}
Common values include left, right,
top, bottom and center.
Background Size
The background-size property controls the size of a
background image. The cover value makes the image cover
the complete element.
.banner {
background-image: url("background.jpg");
background-size: cover;
background-position: center;
}
CSS Gradient Background
CSS gradients allow developers to create smooth transitions between two or more colors without using an image.
.box {
background: linear-gradient(
to right,
blue,
purple
);
}
CSS Text Effects
CSS provides many properties for controlling the appearance and layout of text. These properties can change alignment, decoration, transformation, spacing and wrapping behavior.
Text Alignment
The text-align property controls the horizontal alignment
of text.
.left {
text-align: left;
}
.center {
text-align: center;
}
.right {
text-align: right;
}
Text Decoration
The text-decoration property adds or removes decorations
such as underlines and strike-through effects.
a {
text-decoration: none;
}
.underline {
text-decoration: underline;
}
.strike {
text-decoration: line-through;
}
Text Transformation
The text-transform property changes the capitalization of
text without changing the original HTML content.
.uppercase {
text-transform: uppercase;
}
.lowercase {
text-transform: lowercase;
}
.capitalize {
text-transform: capitalize;
}
Letter Spacing
The letter-spacing property controls the amount of space
between individual characters.
.heading {
letter-spacing: 3px;
}
Word Spacing
The word-spacing property controls the space between
individual words.
.text {
word-spacing: 10px;
}
CSS Text Shadow
The text-shadow property adds a shadow effect behind text.
It can be used to improve visual appearance and create different text
effects.
The basic syntax contains horizontal offset, vertical offset, blur radius and shadow color.
.heading {
text-shadow:
2px 2px 4px gray;
}
Text Shadow Example
Multiple Text Shadows
Multiple shadows can be added to the same text by separating each shadow with a comma.
.heading {
text-shadow:
2px 2px 3px red,
4px 4px 5px blue;
}
CSS Text
CSS provides several properties for controlling the appearance of text.
Common properties include color,
font-size, text-align,
text-decoration, text-transform,
letter-spacing and line-height.
.text {
color: darkblue;
font-size: 20px;
text-align: center;
line-height: 1.6;
}
Line Height
The line-height property controls the vertical distance
between lines of text. Increasing line height can make paragraphs
easier to read.
p {
line-height: 1.8;
}
CSS No Wrap
The white-space property controls how whitespace and line
breaks are handled. The value nowrap prevents text from
wrapping onto the next line.
.text {
white-space: nowrap;
}
white-space: nowrap; can cause content to extend outside
its container when the text is longer than the available width.
CSS Fonts
CSS font properties control how text is displayed. Developers can specify the font family, size, weight, style and other characteristics.
Font Family
The font-family property specifies the typeface used for
displaying text.
body {
font-family: Arial, sans-serif;
}
Font Size
The font-size property controls the size of text.
h1 {
font-size: 36px;
}
p {
font-size: 18px;
}
Font Weight
The font-weight property controls the thickness of text.
Common values include normal, bold and
numeric values such as 400 and 700.
p {
font-weight: bold;
}
Font Style
The font-style property can be used to make text italic.
.text {
font-style: italic;
}
CSS Word Wrap
The overflow-wrap property allows long words or strings
to wrap onto the next line when they cannot fit inside their container.
This is particularly useful for long URLs, email addresses or other continuous strings of characters.
.content {
overflow-wrap: break-word;
}
CSS Word Break
The word-break property specifies how words should break
when they reach the edge of a container.
The value break-all allows the browser to break a word
at almost any character when necessary.
.content {
word-break: break-all;
}
Difference Between Word Wrap and Word Break
| Property | Purpose | Example |
|---|---|---|
overflow-wrap |
Allows long words or strings to wrap when necessary. |
overflow-wrap: break-word;
|
word-break |
Controls where words can be broken when reaching the container boundary. |
word-break: break-all;
|
white-space: nowrap |
Prevents text from wrapping onto a new line. |
white-space: nowrap;
|
Complete CSS3 Example
The following example combines borders, border radius, background gradients, text effects, fonts and spacing properties to create a modern CSS3 card.
<div class="card">
<h2>CSS3 Card</h2>
<p>
Learn modern CSS3 features.
</p>
</div>
<style>
.card {
width: 300px;
padding: 25px;
margin: 20px auto;
background:
linear-gradient(
135deg,
#0d6efd,
#6f42c1
);
color: white;
border: 2px solid #ffffff;
border-radius: 15px;
text-align: center;
box-shadow:
0 5px 15px rgba(0, 0, 0, 0.3);
}
.card h2 {
font-family: Arial, sans-serif;
text-shadow:
2px 2px 4px black;
}
.card p {
line-height: 1.6;
}
</style>
CSS3 Card
Learn modern CSS3 features.
text-shadow property adds shadows to text, while font
properties control the appearance of characters. Properties such as
white-space, overflow-wrap and
word-break help control how text behaves inside containers.
Tailwind CSS
Learn Tailwind CSS, utility-first styling, installation, colors, backgrounds, spacing, typography, flexbox, grid, positioning and responsive design.
Tailwind CSS is a utility-first CSS framework that provides small, reusable utility classes for styling HTML elements. Instead of writing separate CSS rules for every component, developers can apply utility classes directly to HTML elements.
Tailwind CSS makes it easier to create custom and responsive designs. It provides utility classes for colors, spacing, sizing, typography, borders, shadows, layouts and many other CSS properties.
What is Tailwind CSS?
Tailwind CSS provides predefined utility classes that represent
individual CSS properties. For example, instead of creating a custom
CSS class for a blue button, you can directly use classes such as
bg-blue-500, text-white and
p-2.
<button class="bg-blue-500 text-white p-2">
Button
</button>
Here, bg-blue-500 sets the background color,
text-white sets the text color and
p-2 adds padding.
Utility-First CSS
The utility-first approach means using small, single-purpose classes to build the complete design of an element. Each class generally performs one specific styling task.
For example, traditional CSS may require creating a custom
.btn class. With Tailwind CSS, the same styling can be
created by combining utility classes directly in HTML.
/* Traditional CSS */
.btn {
background-color: blue;
color: white;
padding: 10px;
}
<!-- Tailwind CSS -->
<button class="bg-blue-500 text-white p-2">
Button
</button>
Advantages of Tailwind CSS
Faster Development
Utility classes allow developers to style elements quickly without creating custom CSS rules for every component.
Less Unused CSS
Tailwind's build process can remove unused styles, helping to keep the final CSS output smaller.
Easy Maintenance
Consistent utility classes help developers maintain a common design system throughout a project.
Minimal Custom CSS
Many common styles can be created using Tailwind utilities without writing separate CSS rules.
Installing Tailwind CSS
Tailwind CSS can be used in different ways depending on the type of project. For learning and quick experiments, the CDN approach is convenient. For production projects, a proper Node.js and npm setup provides a complete build process.
Tailwind CSS Using CDN
The CDN method allows Tailwind CSS to be used directly in an HTML file without installing packages or creating a build configuration. It is useful for beginners, practice and small demonstrations.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
>
<script
src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"
></script>
</head>
<body>
<h1 class="text-blue-500 text-3xl font-bold">
Hello Tailwind CSS
</h1>
</body>
</html>
Advantages of CDN
- Easy to set up.
- No package installation is required.
- Useful for learning and practice.
- Suitable for quick prototypes.
Disadvantages of CDN
- Not the preferred approach for production projects.
- HTML can contain many utility classes.
- A proper build process provides more control for larger applications.
Tailwind Colors
Tailwind provides utility classes for applying colors to text, backgrounds and borders. Common color families include gray, red, blue, indigo, purple, green, yellow and pink.
Text Color
Text color classes start with text-. For example,
text-black makes text black and
text-white makes text white.
<p class="text-red-500">
Red Text
</p>
<p class="text-blue-500">
Blue Text
</p>
<p class="text-green-500">
Green Text
</p>
Color Shades
Tailwind color families use numeric shades. Generally, lower numbers
represent lighter shades while higher numbers represent darker shades.
Common shades include 50, 100,
200, 300, 400,
500, 600, 700,
800, 900 and 950.
<p class="text-blue-300">
Light Blue
</p>
<p class="text-blue-500">
Standard Blue
</p>
<p class="text-blue-700">
Dark Blue
</p>
<p class="text-blue-900">
Very Dark Blue
</p>
text-blue-500 contains three parts:
text represents the property,
blue represents the color family and
500 represents the shade.
Tailwind Background Colors
Background colors are applied using bg- utility classes.
These classes can be used to create backgrounds for buttons, cards,
sections and other containers.
<div class="bg-blue-500 text-white p-4">
Blue Background
</div>
Tailwind Background Images
Tailwind allows background images to be specified using an arbitrary
value. The bg-[url(...)] syntax can be used to define a
background image.
<div
class="bg-[url('/image.jpg')]
bg-cover
bg-center
">
Background Image
</div>
Background Repeat
Tailwind provides utility classes for controlling how background images
repeat. Common classes include bg-repeat,
bg-no-repeat, bg-repeat-x and
bg-repeat-y.
bg-repeat
bg-no-repeat
bg-repeat-x
bg-repeat-y
bg-repeat-space
Background Size
Background size utilities control how a background image fits inside an element.
bg-auto
bg-cover
bg-contain
The bg-cover class scales the image so that it covers the
entire container, while bg-contain scales the image so
that the complete image fits inside the container.
Tailwind Gradients
Tailwind provides gradient direction utilities that can be combined
with gradient color utilities to create smooth color transitions.
Common direction classes include bg-gradient-to-r,
bg-gradient-to-l, bg-gradient-to-t and
bg-gradient-to-b.
<div
class="bg-gradient-to-r
from-blue-500
to-purple-500
text-white
p-4"
>
Tailwind Gradient
</div>
Tailwind Width
Tailwind provides width utilities using the w- prefix.
These classes can define fixed widths, fractional widths, full width
and viewport-based widths.
w-0
w-auto
w-1/2
w-1/3
w-1/4
w-1/6
w-full
w-screen
w-min
w-max
For example, w-1/2 gives an element half of the available
width, while w-full makes the element occupy the full
available width.
<div class="w-1/2 bg-blue-500 text-white p-3">
50% Width
</div>
<div class="w-full bg-green-500 text-white p-3">
Full Width
</div>
Tailwind Height
Height utilities use the h- prefix. They can be used to
control the height of elements and containers.
h-0
h-auto
h-px
h-1/2
h-1/3
h-1/4
h-screen
The h-screen class makes an element span the height of
the viewport.
Tailwind Padding
Padding utilities add space inside an element. Tailwind uses the
p- prefix for padding on all sides and directional
prefixes such as px-, py-,
pt-, pr-, pb- and
pl-.
<div class="p-4 bg-blue-500 text-white">
Padding on all sides
</div>
<div class="px-6 py-3 bg-green-500 text-white">
Horizontal and Vertical Padding
</div>
Tailwind Margin
Margin utilities create space outside an element. Tailwind uses
m- for all sides and directional utilities such as
mx-, my-, mt-,
mr-, mb- and ml-.
<div class="m-4 bg-blue-500 text-white p-3">
Margin on all sides
</div>
<div class="mx-auto bg-green-500 text-white p-3">
Horizontally Centered
</div>
Tailwind Fonts
Tailwind provides utility classes for font family, font size and font weight. These utilities allow developers to control the appearance of text directly from HTML.
Font Family
font-sans
font-serif
font-mono
Font Size
text-xs
text-sm
text-base
text-lg
text-xl
text-2xl
text-3xl
text-4xl
Font Weight
font-thin
font-light
font-normal
font-medium
font-semibold
font-bold
font-extrabold
font-black
<h2 class="text-3xl font-bold text-blue-600">
Tailwind CSS
</h2>
Text Alignment
Tailwind provides utility classes for controlling the alignment of text.
text-left
text-center
text-right
text-justify
<p class="text-center text-lg">
Center Aligned Text
</p>
Text Decoration
Text decoration utilities can be used to underline text, add a line-through effect or remove an existing underline.
underline
line-through
no-underline
Text Transformation
Tailwind provides utility classes for changing the capitalization of text.
uppercase
lowercase
capitalize
normal-case
Tailwind Borders
Border utilities allow developers to add borders and control their width, style and color.
Border Width
border
border-0
border-2
border-4
border-8
border-t
border-r
border-b
border-l
Border Style
border-solid
border-dashed
border-dotted
border-double
border-none
border-hidden
Border Color
<div
class="border-2
border-blue-500
border-solid
p-4"
>
Border Example
</div>
Border Radius
Tailwind provides rounded utility classes for creating rounded corners. These classes range from small rounded corners to completely circular elements.
rounded-none
rounded-sm
rounded
rounded-md
rounded-lg
rounded-xl
rounded-2xl
rounded-3xl
rounded-full
Tailwind Box Shadow
Shadow utilities add visual depth to cards, buttons and other components. Tailwind provides different shadow sizes.
shadow-sm
shadow
shadow-md
shadow-lg
shadow-xl
shadow-2xl
shadow-inner
shadow-none
<div class="shadow-lg p-4 rounded-lg">
Shadow Example
</div>
Tailwind Opacity
Opacity utilities control the transparency of an element. An opacity value determines how transparent or visible an element appears.
<div class="opacity-50">
Semi Transparent Element
</div>
Tailwind Display Classes
Display utilities control how an element participates in the layout.
Tailwind provides classes such as block,
inline-block, inline,
flex and inline-flex.
block
inline-block
inline
flex
inline-flex
Tailwind Flexbox
Tailwind provides utility classes for creating flexible layouts using
CSS Flexbox. The flex class creates a flex container,
while additional utilities control direction, wrapping and item sizing.
<div class="flex">
<div class="bg-primary text-white flex-1 p-3">
Item 1
</div>
<div class="bg-success text-white flex-1 p-3">
Item 2
</div>
</div>
Flex Direction
Flex direction determines whether flex items are arranged horizontally or vertically.
flex-row
flex-row-reverse
flex-col
flex-col-reverse
Flex Wrap
Flex wrapping controls whether flex items stay on one line or move to additional lines when there is not enough space.
flex-wrap
flex-nowrap
flex-wrap-reverse
Tailwind Grid
CSS Grid is useful for creating layouts with rows and columns. Tailwind
provides grid and grid-cols-* utilities to
create grid layouts.
<div class="grid grid-cols-2 gap-4">
<div class="bg-blue-500 text-white p-3">
1
</div>
<div class="bg-green-500 text-white p-3">
2
</div>
<div class="bg-purple-500 text-white p-3">
3
</div>
<div class="bg-red-500 text-white p-3">
4
</div>
</div>
Grid Columns
Tailwind provides grid column utilities from
grid-cols-1 through grid-cols-12.
grid-cols-1
grid-cols-2
grid-cols-3
grid-cols-4
grid-cols-6
grid-cols-12
Grid Column Span
The col-span utilities allow an element to occupy multiple
columns in a grid.
<div class="grid grid-cols-6 gap-4">
<div class="col-span-4 bg-blue-500 text-white p-3">
Spans 4 Columns
</div>
</div>
Grid Rows
Tailwind also provides utilities for defining grid rows such as
grid-rows-1, grid-rows-2,
grid-rows-3 and more.
grid-rows-1
grid-rows-2
grid-rows-3
grid-rows-4
grid-rows-5
grid-rows-6
Tailwind Gap
The gap utilities add space between rows and columns in
Flexbox and Grid layouts. Tailwind also provides separate horizontal
and vertical gap utilities.
gap-0
gap-1
gap-2
gap-3
gap-4
gap-6
gap-8
gap-x-4
gap-y-4
Tailwind Position
Position utilities control how an element is positioned in relation to the normal document flow or its containing element.
static
relative
absolute
fixed
sticky
Relative and Absolute Positioning
The relative class establishes a positioning context,
while absolute allows an element to be positioned relative
to its positioned ancestor.
<div class="relative h-32 bg-gray-200">
<div
class="absolute top-2 right-2
bg-blue-500 text-white p-2"
>
Positioned Box
</div>
</div>
Tailwind Z-Index
Z-index utilities control the stacking order of positioned elements. An element with a higher z-index generally appears above an element with a lower z-index when they overlap.
z-0
z-10
z-20
z-30
z-40
z-50
z-auto
Tailwind Overflow
Overflow utilities control what happens when content is larger than its container.
overflow-auto
overflow-hidden
overflow-visible
overflow-scroll
overflow-auto
Adds scrollbars when the content requires them.
overflow-hidden
Hides content that extends outside the container.
overflow-visible
Allows content to extend outside the container.
overflow-scroll
Always displays scrollbars for the container.
Tailwind Responsive Design
Tailwind follows a mobile-first responsive design approach. Utility classes can be prefixed with breakpoint names to apply different styles at different screen sizes.
The main responsive breakpoints are sm,
md, lg, xl and
2xl.
| Breakpoint | Minimum Width |
|---|---|
sm |
640px |
md |
768px |
lg |
1024px |
xl |
1280px |
2xl |
1536px |
Responsive Example
In the following example, the text size starts small on mobile devices and becomes larger on medium and large screens.
<h1
class="text-xl md:text-3xl lg:text-5xl"
>
Responsive Heading
</h1>
Here, text-xl applies the default mobile size,
md:text-3xl changes the size on medium screens and
lg:text-5xl changes it again on large screens.
Responsive Grid Example
Tailwind responsive classes can also be used to change the number of columns depending on the screen size.
<div
class="grid
grid-cols-1
md:grid-cols-2
lg:grid-cols-4
gap-4"
>
<div class="bg-blue-500 p-4">1</div>
<div class="bg-green-500 p-4">2</div>
<div class="bg-red-500 p-4">3</div>
<div class="bg-purple-500 p-4">4</div>
</div>
On small screens, the layout contains one column. On medium screens, it changes to two columns, and on large screens, it displays four columns.
Complete Tailwind CSS Example
The following example combines Tailwind utilities for background colors, typography, spacing, borders, rounded corners, shadows and responsive design.
<div
class="max-w-md
mx-auto
p-6
bg-blue-500
text-white
rounded-xl
shadow-lg
text-center"
>
<h2 class="text-3xl font-bold mb-3">
Tailwind CSS
</h2>
<p class="text-lg mb-4">
Build modern websites using utility classes.
</p>
<button
class="bg-white
text-blue-600
px-4
py-2
rounded-lg
font-semibold"
>
Learn More
</button>
</div>
Tailwind CSS
Build modern websites using utility classes.
JavaScript
Learn JavaScript fundamentals including variables, data types, operators, conditions, loops, arrays, strings, functions, objects, events and DOM manipulation.
JavaScript Introduction
JavaScript is a high-level programming language mainly used to make web pages interactive and dynamic. It allows developers to respond to user actions, change webpage content, validate forms, create animations and communicate with servers.
HTML is used to create the structure of a webpage, CSS is used to style the webpage, and JavaScript is used to add behavior and interactivity.
Client-Side Scripting
JavaScript can execute inside a web browser and respond to actions performed by the user.
Dynamic Web Pages
JavaScript can dynamically change HTML content, CSS styles and webpage elements without refreshing the page.
Form Validation
JavaScript can check form values before they are submitted to a server.
Web Applications
JavaScript is widely used to build modern interactive websites and web applications.
Your First JavaScript Program
The console.log() function is commonly used to display
information in the browser console.
console.log("Hello JavaScript!");
JavaScript Variables
Variables are containers used to store data in a program. JavaScript
provides three keywords for declaring variables:
var, let and const.
let is generally used when a value may change.
const is used when a variable should not be reassigned.
var is an older way of declaring variables.
let name = "Dhanush";
let age = 15;
const country = "India";
console.log(name);
console.log(age);
console.log(country);
15
India
JavaScript Data Types
A data type defines the kind of value stored in a variable. JavaScript has primitive and non-primitive data types.
Primitive Data Types
String, Number, Boolean, Undefined, Null, BigInt and Symbol are primitive data types.
Non-Primitive Data Types
Objects, arrays and functions are commonly used as non-primitive reference values.
let name = "Dhanush";
let age = 15;
let passed = true;
console.log(typeof name);
console.log(typeof age);
console.log(typeof passed);
number
boolean
JavaScript Operators
Operators are symbols used to perform operations on values and variables.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication and division.
let a = 10;
let b = 3;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
7
30
3.3333333333333335
1
Assignment Operators
Assignment operators are used to assign or update values stored in variables.
let x = 10;
x += 5;
console.log(x);
x -= 2;
console.log(x);
13
Comparison Operators
Comparison operators compare two values and return a Boolean value:
true or false.
let a = 10;
let b = 20;
console.log(a < b);
console.log(a > b);
console.log(a == b);
console.log(a != b);
console.log(a === b);
Logical Operators
Logical operators are used to combine multiple conditions.
The main logical operators are &&,
|| and !.
let age = 25;
console.log(age > 18 && age < 60);
console.log(age < 18 || age > 60);
console.log(!(age > 18));
Conditional Statements
Conditional statements allow a program to make decisions based on conditions.
if Statement
let age = 20;
if (age >= 18) {
console.log("Eligible to vote");
}
if...else Statement
let age = 16;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
else if Statement
The else if statement is used when multiple conditions
need to be checked.
let mark = 85;
if (mark >= 90) {
console.log("A+");
} else if (mark >= 80) {
console.log("A");
} else if (mark >= 70) {
console.log("B");
} else {
console.log("C");
}
switch Statement
The switch statement is useful when one expression
needs to be compared with several possible values.
let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Invalid Day");
}
Looping Structures
Loops are used when the same block of code needs to execute
repeatedly. JavaScript provides for,
while, do...while and other iteration
mechanisms.
for Loop
A for loop is commonly used when the number of
repetitions is known.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
2
3
4
5
while Loop
A while loop executes as long as its condition
remains true.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
do...while Loop
The do...while loop executes its code block at least
once before checking the condition.
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
break and continue
The break statement stops a loop completely.
The continue statement skips the current iteration
and continues with the next iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
2
4
5
JavaScript Functions
A function is a reusable block of code designed to perform a particular task. Functions help reduce code repetition and make programs easier to organize.
Function Declaration
function greet() {
console.log("Welcome to JavaScript!");
}
greet();
Function Parameters
Parameters allow a function to receive values from the code that calls it.
function greet(name) {
console.log("Hello " + name);
}
greet("Dhanush");
Return Statement
The return statement sends a value back from a
function to the code that called it.
function add(a, b) {
return a + b;
}
let result = add(10, 20);
console.log(result);
JavaScript Arrays
An array is a collection of values stored in a single variable.
Array elements are accessed using indexes, and the first index
starts from 0.
let fruits = [
"Apple",
"Mango",
"Orange"
];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
Mango
Orange
Array Length
The length property returns the number of elements
present in an array.
let fruits = [
"Apple",
"Mango",
"Orange"
];
console.log(fruits.length);
JavaScript Array Methods
Array methods are built-in methods used to add, remove, search, transform and process elements in arrays.
push()
The push() method adds one or more elements to the
end of an array.
let fruits = ["Apple", "Mango"];
fruits.push("Orange");
console.log(fruits);
pop()
The pop() method removes the last element from an array.
let fruits = [
"Apple",
"Mango",
"Orange"
];
fruits.pop();
console.log(fruits);
forEach()
The forEach() method executes a function once for
every element in an array.
let numbers = [10, 20, 30];
numbers.forEach(function(value) {
console.log(value);
});
map()
The map() method creates a new array by applying a
function to each element.
let numbers = [1, 2, 3, 4];
let squares = numbers.map(function(value) {
return value * value;
});
console.log(squares);
filter()
The filter() method creates a new array containing
only the elements that satisfy a condition.
let numbers = [10, 15, 20, 25, 30];
let result = numbers.filter(function(value) {
return value > 20;
});
console.log(result);
find()
The find() method returns the first element that
satisfies a specified condition.
let numbers = [10, 20, 30, 40];
let result = numbers.find(function(value) {
return value > 25;
});
console.log(result);
JavaScript Strings
A string is a sequence of characters used to represent text. Strings can be created using single quotes, double quotes or template literals.
let name = "Dhanush";
let city = 'Chennai';
let message = `Welcome ${name}`;
console.log(name);
console.log(city);
console.log(message);
JavaScript String Methods
JavaScript provides several built-in methods for searching, extracting, modifying and processing strings.
length
The length property returns the number of characters
in a string.
let text = "JavaScript";
console.log(text.length);
toUpperCase()
let text = "javascript";
console.log(text.toUpperCase());
toLowerCase()
let text = "JAVASCRIPT";
console.log(text.toLowerCase());
trim()
The trim() method removes whitespace from the
beginning and end of a string.
let text = " Hello JavaScript ";
console.log(text.trim());
includes()
The includes() method checks whether a string contains
a specified value.
let text = "I am learning JavaScript";
console.log(text.includes("JavaScript"));
slice()
The slice() method extracts a portion of a string
without modifying the original string.
let text = "JavaScript";
console.log(text.slice(0, 4));
JavaScript Objects
An object is a collection of related data stored using key-value pairs. Objects are useful for representing real-world entities such as students, employees, products and customers.
let student = {
name: "Dhanush",
age: 15,
course: "JavaScript"
};
console.log(student.name);
console.log(student.age);
console.log(student.course);
15
JavaScript
Modifying Object Properties
Object properties can be changed, added or removed using JavaScript.
let student = {
name: "Dhanush",
age: 15
};
student.age = 15;
student.city = "Chennai";
console.log(student);
Document Object Model (DOM)
DOM stands for Document Object Model. When a browser loads an HTML document, it creates a tree-like representation of the webpage called the DOM.
JavaScript can use the DOM to access HTML elements, change their content, modify CSS styles, create new elements, remove elements and respond to user actions.
Selecting an Element Using ID
The getElementById() method selects an HTML element
using its id.
<h2 id="title">Hello</h2>
<script>
let heading = document.getElementById("title");
console.log(heading);
</script>
querySelector()
The querySelector() method selects the first element
that matches a CSS selector.
<p class="message">
Welcome
</p>
<script>
let element = document.querySelector(".message");
console.log(element);
</script>
Changing HTML Content
JavaScript can change the text displayed inside an HTML element
using the textContent property.
<h2 id="title">
Old Heading
</h2>
<script>
let title = document.getElementById("title");
title.textContent = "New Heading";
</script>
New Heading
Changing CSS Using DOM
JavaScript can modify the CSS style of an HTML element using the
style property.
<h2 id="title">
Hello JavaScript
</h2>
<script>
let title = document.getElementById("title");
title.style.color = "blue";
title.style.backgroundColor = "lightyellow";
</script>
JavaScript Events
An event is an action that occurs in a webpage. Examples include clicking a button, typing into an input, moving the mouse and submitting a form.
JavaScript can listen for these events and execute a function when the event occurs.
addEventListener()
The addEventListener() method is used to attach an
event handler to an HTML element.
<button id="btn">
Click Me
</button>
<script>
let button = document.getElementById("btn");
button.addEventListener("click", function() {
alert("Button Clicked!");
});
</script>
Common JavaScript Events
| Event | Description |
|---|---|
click |
Occurs when an element is clicked. |
mouseover |
Occurs when the mouse moves over an element. |
keydown |
Occurs when a keyboard key is pressed. |
input |
Occurs when an input value changes. |
submit |
Occurs when a form is submitted. |
change |
Occurs when the value of a form control changes. |
Creating HTML Elements Using DOM
JavaScript can create new HTML elements dynamically using the
createElement() method.
The appendChild() method can then be used to add the
newly created element to an existing HTML element.
<div id="container"></div>
<script>
let paragraph = document.createElement("p");
paragraph.textContent = "New paragraph created using JavaScript.";
let container = document.getElementById("container");
container.appendChild(paragraph);
</script>
JavaScript Form Handling
JavaScript can access form elements, read user input and validate the entered values before processing the form.
<input id="name" type="text">
<button id="btn">
Submit
</button>
<script>
let input = document.getElementById("name");
let button = document.getElementById("btn");
button.addEventListener("click", function() {
let name = input.value;
console.log(name);
});
</script>
The value property is used to retrieve the value
entered by the user in an input field.
JavaScript JSON
JSON stands for JavaScript Object Notation. It is a text-based format commonly used for exchanging data between a client and a server.
let student = {
"name": "Dhanush",
"age": 15,
"course": "JavaScript"
};
console.log(student.name);
JavaScript Error Handling
JavaScript provides try, catch and
finally blocks for handling runtime errors and
preventing unexpected program termination.
try {
let result = unknownVariable;
console.log(result);
} catch (error) {
console.log("An error occurred.");
}
JavaScript Local Storage
Local Storage allows a webpage to store small amounts of data in the user's browser. The stored data remains available even after the browser page is refreshed.
localStorage.setItem("name", "Dhanush");
let name = localStorage.getItem("name");
console.log(name);
ES6
Learn modern JavaScript features introduced in ES6 including let, const, arrow functions, template literals, destructuring, spread, rest, classes, modules, promises and async programming.
ES6 Introduction
ES6 stands for ECMAScript 2015. It is a major version of the JavaScript language that introduced many modern features and improved the way JavaScript applications are written.
ES6 makes JavaScript code more readable, reusable and easier to
maintain. Features such as let, const,
arrow functions, classes, destructuring and modules are commonly
used in modern JavaScript and React applications.
Modern Syntax
ES6 provides simpler and cleaner syntax for writing JavaScript programs.
Reusable Code
Features such as functions, classes and modules make code easier to organize and reuse.
let and const
ES6 introduced let and const for declaring
variables. Unlike var, they are block scoped.
The let variable can be reassigned, while a
const variable cannot be reassigned after initialization.
let age = 10;
age = 15;
const name = "Dhanush";
console.log(name);
console.log(age);
15
Arrow Functions
Arrow functions provide a shorter syntax for writing functions. They are commonly used in modern JavaScript and React applications.
const add = (a, b) => {
return a + b;
};
console.log(add(10, 20));
Template Literals
Template literals allow strings to be created using backticks.
JavaScript expressions can be inserted inside a template literal
using ${ }.
let name = "Dhaunsh";
let age = 15;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message);
Default Parameters
Default parameters allow a function to use a default value when an argument is not provided.
function greet(name = "Guest") {
console.log(`Hello ${name}`);
}
greet();
greet("Dhanush");
Hello Dhanush
Destructuring
Destructuring allows values from arrays or properties from objects to be extracted and assigned to variables in a simple way.
Array Destructuring
let colors = ["Red", "Green", "Blue"];
let [first, second, third] = colors;
console.log(first);
console.log(second);
console.log(third);
Object Destructuring
let student = {
name: "Dhanush",
age: 15
};
let { name, age } = student;
console.log(name);
console.log(age);
Spread Operator
The spread operator ... is used to expand the values
of an array or properties of an object. It is commonly used for
copying and combining arrays and objects.
let numbers1 = [10, 20, 30];
let numbers2 = [40, 50, 60];
let numbers = [...numbers1, ...numbers2];
console.log(numbers);
Rest Parameter
The rest parameter also uses .... It allows a function
to accept any number of arguments and collects them into an array.
function total(...numbers) {
let sum = 0;
for (let number of numbers) {
sum += number;
}
return sum;
}
console.log(total(10, 20, 30, 40));
Object Property Shorthand
ES6 provides a shorter syntax for creating object properties when the property name and variable name are the same.
let name = "Dhanush";
let age = 15;
let student = {
name,
age
};
console.log(student);
for...of Loop
The for...of loop is used to iterate over iterable
objects such as arrays, strings, Sets and Maps.
let fruits = ["Apple", "Mango", "Orange"];
for (let fruit of fruits) {
console.log(fruit);
}
Mango
Orange
Map
Map is an ES6 collection that stores data as
key-value pairs. Keys can be of different data types.
let students = new Map();
students.set(1, "Dhanush");
students.set(2, "Arun");
console.log(students.get(1));
Set
A Set is a collection that stores unique values.
Duplicate values are automatically ignored.
let numbers = new Set();
numbers.add(10);
numbers.add(20);
numbers.add(10);
numbers.add(30);
console.log(numbers);
Classes
ES6 introduced the class syntax for creating objects
and implementing object-oriented programming concepts. Classes can
contain constructors and methods.
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
display() {
console.log(this.name);
console.log(this.age);
}
}
let student = new Student("Harish", 24);
student.display();
Modules
ES6 modules allow JavaScript code to be divided into separate
files. The export keyword makes values available
outside a module, while import is used to use those
values in another file.
math.js
export function add(a, b) {
return a + b;
}
app.js
import { add } from "./math.js";
console.log(add(10, 20));
Promises
A Promise represents the eventual completion or failure of an asynchronous operation. A Promise can be in a pending, fulfilled or rejected state.
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation Successful");
} else {
reject("Operation Failed");
}
});
promise
.then(result => console.log(result))
.catch(error => console.log(error));
async and await
async and await provide a cleaner way to
work with Promises. An async function returns a
Promise, while await pauses the execution of the
asynchronous function until the Promise is settled.
function getData() {
return Promise.resolve("Data Received");
}
async function displayData() {
let result = await getData();
console.log(result);
}
displayData();
let, const, arrow functions, template
literals, destructuring, spread and rest operators, classes,
Maps, Sets, modules, Promises and async/await.
These features are widely used in modern JavaScript frameworks
such as React.
React JS
Learn React fundamentals including JSX, components, props, state, hooks, events, forms, routing and reusable user interfaces.
React JS Introduction
React is an open-source JavaScript library used to build user interfaces, especially for web applications. React follows a component-based approach, which allows developers to divide a webpage into small, reusable components.
React was originally developed at Facebook and was publicly released in 2013. It is mainly responsible for building the user interface layer of an application.
Component Based
React applications are built using reusable components. Each component can contain its own structure and behavior.
Reusable UI
Components can be created once and reused multiple times throughout an application.
Dynamic Interface
React can update the user interface when application data changes.
JavaScript Library
React uses JavaScript along with JSX to create interactive user interfaces.
React Installation
To develop React applications, Node.js and a code editor such as Visual Studio Code can be installed on the system. Node.js provides the npm package manager, which is used to install React packages and manage project dependencies.
After installing Node.js and Visual Studio Code, a React project can be created using a project creation tool.
npx create-react-app myapp
cd myapp
npm start
React JSX
JSX stands for JavaScript XML. It is a syntax extension used by React that allows developers to write markup that looks similar to HTML inside JavaScript code.
JSX makes React components easier to read and allows JavaScript
expressions to be embedded inside markup using curly braces
{ }.
function App() {
const name = "Dhanush";
return (
<div>
<h1>Hello {name}</h1>
<p>Welcome to React</p>
</div>
);
}
export default App;
Hello Dhanush
JSX Attributes
JSX uses attributes to provide additional information to elements.
Many HTML attributes use camelCase naming conventions in JSX.
For example, HTML uses class, while JSX uses
className.
function App() {
return (
<div className="container">
<h1 className="title">React JS</h1>
</div>
);
}
export default App;
React Components
Components are the building blocks of a React application. A component represents a reusable part of the user interface. Components can be combined together to create a complete webpage.
For example, a website can contain separate components for a header, navigation bar, product list, footer and contact form.
function Welcome() {
return (
<h2>Welcome to React</h2>
);
}
function App() {
return (
<div>
<Welcome />
<Welcome />
</div>
);
}
export default App;
Welcome to React
Welcome to React
Functional Components
A functional component is a JavaScript function that returns JSX. Functional components are the commonly used approach for creating React components in modern applications.
function Student() {
return (
<div>
<h2>Student Details</h2>
<p>Name: Harish</p>
</div>
);
}
export default Student;
Class Components
Class components are an older way of creating React components
using JavaScript classes. They extend React.Component
and normally contain a render() method.
import React from "react";
class App extends React.Component {
render() {
return (
<h1>Hello React Students</h1>
);
}
}
export default App;
React Props
Props, short for properties, are used to pass data from a parent component to a child component. Props are read-only and help make components reusable.
function Student(props) {
return (
<h2>
Student Name: {props.name}
</h2>
);
}
function App() {
return (
<div>
<Student name="Dhanush" />
<Student name="Arun" />
</div>
);
}
export default App;
Student Name: Arun
React State
State is data that belongs to a component and can change over time. When the state changes, React re-renders the component so that the user interface reflects the latest data.
The useState() Hook is commonly used to create and
update state in functional components.
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default App;
React Events
React events allow a component to respond to user actions such as clicking a button, typing into an input field, submitting a form or moving the mouse.
Event names in React use camelCase, such as
onClick, onChange and
onSubmit.
function App() {
const showMessage = () => {
alert("Button Clicked!");
};
return (
<button onClick={showMessage}>
Click Me
</button>
);
}
export default App;
Conditional Rendering
Conditional rendering allows React to display different content depending on a condition. JavaScript conditional operators such as the ternary operator can be used inside JSX.
function App() {
const isLoggedIn = true;
return (
<div>
{isLoggedIn
? <h2>Welcome User</h2>
: <h2>Please Login</h2>
}
</div>
);
}
export default App;
Welcome User
Rendering Lists
React can display multiple items from an array using the
map() method. A unique key should normally
be provided when rendering a list of elements.
function App() {
const fruits = [
"Apple",
"Mango",
"Orange"
];
return (
<ul>
{fruits.map((fruit, index) => (
<li key={index}>
{fruit}
</li>
))}
</ul>
);
}
export default App;
React Forms
Forms are used to collect information from users. React can control form fields using state and event handlers.
An input whose value is controlled by React state is called a controlled component.
import { useState } from "react";
function App() {
const [name, setName] = useState("");
return (
<div>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter Name"
/>
<p>Name: {name}</p>
</div>
);
}
export default App;
CSS in React
CSS can be used to style React components. Styles can be written
directly using the style attribute or placed in a
separate CSS file and imported into the component.
Inline CSS
function App() {
const headingStyle = {
color: "blue",
fontSize: "30px"
};
return (
<h1 style={headingStyle}>
Hello React
</h1>
);
}
export default App;
External CSS
import "./App.css";
function App() {
return (
<h1 className="title">
Hello React
</h1>
);
}
export default App;
React Hooks
Hooks are functions provided by React that allow functional components to use features such as state, effects, context and references.
Hooks should normally be called at the top level of React components or custom Hooks. They should not be called inside loops, conditions or nested functions.
Basic Hooks
useState, useEffect and
useContext are commonly used basic Hooks.
Additional Hooks
React also provides Hooks such as useReducer,
useCallback, useMemo and
useRef.
useState Hook
The useState() Hook allows a functional component to
store and update data. It returns the current state value and a
function used to update that value.
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default App;
useEffect Hook
The useEffect() Hook is used to perform side effects
in functional components. Side effects can include fetching data,
updating the document title, setting up subscriptions or working
with browser APIs.
import { useState, useEffect } from "react";
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default App;
count changes in this example, the effect runs again.
useContext Hook
The useContext() Hook allows components to access
shared data without passing props through every level of the
component tree.
Context is useful for application-wide data such as authentication status, theme information or language settings.
import { createContext, useContext } from "react";
const UserContext = createContext();
function App() {
return (
<UserContext.Provider value="Harish">
<Profile />
</UserContext.Provider>
);
}
function Profile() {
const user = useContext(UserContext);
return (
<h2>
Welcome {user}
</h2>
);
}
export default App;
useReducer Hook
The useReducer() Hook is useful when state management
becomes more complex. Instead of directly updating the state,
actions are dispatched to a reducer function that determines the
next state.
import { useReducer } from "react";
function reducer(state, action) {
switch (action.type) {
case "add":
return state + 1;
case "subtract":
return state - 1;
default:
return state;
}
}
function App() {
const [count, dispatch] = useReducer(reducer, 0);
return (
<div>
<h2>{count}</h2>
<button onClick={() => dispatch({ type: "add" })}>
Add
</button>
<button onClick={() => dispatch({ type: "subtract" })}>
Subtract
</button>
</div>
);
}
export default App;
useMemo Hook
The useMemo() Hook can be used to memoize the result
of a calculation. React can reuse the previously calculated value
until one of its dependencies changes.
import { useState, useMemo } from "react";
function App() {
const [number, setNumber] = useState(5);
const square = useMemo(() => {
return number * number;
}, [number]);
return (
<div>
<p>Square: {square}</p>
<button onClick={() => setNumber(number + 1)}>
Increase
</button>
</div>
);
}
export default App;
useCallback Hook
The useCallback() Hook is used to memoize a function.
It can be useful when passing functions to child components and
avoiding unnecessary function recreation.
import { useState, useCallback } from "react";
function App() {
const [count, setCount] = useState(0);
const increase = useCallback(() => {
setCount(value => value + 1);
}, []);
return (
<div>
<h2>{count}</h2>
<button onClick={increase}>
Increase
</button>
</div>
);
}
export default App;
useRef Hook
The useRef() Hook can store a value that persists
between renders without causing a re-render when the value changes.
It is also commonly used to create a reference to a DOM element.
import { useRef } from "react";
function App() {
const inputRef = useRef();
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>
Focus Input
</button>
</div>
);
}
export default App;
React Fragment
A React Fragment allows a component to return multiple elements without adding an unnecessary wrapper element to the DOM.
Fragments can be written using <React.Fragment>
or the shorter syntax <></>.
function App() {
return (
<>
<h1>React</h1>
<p>JavaScript Library</p>
</>
);
}
export default App;
React Routing
React applications often use routing to display different
components for different URLs without completely reloading the
webpage. The react-router-dom package is commonly
used for client-side routing.
npm install react-router-dom
A router can define routes such as Home, About, Services and Contact pages.
import {
BrowserRouter,
Routes,
Route,
Link
} from "react-router-dom";
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
{" | "}
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Fetching API Data
React applications often communicate with backend APIs to retrieve
or send data. JavaScript's fetch() function can be
used to request data from an API.
The API request can commonly be performed inside the
useEffect() Hook when the component loads.
import { useEffect, useState } from "react";
function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => setUsers(data));
}, []);
return (
<div>
{users.map(user => (
<p key={user.id}>
{user.name}
</p>
))}
</div>
);
}
export default App;
React Hook Form
React Hook Form is a library used to simplify form handling and validation in React applications. It provides an efficient way to manage form values, validation and submission.
It can be useful for registration forms, login forms, contact forms and other applications that require user input.
import { useForm } from "react-hook-form";
function App() {
const {
register,
handleSubmit
} = useForm();
const onSubmit = data => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...register("name")}
placeholder="Enter Name"
/>
<button type="submit">
Submit
</button>
</form>
);
}
export default App;
useState, useEffect,
useContext, useReducer,
useMemo, useCallback and
useRef provide additional functionality to
functional components. React can also be used with forms,
APIs, CSS and routing to build complete web applications.