map method

The map method in JavaScript is an array method used to create a new array by applying a provided function to each element in the original array. It’s particularly useful when you need to transform or process each element and return a new array with the results, leaving the original array unchanged.

Syntax:


const newArray = array.map(function(element, index, array) {
  // Return transformed element here
}, thisArg);

element: The current element being processed in the array.

index (optional): The index of the current element being processed.

array (optional): The array map was called upon.

thisArg (optional): A value to use as this when executing the callback function.

Characteristics of map

1. Returns a New Array: The map method returns a new array containing the results of applying the provided function to each element of the original array.

2. Original Array Unchanged: The original array remains unchanged after the map operation.

3. Transforms Each Element: The function provided to map transforms each element in the array, and the result of this transformation is stored in the new array.

4. Iterates Over Every Element: The function passed to map is called for every element in the array, even if the element is undefined, null, or an empty slot.

5. Chaining: Since map returns a new array, you can chain other array methods like filter, reduce, etc., on the result.

Example:


const numbers = [1, 2, 3, 4];
const updatedNumbers = numbers.map(num => num * 5);

console.log(updatedNumbers); // Output: [5, 10, 15, 20]
console.log(numbers); // Output: [1, 2, 3, 4] (original array is unchanged)

Extracting Specific Properties:


const users = [
    {name: 'John', age: 39},
    {name: 'Tom', age: 38},
    {name: 'Mathew', age: 35}
];

const names = users.map(user => user.name);

console.log(names); // Output: ['John', 'Tom', 'Mathew']

forEach method

The forEeach method in JavaScript is an array method used to execute a provided function once for each element in an array. It’s beneficial when you want to perform side effects such as logging, updating each element in place, or calling functions that do not require returning a new array.

Syntax:


array.forEach(function(element, index, array) {
  // Your code here
}, thisArg);

element: The current element being processed in the array.

index (optional): The index of the current element being processed.

array (optional): The array forEach was called upon.

thisArg (optional): A value to use as this when executing the callback function.

Characteristics of forEach

1. Does Not Return a Value: The forEach method always returns undefined. It doesn’t return a new array, unlike some other array methods like map.

2. Iterates Over Every Element: The function passed to forEach is executed for every element of the array, even if it is undefined, null, or an empty slot.

3. Cannot Be Interrupted: You cannot break out of a forEach loop using break or continue. If you need to stop iteration based on a condition, consider using a for loop or the some or every methods.

4. Modifying the Array: You can modify the original array within the forEach loop by directly altering its elements.

Example: Modify the array element


const numbers = [1, 2, 3, 4];
numbers.forEach((num, index, arr) => {
    arr[index] = num * 5; // multiply by 5 for each element in the original array
});
console.log(numbers); // Output: [5, 10, 15, 20]

find() method

In JavaScript, find methods is used to search for elements in an array based on a given condition.

KeyPoints:

1. The find method returns the value of the first element in the array that satisfies the provided testing function.

2. It returns the first element that matches the condition. If no elements match, it returns undefined.

Example:

1. Filtering Even Numbers:


const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 10];
const data = numbers.find(num => num % 2 === 0);
console.log(data); // Output: 2

2. Filtering string from the array


const fruits = ['Apple', 'Banana', 'Orange'];
const filteredData= fruits.find(fruit => fruit== 'Orange');
console.log(filteredData); // Output: Orange

3. Filtering Objects in an Array


const employees = [
  { name: 'John', age: 38 },
  { name: 'Tom', age: 37 },
  { name: 'Mathew', age: 35 },
  { name: 'Andrew', age: 30 },
];

const data = employees.find(employee => employee.age > 36);
console.log(data); // Output: { name: 'John', age: 38 }

filter() method

In JavaScript, filter is an array method used to search for elements in an array based on a given condition.

Key Points

1. The filter method creates a new array containing all elements that pass the test implemented by the provided function.

2. It returns an array of all elements that satisfy the condition. If no elements match the condition, it returns an empty array.

Example:

1. Filtering Even Numbers:


const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 10];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6, 8 ,10]

2. Filtering Odd Numbers:


const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 10];
const oddNumbers = numbers.filter(num => num % 2 !== 0);
console.log(evenNumbers); // Output: [1, 3, 5, 7]

3. Filtering string from the array


const fruits = ['Apple', 'Banana', 'Orange'];
const filteredData= fruits.filter(fruit => fruit== 'Orange');
console.log(filteredData); // Output: ['Orange']

4. Filtering Objects in an Array


const employees = [
  { name: 'John', age: 38 },
  { name: 'Tom', age: 37 },
  { name: 'Mathew', age: 35 },
  { name: 'Andrew', age: 30 },
];

const data = employees.filter(employee => employee.age > 36);
console.log(data); // Output: [ { name: 'John', age: 38 }, { name: 'Tom', age: 37 } ]

JavaScript if else statement

In JavaScript, if, else, and else if are control flow statements that allow you to execute certain blocks of code based on specific conditions. These statements help you make decisions in your code.

1. if Statement

The if statement is used to execute a block of code if a specified condition is true.

Syntax:


if (condition) {
    // Code to execute if the condition is true
}

Example:


let age = 21;
if (age >= 21) {
    console.log("Age of boy adult.");
}

In this example, the message “Age of boy adult.” will be logged to the console because the condition age >= 21 is true.

2. else Statement

The else statement is used to execute a block of code if the if condition is false.

Syntax:


if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}

Example:


let age = 20;
if (age >= 21) {
    console.log("You are an adult.");
} else {
    console.log("You are not an adult.");
}

In this example, the message “You are not an adult.” will be logged to the console because the condition age >= 21 is false.

else if Statement

The else if statement allows you to check additional conditions if the previous if condition is false. You can chain multiple else if statements together.

Syntax:


if (condition1) {
    // Code to execute if condition1 is true
} else if (condition2) {
    // Code to execute if condition1 is false and condition2 is true
} else {
    // Code to execute if both condition1 and condition2 are false
}

Example:


let score = 85;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else if (score >= 70) {
    console.log("Grade: C");
} else {
    console.log("Grade: F");
}

In this example, the message Grade: B will be logged to the console because the condition score >= 80 is true, and the conditions before it are false.

JavaScript comparison

JavaScript comparison operators are used to compare two values and return a boolean value (true or false) based on the comparison. These operators are essential in controlling the flow of a program, especially in conditional statements like if, while, and for loops.

1. Equality (==) Operator

Compares two values for equality after converting them to a common type (type coercion).

Returns true if the values are equal, otherwise false


10 == "10";     // true (number 10 is coerced to string "10")
20 == 20     // true (number 20 is coerced to number 20)

2. Strict Equality (===)

Compares two values for equality without performing type conversion. Both value and type must be the same.


10 === "10"; // false
10 === 10;   // true

3. Inequality (!=)

Compares two values for inequality without performing type conversion.


10 !== "10"; // true
10 !== 10;   // false

4. Strict Inequality (!==)

Compares two values for inequality without performing type conversion.


10 !== "10"; // true
10 !== 10;   // false

5. Greater Than (>)

Returns true if the left operand is greater than the right operand.


10 > 5; // true

6. Greater Than or Equal To (>=)

Returns true if the left operand is greater than or equal to the right operand.


10 >= 10; // true

7. Less Than (<)

Returns true if the left operand is less than the right operand.


5 < 10; // true

8. Less Than or Equal To (<=)

Returns true if the left operand is less than or equal to the right operand.


5 <= 5; // true

9. Ternary Operator (? :)

A shorthand for an if-else statement. It takes three operands: a condition, a value if true, and a value if false.


const result = (10 > 5) ? "Yes" : "No"; // "Yes"

JavaScript Comments

JavaScript comments are annotations in the code that are ignored by the JavaScript engine when the code is executed. They are used to explain code, make notes, or temporarily disable certain parts of the code. Comments are helpful for both the developer writing the code and others who might read or maintain the code in the future.

There are two types of comments

Single-Line Comments

Single-line comments are used to add short notes or explanations on one line.

They start with // and extend to the end of the line.


// This is a single-line comment
let name = 'John'; // Variable name is assigned the value John

Multi-Line Comments

Multi-line comments are used for longer explanations or for commenting out multiple lines of code.

They start with /* and end with */


/*
This is a multi-line comment.
It can span multiple lines.
It is useful for longer descriptions or temporarily disabling blocks of code.
*/
let x = 10;

JavaScript Syntax

JavaScript syntax refers to the set of rules that define how a JavaScript program is written and interpreted by the browser or JavaScript engine.

1. Variables

Used to store data values.

Declared using var, let, or const.


var x = 10;
let y = 20;
const name = "John";

2. Semicolons

Although semicolons are often optional, it is recommended to use them to terminate statements to avoid potential issues caused by JavaScript’s automatic semicolon insertion.


let x = 5;
let y = 10;

3. Automatic Type Conversion (Coercion)

JavaScript automatically converts data types when performing operations between different types (e.g., adding a number to a string).


let result = 5 + "5"; // "55" (number 5 is converted to string)

4. Identifiers

Identifiers are names given to variables, functions, and objects. They must start with a letter, underscore (_), or dollar sign ($), followed by letters, digits, underscores, or dollar signs.


let name = "John";
let $numValue = 100;
let _isUserAllowed = true;

we can’t declare a variable that starts with a number.


let 1name = "John";  // not allowd

5. Reassigning Variables

Variables declared with var or let can be reassigned.

Variables declared with const cannot be reassigned.


let a = 10;
a = 20; // Valid

const b = 50;
// b = 100; // Error: Assignment to constant variable.

spread operator

The spread operator (...) in JavaScript is a versatile and powerful feature that allows you to expand or spread elements in arrays, objects, or function arguments. It’s commonly used for copying, merging, and passing around data structures without modifying the original ones.

the use of spread operator in Array

Copying an Array:


const arr1 = ["Apple","Banana", "Orange"];
const arr2 = [...arr1];
console.log(arr2); // Output: [Apple,Banana,"Orange]

Combining Arrays


const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // Output: [1, 2, 3, 4, 5, 6]

Adding Elements to an Array:


const arr1 = [1, 2, 3];
const arr2 = [0, ...arr1, 4];
console.log(arr2); // Output: [0, 1, 2, 3, 4]

the use of the spread operator in Object

Copying an Object


const obj1 = { name: 'John', age: 38 };
const obj2 = { ...obj1 };
console.log(obj2); // Output: {name: 'John', age: 38}

Merging Objects


const obj1 = { name: 'John', age: 38 };
const obj2 = { sex: 'Male', qualification: 'Graduate'};
const merged = { ...obj1, ...obj2 };
console.log(merged); // Output: {name: 'John', age: 38, sex: 'Male', qualification: 'Graduate' }

Overriding Properties


const obj1 = { name: 'John', age: 38 };
const obj2 = { age: 39, qualification: 'Graduate'};
const merged = { ...obj1, ...obj2 };
console.log(merged); // Output: {name: 'John', age: 39, qualification: 'Graduate' }

Function Arguments

Spreading an Array as Arguments


function sum(a, b, c, d) {
  return a+b+c+d;
}
const numbers = [1, 2, 3,4];
console.log(sum(...numbers)); // Output: 10

Array in Typescript

In TypeScript, an array is a data structure that stores a collection of elements, which can be of any type, though typically of the same type. Arrays allow you to store multiple values in a single variable and access them via their index.

Creating Arrays in TypeScript

1. Array of a specific type:

You can define an array to contain elements of a specific type using the following syntax:


let numbers: number[] = [1, 2, 3, 4];
let strings: string[] = ["Apple", "Banana", "Orange"];

2. Using the Array generic type:

Another way to define an array is by using the Array<T> syntax, where T is the type of elements in the array:


let numbers: Array = [1, 2, 3, 4];
let strings: Array = ["Apple", "Banana", "Orange"];

Multi-dimensional Arrays

You can also create multi-dimensional arrays (arrays of arrays) in TypeScript:


let matrix: number[][] = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

Array Methods

TypeScript arrays inherit many useful methods from JavaScript, such as:

push() – Adds elements to the end of the array.

pop() – Removes and returns the last element.

shift() – Removes and returns the first element.

unshift() – Adds elements to the beginning of the array.

map() – Creates a new array by applying a function to each element.

filter() – Creates a new array with all elements that pass a test.

reduce() – Reduces the array to a single value by applying a function.

Example:


let fruits: string[] = ["Apple", "Banana", "Orange"];
fruits.push("Mango");
console.log(fruits); // Output: ["Apple", "Banana", "Orange", "Mango"]

CSS Opacity

The opacity property in CSS is used to set the transparency level of an element. It accepts values ranging from 0 (completely transparent) to 1 (completely opaque). This property affects not only the background of the element but also its text and any other child elements.

Syntax:


selector {
    opacity: value;
}

value: A number between 0 and 1, inclusive. 0 represents full transparency, and 1 represents full opacity.

Semi transparent (50% transparent)


      .semi-transparent {
            opacity: 0.5; /* 50% transparent */
            background-color: lightgreen;
            padding: 20px;
            margin: 10px;
        }
This is semi-transparent (opacity: 0.5).

Try it Yourself

Fully transparent (100% transparent)


      .fully-transparent {
            opacity: 0; /* 100% transparent */
            background-color: lightgreen;
            padding: 20px;
            margin: 10px;
        }

Note:- if opacity is 0 then date will not be display.

Try it Yourself

CSS combinators

CSS combinators are used to define the relationship between selectors. They help in applying styles to elements based on their relationship in the HTML document.

There are four main types of combinators:

  • descendant combinator
  • child combinator
  • adjacent sibling combinator
  • general sibling combinator

1. Descendant Combinator ()

The descendant combinator selects elements that are descendants of a specified element. This is represented by a space between two selectors.

Example: Selects all <p> elements inside elements.


/* Selects all <p> elements inside <div> elements */
div p {
    color: blue;
}

Try it Yourself

2. Child Combinator (>)

The child combinator selects elements that are direct children of a specified element.

Example: Selects all <p> elements that are direct children of <div> elements


/* Selects all <p> elements that are direct children of <div> elements  */
div > p {
    color: green;
}

Try it Yourself

3. Adjacent Sibling Combinator (+)

The adjacent sibling combinator selects an element that is directly adjacent to a specified element. This means it selects the element that immediately follows the first element.

Example: Selects the <p> element that is immediately after a <div> element


/* Selects the <p> element that is immediately after a <div> element */
div + p {
    color: red;
}

Try it Yourself

4. General Sibling Combinator (~)

The general sibling combinator selects all elements that are siblings of a specified element, following it.

Example: Selects all <p> elements that are siblings of a <div> element


/* Selects the <p> Selects all <p> elements that are siblings of a <div> element  */
div ~ p {
    color: orange;
}

Try it Yourself

Complete Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        /* Descendant Combinator */
        div p {
            color: blue;
        }

        /* Child Combinator */
        div > p {
            color: green;
        }

        /* Adjacent Sibling Combinator */
        div + p {
            color: red;
        }

        /* General Sibling Combinator */
        div ~ p {
            color: orange;
        }
    </style>
</head>
<body>

    <div>
        <p>Descendant (and child) of div</p>
        <p>Another descendant (and child) of div</p>
    </div>
    <p>Adjacent sibling of div</p>
    <p>General sibling of div</p>

</body>
</html>

Try it Yourself

Explanation:

  • Descendant Combinator (div p): Styles all <p> elements inside a <div>, regardless of their depth.
  • Child Combinator (div > p): Styles only <p> elements that are direct children of a <div>.
  • Adjacent Sibling Combinator (div + p): Styles the first <p> element immediately following a <div>.
  • General Sibling Combinator (div ~ p): Styles all <p> elements that are siblings of a <div> and come after it.

CSS align

CSS alignment properties are used to control the positioning of elements within their containers and to align text or other content within elements. Depending on the context and the type of element, different properties and techniques are used for alignment. Here are some of the most commonly used CSS properties for alignment:

Text Alignment

The text-align property is used to specify the horizontal alignment of text within an element.

Syntax:


/* Text alignment within an element */
.container {
    text-align: left;   /* Align text to the left */
    text-align: right;  /* Align text to the right */
    text-align: center; /* Center align text */
    text-align: justify; /* Justify text */
}

Try it Yourself

Vertical Alignment

The vertical-align property is used to align inline or table-cell elements vertically.

Syntax:


/* Vertical alignment within inline or table-cell elements */
.element {
    vertical-align: baseline;  /* Default, aligns with the baseline of the parent */
    vertical-align: top;       /* Aligns with the top of the tallest element */
    vertical-align: middle;    /* Centers the element vertically */
    vertical-align: bottom;    /* Aligns with the bottom of the lowest element */
}

Try it Yourself

Flexbox Alignment

The Flexbox layout model provides powerful alignment capabilities for both the main axis and the cross axis.

Main Axis Alignment

The justify-content property aligns flex items along the main axis (horizontally for row direction).

Syntax:


/* Main axis alignment within a flex container */
.container {
    display: flex;
    justify-content: flex-start; /* Align items to the start of the container */
    justify-content: flex-end;   /* Align items to the end of the container */
    justify-content: center;     /* Center items within the container */
    justify-content: space-between; /* Distribute items with space between */
    justify-content: space-around; /* Distribute items with space around */
    justify-content: space-evenly; /* Distribute items with equal space around */
}

Try it Yourself

Cross Axis Alignment

The align-items property aligns flex items along the cross axis (vertically for row direction).

Syntax:


/* Cross axis alignment within a flex container */
.container {
    display: flex;
    align-items: flex-start; /* Align items to the start of the cross axis */
    align-items: flex-end;   /* Align items to the end of the cross axis */
    align-items: center;     /* Center items along the cross axis */
    align-items: baseline;   /* Align items along their baselines */
    align-items: stretch;    /* Stretch items to fill the container (default) */
}

CSS inline-block

The inline-block value for the display property in CSS is used to combine the characteristics of both inline and block elements. Elements with display: inline-block behave like inline elements in terms of layout, but they also respect width and height properties like block elements.

Key Characteristics:

1. Inline Characteristics:

Elements are laid out horizontally, one after the other.

Elements do not start on a new line and do not force subsequent content to start on a new line.

2. Block Characteristics:

Elements respect the width and height properties.

Margins and paddings are applied around the element.

Syntax:


selector {
    display: inline-block;
}

Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .inline-block-element {
            display: inline-block;
            width: 150px;
            height: 100px;
            margin: 10px;
            background-color: lightblue;
            text-align: center;
            vertical-align: top;
            line-height: 100px; /* Centers text vertically */
        }
    </style>
</head>
<body>

    <div class="inline-block-element">Element 1</div>
    <div class="inline-block-element">Element 2</div>
    <div class="inline-block-element">Element 3</div>

</body>
</html>

Try it Yourself

Element 1
Element 2
Element 3

CSS Float

The float property in CSS is used to position an element to the left or right of its container, allowing text and inline elements to wrap around it. Originally designed for wrapping text around images, float can also be used to create various layouts and effects.

Float property values

1. none: The element does not float. This is the default value.

2. left: The element floats to the left of its container.

3. right: The element floats to the right of its container.

4. inherit: The element inherits the float value from its parent.

Syntax:


selector {
    float: none | left | right | inherit;
}

Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .container {
            border: 1px solid #000;
            padding: 10px;
        }
        .box {
            width: 100px;
            height: 100px;
            margin: 10px;
            background-color: lightblue;
        }
        .left {
            float: left;
        }
        .right {
            float: right;
        }
        .clearfix::after {
            content: "";
            display: table;
            clear: both;
        }
    </style>
</head>
<body>

    <div class="container clearfix">
        <div class="box left">Float Left</div>
        <div class="box right">Float Right</div>
        <p>This is some text that wraps around the floating elements. The float property can be used to create simple layouts where elements are positioned to the left or right and content flows around them.</p>
    </div>

</body>
</html>

Try it Yourself

Float Left
Float Right

This is some text that wraps around the floating elements. The float property can be used to create simple layouts where elements are positioned to the left or right and content flows around them.

In this example:

  • The .box.left element floats to the left, and the .box.right element floats to the right.
  • The text inside the .container wraps around the floating elements.
  • The .clearfix class is used to clear the floats, ensuring that the container expands to encompass the floated elements. This is a common technique to avoid layout issues when using floats.

Notes:-

Clearing Floats: Floats can cause layout issues because they are taken out of the normal document flow. To ensure that a container expands to fit floated elements, you need to clear the floats. This can be done using the clear property or the clearfix method.

Syntax:


selector {
    clear: both;
}

CSS overflow

The overflow property in CSS specifies what should happen if content overflows an element’s box. It is used to control the behavior of content that is too large to fit in an element’s box.

overflow property values

1. visible: The default value. Content is not clipped and may render outside the element’s box.

2. hidden: Content that overflows the element’s box is clipped, and no scrollbars are provided.

3. scroll: Content that overflows the element’s box is clipped, but scrollbars are provided to allow the user to scroll to see the rest of the content.

4. auto: If the content overflows, the browser will display scrollbars only when necessary.

Syntax:


selector {
    overflow: visible | hidden | scroll | auto;
}

Example:-


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .box {
            width: 200px;
            height: 100px;
            border: 1px solid black;
            margin-bottom: 20px;
        }

        .visible {
            overflow: visible;
            background-color: lightblue;
        }

        .hidden {
            overflow: hidden;
            background-color: lightcoral;
        }

        .scroll {
            overflow: scroll;
            background-color: lightgreen;
        }

        .auto {
            overflow: auto;
            background-color: lightyellow;
        }

        .content {
            width: 300px;
            height: 150px;
            background-color: rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>

    <div class="box visible">
        <div class="content">This box has overflow: visible.</div>
    </div>

    <div class="box hidden">
        <div class="content">This box has overflow: hidden.</div>
    </div>

    <div class="box scroll">
        <div class="content">This box has overflow: scroll.</div>
    </div>

    <div class="box auto">
        <div class="content">This box has overflow: auto.</div>
    </div>

</body>
</html>

Explanation:

  • Visible: The content overflows and is visible outside the box.
  • Hidden: The content that overflows is clipped, and only the part that fits within the box is visible.
  • Scroll: Scrollbars appear, allowing the user to scroll to see the overflowing content.
  • Auto: Scrollbars appear only if the content overflows, similar to scroll but only when necessary.

Additional Properties:

overflow-x: Controls the horizontal overflow.

overflow-y: Controls the vertical overflow.

Syntax:


selector {
    overflow-x: visible | hidden | scroll | auto;
    overflow-y: visible | hidden | scroll | auto;
}

Example:


.box {
    width: 200px;
    height: 100px;
    border: 1px solid black;
}

.x-scroll {
    overflow-x: scroll;
    overflow-y: hidden;
}

In this example, the x-scroll class allows horizontal scrolling but hides any vertical overflow. This is useful when you want to control scrolling behavior separately for horizontal and vertical content.

CSS z-index

The z-index property in CSS controls the stacking order of elements that overlap. Elements with a higher z-index value will appear in front of those with a lower z-index value. The z-index property only works on positioned elements (position: relative, position: absolute, position: fixed, or position: sticky).

Key points

Default Value: The default value for z-index is auto, which means the element will follow the order of the HTML structure.

Higher Values in Front: Elements with higher z-index values are stacked in front of elements with lower values.

Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .box {
            position: absolute;
            width: 100px;
            height: 100px;
            color: white;
            font-size: 20px;
            text-align: center;
            line-height: 100px;
        }

        .box1 {
            background-color: red;
            top: 50px;
            left: 50px;
            z-index: 1;
        }

        .box2 {
            background-color: blue;
            top: 80px;
            left: 80px;
            z-index: 3;
        }

        .box3 {
            background-color: green;
            top: 110px;
            left: 110px;
            z-index: 2;
        }
    </style>
</head>
<body>

    <div class="box box1">1</div>
    <div class="box box2">2</div>
    <div class="box box3">3</div>

</body>
</html>

Notes:

1. Negative Values: z-index can have negative values, which place elements behind those with a z-index of 0 or higher.

2. Non-Positioned Elements: If an element is not positioned (i.e., position: static), the z-index property does not apply to it.

CSS Position

In CSS, the position property is used to specify how an element is positioned in a document. There are several possible values for the position property:

position: static

position: static is the default positioning for all HTML elements. When an element has a position value of static, it is placed in the normal document flow, meaning it follows the standard layout rules without any special positioning. The top, right, bottom, and left properties do not apply to elements with position: static.

Syntax


.static-element {
    position: static;
}

Note: position: static is the default value, you don’t actually need to specify it unless you’re overriding another position value.

position: relative

position: relative is a CSS property that allows an element to be positioned relative to its normal position in the document flow. When an element is given a position value of relative, it remains in the normal flow of the document, but you can adjust its position using the top, right, bottom, and left properties. These properties will offset the element from where it would normally be placed without changing the layout of surrounding elements.

Syntax:


.relative-element {
    position: relative;
    top: 20px;
    left: 30px;
}

Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .relative-element {
            position: relative;
            top: 20px;
            left: 20px;
            background-color: lightcoral;
            padding: 10px;
            margin: 10px;
        }
        .normal-element {
	  background-color: green;
	}
    </style>
</head>
<body>
    <div class="relative-element">This is a relatively positioned element.</div>
    <div class="normal-element">This is a normal static element.</div>
</body>
</html>
This is a relatively positioned element.
This is a normal static element.

In this example:

  • The div with the class relative-element has a position value of relative.
  • The top: 20px and left: 20px properties move the element 20 pixels down and 20 pixels to the right from its normal position.
  • The element remains in the document flow, so it occupies its original space. The next element in the document flow will not move into the space of the relatively positioned element.

position: absolute

position: absolute is a CSS property that allows an element to be positioned relative to its closest positioned ancestor. An element with position: absolute is removed from the normal document flow, meaning it does not affect the layout of surrounding elements and is not affected by them. Instead, its position is determined by the top, right, bottom, and left properties.

Syntax:


.absolute-element {
    position: absolute;
    top: 50px;
    left: 100px;
}

Example:


<html lang="en">
<head>
    <style>
        .relative-container {
            position: relative;
            width: 300px;
            height: 200px;
            background-color: lightgray;
        }

        .absolute-element {
            position: absolute;
            top: 20px;
            left: 30px;
            background-color: lightgreen;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div class="relative-container">
        This is a relatively positioned container.
        <div class="absolute-element">This is an absolutely positioned element.</div>
    </div>
</body>
</html>
This is a relatively positioned container.
This is an absolutely positioned element.

position: fixed

position: fixed is a CSS property that positions an element relative to the browser window, rather than its containing element. A fixed-position element stays in the same place on the screen, even when the page is scrolled. This makes it useful for creating elements like sticky headers, footers, or floating buttons.

Key Points:

1. Fixed Positioning: The element is positioned relative to the viewport and does not move when the page is scrolled.

2. Offset Properties: The top, right, bottom, and left properties determine the position of the element relative to the viewport.

3. Removed from Normal Flow: The element is taken out of the normal document flow, so it does not affect the layout of other elements and vice versa.

Syntax:


.fixed-element {
    position: fixed;
    top: 0;
    right: 0;
}

Example:


<html lang="en">
<head>
    <style>
        .fixed-element {
            position: fixed;
            top: 10px;
            right: 10px;
            background-color: lightpink;
            padding: 10px;
            border: 1px solid #000;
        }

        .content {
            height: 1500px; /* Adding height to demonstrate scrolling */
            background-color: lightgray;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div class="fixed-element">This is a fixed element.</div>
    <div class="content">
        Scroll down to see the fixed element stay in place.
    </div>
</body>
</html>

position: sticky

position: sticky is a CSS property that allows an element to switch between relative and fixed positioning, depending on the user’s scroll position. A sticky element toggles between relative and fixed positioning based on the scroll position in the document. When the element reaches a specified point in the scroll, it sticks to that position (like fixed) until its containing block is out of view.

Key Points:

1. Relative Positioning: The element is positioned according to the normal flow of the document until a specified scroll position is reached.

2. Fixed Positioning: Once the specified scroll position is reached, the element becomes fixed and remains at that position relative to the viewport until its container is scrolled out of view.

3. Offset Properties: The top, right, bottom, and left properties are used to define the point at which the element becomes sticky.

Syntax:


.sticky-element {
    position: sticky;
    top: 0;
}

Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .sticky-container {
            height: 2000px; /* Adding height to demonstrate scrolling */
            background-color: lightgray;
            padding: 10px;
        }

        .sticky-element {
            position: sticky;
            top: 10px; /* Becomes fixed 10px from the top of the viewport */
            background-color: lightyellow;
            padding: 10px;
            border: 1px solid #000;
        }
    </style>
</head>
<body>

    <div class="sticky-container">
        <div class="sticky-element">This is a sticky element.</div>
        <p>Scroll down to see the sticky effect.</p>
        <p>Content...</p>
        <p>Content...</p>
        <p>Content...</p>
        <p>Content...</p>
        <p>Content...</p>
        <p>Content...</p>
    </div>

</body>
</html>

CSS Max Width

The max-width property in CSS is used to set the maximum width of an element. This property ensures that the element’s width does not exceed the specified value, even if the content inside the element requires more space. It is particularly useful for creating responsive designs, ensuring that elements do not become too wide on larger screens.

Syntax


selector {
  max-width: value;
}

values of max-width

1. none

(default) The element has no maximum width.

2. length

Specifies a fixed maximum width using units such as px, em, rem, etc.


.container {
  max-width: 700px;
}

3. percentage

Specifies a maximum width as a percentage of the containing element’s width.


.container {
  max-width: 80%;
}

4. inherit

The element inherits the max-width value from its parent.


.container {
  max-width: inherit;
}

5. initial

Sets the property to its default value.


.container {
  max-width: initial;
}

6. unset

Resets the property to its natural value.


.container {
  max-width: unset;
}

Important Points

The max-width property can override the width property if the specified width exceeds the max-width value.

Combining max-width with other properties like min-width, width, and max-height can create highly controlled and flexible layouts.

CSS Display

The display property in CSS is used to define how an element is displayed on a web page. It determines the layout behavior of an element. This property controls the inner and outer display types of an element, affecting how it is rendered in the document flow and how it interacts with other elements.

property values

1. display: none

This not only hides the element but also removes it from the document flow, meaning it won’t take up any space.

Syntax:-


.container {
  display: none;
}

2. display: block

The element is displayed as a block element (like <div>). It will take up the full width available and start on a new line.

Syntax:


.element-block {
  display: block;
}

3. display: inline

The element is displayed as an inline element (like <span>). It will take up only as much width as necessary and will not start on a new line.

Syntax:


.inline-element{
  display: inline;
}

4. display: inline-block

The element is displayed as an inline element, but it can have width and height like a block element.

Syntax:


.inline-element{
  display: inline-block;
}

5. display: flex

The element is displayed as a block-level flex container. It enables the use of the flexible box layout model.

Syntax:


.flex-container{
  display: flex;
}

6. display: inline-flex

The element is displayed as an inline-level flex container.

Syntax:


.flex-inline-container{
  display: inline-flex;
}

7. display: grid

The element is displayed as a block-level grid container. It enables the use of the grid layout model.

Syntax:


.grid-container {
  display: grid;
}

8. display: inline-grid

The element is displayed as an inline-level grid container.

Syntax:


.grid-inline-container {
  display: inline-grid;
}

9. display: table

The element is displayed as a block-level table (like <table>).

Syntax:


.table-container {
  display: table;
}

10. inline-table

The element is displayed as an inline-level table.

Syntax:


.table-inline-container {
  display: inline-table;
}

11. table-row and table-cell

These values display the element as a table row, table cell, and so on.

Syntax:


.table-row{
  display: table-row;
}
.table-cell{
  display: table-cell;
}

12. display: list-item

he element is displayed as a list item (like <li>).

Syntax:


.list-item-container {
  display: list-item;
}

13. display: contents

The element itself is not displayed, but its child elements are displayed as if they were direct children of the element’s parent.

Syntax:


.content-container {
  display: contents;
}

CSS Tables

CSS tables refer to the way CSS (Cascading Style Sheets) is used to style HTML tables. HTML tables are used to display tabular data, and CSS can be applied to control their layout, appearance, and responsiveness. CSS allows for detailed customization of table elements, including borders, padding, text alignment, colors, and more.

Basic HTML Table Structure

HTML tables are created using the <table>, <tr>, <th>, and <td> elements. Here is a simple example of an HTML table:


<table>
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Data 1</td>
            <td>Data 2</td>
            <td>Data 3</td>
        </tr>
        <tr>
            <td>Data 4</td>
            <td>Data 5</td>
            <td>Data 6</td>
        </tr>
    </tbody>
</table>

Basic CSS Table Properties

CSS can be applied to tables using a variety of properties to enhance their appearance and usability.

Table Borders

You can add borders to tables, table rows, table headers, and table cells:


table {
    border-collapse: collapse; /* Merge adjacent borders into a single border */
    width: 100%; /* Make the table take up 100% of the container width */
}

th, td {
    border: 1px solid black; /* Add a 1px solid black border to headers and cells */
    padding: 8px; /* Add padding inside headers and cells */
    text-align: left; /* Left-align text in headers and cells */
}

Table Header and Row Background Colors

You can style the table headers and rows with background colors for better readability:


th {
    background-color: #f2f2f2; /* Light grey background for headers */
}

tr:nth-child(even) {
    background-color: #f9f9f9; /* Light grey background for even rows */
}

tr:hover {
    background-color: #d1e7dd; /* Light green background on hover */
}

Text Alignment and Padding

You can control the alignment of text and the padding inside the cells:


th, td {
    text-align: center; /* Center-align text in headers and cells */
    padding: 10px; /* Add padding inside headers and cells */
}

CSS Lists

Styling lists in CSS allows you to control the appearance of ordered (<ol>) and unordered (<ul>) lists, as well as definition lists (<dl>). You can customize list markers, spacing, and layout to match your design requirements.

Unordered Lists (<ul>)

Unordered lists use bullet points by default. You can change the list style, position, and spacing.


<!DOCTYPE html>
<html lang="en">
<head>
<style>
/* Unordered list styles */
.styled-ul {
    list-style-type: square; /* Change bullet to square */
    padding-left: 20px;      /* Add left padding */
    margin: 20px 0;          /* Add top and bottom margin */
}

.styled-ul li {
    margin-bottom: 10px;     /* Add space between list items */
}
</style>
</head>
<body>
    <h1>Unordered List</h1>
    <ul class="styled-ul">
        <li>List Item 1</li>
        <li>List Item 2</li>
        <li>List Item 3</li>
    </ul>
</body>
</html>

Unordered List

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

Ordered Lists (<ol>)

Ordered lists use numbers by default. You can change the list style, position, and spacing similarly to unordered lists.


<!DOCTYPE html>
<html lang="en">
<head>
<style>
/* Ordered list styles */
.styled-ol {
    list-style-type: upper-roman; /* Change number style to upper Roman numerals */
    padding-left: 20px;           /* Add left padding */
    margin: 20px 0;               /* Add top and bottom margin */
}
.styled-ol li {
    margin-bottom: 10px;          /* Add space between list items */
}
</style>
</head>
<body>
<h2>Ordered List</h2>
<ol class="styled-ol">
    <li>First Item</li>
    <li>Second Item</li>
    <li>Third Item</li>
</ol>
</body>
</html>

Ordered List

  1. First Item
  2. Second Item
  3. Third Item

Definition Lists (<dl>)

Definition lists are used for terms and their definitions.


<!DOCTYPE html>
<html lang="en">
<head>
<style>
/* Definition list styles */
.styled-dl dt {
    font-weight: bold;   /* Bold the term */
    margin-top: 10px;    /* Add space above the term */
}

.styled-dl dd {
    margin-left: 20px;   /* Indent the definition */
    margin-bottom: 10px; /* Add space below the definition */
}
</style>
</head>
<body>
<h2>Definition List</h2>
<dl class="styled-dl">
    <dt>Term 1</dt>
    <dd>Definition 1</dd>
    <dt>Term 2</dt>
    <dd>Definition 2</dd>
</dl>
</body>
</html>

Definition List

Term 1
Definition 1
Term 2
Definition 2

CSS Links

In CSS, you can style links (<a> tags) to change their appearance based on different states such as normal, hovered, active, and visited.

Basic link states

1. Normal (a): The default state of the link.


a {
    color: green; /* you can put any color value */
}

2. Visited (a:visited): When the link has been visited.


a:visited {
    color: purple;
}

3. Hover (a:hover): When the mouse is over the link.


a:hover {
    color: red;
}

4. Active (a:active): When the link is being clicked.


a:active {
    color: yellow;
}

Text Decorations Property

text-decoration: none


a {
    color: green; /* you can put any color value */
    text-decoration: none;
}
a:visited {
    color: purple;
    text-decoration: none;
}
a:hover {
    color: red;
    text-decoration: none;
}
a:active {
    color: yellow;
    text-decoration: none;
}

text-decoration: underline


a {
    color: green; 
    text-decoration: underline;
}
a:visited {
    color: purple;
    text-decoration: underline;
}
a:hover {
    color: red;
    text-decoration: underline;
}
a:active {
    color: yellow;
    text-decoration: underline;
}

Background color Property


a {
    color: green; 
    background-color: LightBlue;
}
a:visited {
    color: purple;
    background-color: LightBlue;
}
a:hover {
    color: red;
    background-color: LightBlue;
}
a:active {
    color: yellow;
    background-color: LightBlue;
}

CSS Icons

CSS icons can be incorporated into your web design in several ways, such as using icon fonts, SVGs (Scalable Vector Graphics), or CSS-generated content. Here are some popular methods:

1. Using Icon Fonts

Icon fonts like Font Awesome and Material Icons are popular because they are easy to use and scale well.

Using Font Awesome:

1. Include Font Awesome in your HTML:


<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>

2. Use the icons in your HTML:


<i class="fas fa-home"></i> <!-- Home icon -->
<i class="fas fa-user"></i> <!-- User icon -->

3. Style the icons with CSS:


.fa-home {
    color: blue;
    font-size: 24px;
}

.fa-user {
    color: red;
    font-size: 22px;
}

2. Using SVGs

SVGs are a great choice because they are vector-based, meaning they are resolution-independent and can be scaled to any size without losing quality.

1. Include SVG directly in your HTML:


<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" fill="#000"/>
</svg>

2. Style SVG with CSS:


svg {
    width: 50px;
    height: 50px;
    fill: green;
}

Using SVG as an Image:

1. Include SVG file in your HTML:


<img src="icon.svg" alt="Icon" class="icon">

2. Style the image with CSS:


.icon {
    width: 50px;
    height: 50px;
}

3. CSS-Generated Content

You can use the ::before or ::after pseudo-elements to insert icons, often combined with icon fonts.

Example with Font Awesome:

1. Include Font Awesome in your HTML:


<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>

2. Use CSS to insert the icon:


.icon-home::before {
    content: "\f015"; /* Unicode for home icon in Font Awesome */
    font-family: 'Font Awesome 5 Free';
    font-weight: 900;
    font-size: 20px;
    color: blue;
    margin-right: 10px;
}

3. Use the class in your HTML:


<div class="icon-home">Home</div>
Home

4. Using CSS Libraries

There are several CSS libraries available that provide a wide range of icons, such as Bootstrap Icons.

Using Bootstrap Icons:

1. Include Bootstrap Icons in your HTML:


<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.8.1/font/bootstrap-icons.css">
</head>

2. Use the icons in your HTML:


<i class="bi bi-house"></i> <!-- Home icon -->
<i class="bi bi-person"></i> <!-- Person icon -->

3. Style the icons with CSS:


.bi-house {
    color: green;
    font-size: 34px;
}

.bi-person {
    color: orange;
    font-size: 28px;
}

CSS Fonts

In CSS, fonts can be styled and customized using a variety of properties. These properties allow you to control the typeface, size, weight, style, and more.

Font Properties:

font-family

The font-family property specifies the font for an element. You can list multiple fonts as a “fallback” system, starting with your preferred font and ending with a generic family name (e.g., serif, sans-serif, monospace).


p {
    font-family: 'Arial', 'Helvetica', sans-serif;
}

font-size

The font-size property sets the size of the font. It can be specified in various units, including pixels (px), ems (em), rems (rem), percentages (%), and viewport units (vw, vh).


p {
    font-size: 16px; /* Sets the font size to 16 pixels */
    font-size: 1em;  /* Equivalent to the current font size of the parent element */
    font-size: 1rem; /* Equivalent to the root element's font size */
    font-size: 100%; /* Equivalent to the parent element's font size */
    font-size: 2vw;  /* 2% of the viewport width */
}

font-weight

The font-weight property specifies the thickness of the characters. It can take values like normal, bold, bolder, lighter, or numerical values ranging from 100 to 900.


p {
    font-weight: normal;  /* Standard weight */
    font-weight: bold;    /* Bold weight */
    font-weight: 700;     /* Numeric value (bold) */
    font-weight: 400;     /* Numeric value (normal) */
}

font-style

The font-style property defines the style of the font, such as normal, italic, or oblique.


p {
    font-style: normal;  /* Normal text */
    font-style: italic;  /* Italic text */
    font-style: oblique; /* Oblique text (slightly slanted) */
}

Important Font Notes:

Using Web Fonts: To use web fonts like Google Fonts, you can import them into your CSS.


@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');

body {
    font-family: 'Roboto', sans-serif;
}

Font Fallbacks: Always provide fallback fonts to ensure text is displayed properly even if a preferred font is unavailable.


p {
    font-family: 'Georgia', 'Times New Roman', Times, serif;
}

Responsive Design: Use relative units like em or rem for font sizes to ensure your text scales appropriately across different devices.


p {
    font-size: 1.2rem; /* 1.2 times the root font size */
}

CSS text-shadow

In CSS, the text-shadow property is used to add shadow effects to text. You can apply multiple shadows to text by separating each shadow effect with a comma. The text-shadow property accepts values for the horizontal offset, vertical offset, blur radius, and color of the shadow.

Syntax:


text-shadow: horizontal-offset vertical-offset blur-radius color;

Examples:

1. Basic Text Shadow:


p {
    text-shadow: 2px 2px 4px #000000;
}

Explanations of above example:

  • 2px: Horizontal offset (moves the shadow 2 pixels to the right)
  • 2px: Vertical offset (moves the shadow 2 pixels down)
  • 4px: Blur radius (the amount of blur applied to the shadow)
  • #000000: Shadow color (black)

2. Multiple Text Shadows:


h1 {
    text-shadow: 1px 1px 2px #ff0000, 2px 2px 4px #00ff00, 3px 3px 6px #0000ff;
}

This applies three separate shadows to the text, each with different offsets, blur radii, and colors.

3. Inset Shadow: Although text-shadow does not directly support inset shadows (like box-shadow does), you can achieve similar effects with clever use of offsets and colors.


h2 {
    text-shadow: -1px -1px 0 #ff0000, 1px 1px 0 #00ff00;
}

CSS text spacing

In CSS, text spacing can be adjusted using a few different properties depending on the specific type of spacing you’re aiming to control.

1. Line Height: Controls the vertical spacing between lines of text.


p {
    line-height: 1.5; /* or a unit value like 24px */
}

2. Letter Spacing: Adjusts the space between individual characters.


p {
    letter-spacing: 3px; /* or other unit values */
}

3. Word Spacing: Modifies the space between words.


p {
    word-spacing: 4px; /* or other unit values */
}

4. Text Indent: Indents the first line of text in a block.


p {
    text-indent: 20px; /* or other unit values */
}

5. Text Align: Aligns text horizontally within its containing element.


p {
    text-align: justify; /* or left, right, center */
}

6. Margin and Padding: Adds space around or inside elements, respectively, which can affect the overall spacing of text within its container.


p {
    margin: 20px; /* space outside the element */
    padding: 20px; /* space inside the element */
}

CSS text transform

In CSS, the text-transform property is used to control the capitalization of text within an element. This property allows you to transform text to uppercase, lowercase, capitalize.

Syntax


selector {
  text-transform: value;
}

text-transform values

none: Default. No transformation is applied.

capitalize: Transforms the first character of each word to uppercase.

uppercase: Transforms all characters to uppercase.

lowercase: Transforms all characters to lowercase.

full-width: Changes the text to full-width form (typically used in East Asian typography).

inherit: Inherits the text-transform value from its parent element.

initial: Sets the property to its default value.

Examples

1. Capitalize:


p.capitalize {
  text-transform: capitalize;
}

2. Uppercase:


p.uppercase {
  text-transform: uppercase;
}

3. Lowercase:


p.lowercase {
  text-transform: lowercase;
}

4. Full-width:


p.full-width {
  text-transform: full-width;
}

5. None (No Transformation):


p.none {
  text-transform: none;
}

Example: Here is an example of a simple HTML page demonstrating various uses of the text-transform property:


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .capitalize {
            text-transform: capitalize;
        }
        .uppercase {
            text-transform: uppercase;
        }
        .lowercase {
            text-transform: lowercase;
        }
        .full-width {
            text-transform: full-width;
        }
        .none {
            text-transform: none;
        }
    </style>
</head>
<body>
    <p class="capitalize">this text will have each word capitalized.</p>
    <p class="uppercase">this text will be transformed to uppercase.</p>
    <p class="lowercase">THIS TEXT WILL BE TRANSFORMED TO LOWERCASE.</p>
    <p class="full-width">this text will be transformed to full-width form.</p>
    <p class="none">This Text Will Not Be Transformed.</p>
</body>
</html>

CSS text decoration

In CSS, the text-decoration property is used to add or remove decorations to/from text. This includes underlining, overlining, line-through (strikethrough), and the style and color of these decorations. Here’s a detailed guide on how to use the text-decoration property:

Syntax


selector {
  text-decoration: value;
}

text-decoration values

1. text-decoration-line: Specifies the kind of text decoration to use (underline, overline, line-through, none).

none: No text decoration.

underline: Adds a line beneath the text.

overline: Adds a line above the text.

line-through: Adds a line through the middle of the text.

underline overline: Adds lines both above and beneath the text.

2. text-decoration-color: Specifies the color of the text decoration.

color: Any valid CSS color value (named colors, HEX, RGB, RGBA, HSL, HSLA).

3. text-decoration-style: Specifies the style of the text decoration.

solid: Default. A solid line.

double: A double line.

dotted: A dotted line.

dashed: A dashed line.

wavy: A wavy line.

4. text-decoration-thickness: Specifies the thickness of the text decoration line (not supported in all browsers).

from-font: The default value. Uses the thickness defined by the font.

length: Any valid length value (e.g., 2px, 0.1em).

Example

Here is an example of a simple HTML page demonstrating various uses of the text-decoration property:


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .underline {
            text-decoration: underline;
        }
        .overline {
            text-decoration: overline;
        }
        .line-through {
            text-decoration: line-through;
        }
        .multiple {
            text-decoration: underline overline;
        }
        .decoration-color {
            text-decoration: underline;
            text-decoration-color: red;
        }
        .decoration-style {
            text-decoration: underline;
            text-decoration-style: wavy;
        }
        .decoration-thickness {
            text-decoration: underline;
            text-decoration-thickness: 3px;
        }
    </style>
</head>
<body>
    <p class="underline">This text has an underline.</p>
    <p class="overline">This text has an overline.</p>
    <p class="line-through">This text has a line through it.</p>
    <p class="multiple">This text has both an underline and an overline.</p>
    <p class="decoration-color">This text has an underline with a red color.</p>
    <p class="decoration-style">This text has a wavy underline.</p>
    <p class="decoration-thickness">This text has a thick underline.</p>
</body>
</html>

CSS Text align

In CSS, the text-align property is used to set the horizontal alignment of text within an element. Here are the possible values and how to use them:

Syntax


selector {
  text-align: value;
}

text-align values

left: Aligns the text to the left.

right: Aligns the text to the right.

center: Centers the text.

justify: Stretches the lines so that each line has equal width, and the left and right margins are aligned.

start: Aligns text to the start of the writing mode. For left-to-right text, this is equivalent to left.

end: Aligns text to the end of the writing mode. For left-to-right text, this is equivalent to right.

Example:

1. Left Align:


p {
   text-align: left;
}

2. Right Align:


p {
   text-align: right;
}

3. Center Align:


p {
   text-align: center;
}

4. Justify Align:


p {
   text-align: justify;
}

Examples: Here is an example of a simple HTML page demonstrating the use of the text-align property:


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .left {
            text-align: left;
        }
        .right {
            text-align: right;
        }
        .center {
            text-align: center;
        }
        .justify {
            text-align: justify;
        }
    </style>
</head>
<body>
    <p class="left">This text is aligned to the left.</p>
    <p class="right">This text is aligned to the right.</p>
    <p class="center">This text is centered.</p>
    <p class="justify">This text is justified. It will stretch the lines so that each line has equal width, and the left and right margins are aligned, making the text look more uniform and neat.</p>
</body>
</html>

CSS Text color

In CSS, the color property is used to set the color of text. You can specify the color using different formats, such as named colors, HEX values, RGB values, RGBA values, HSL values, and HSLA values. Here’s a detailed guide on how to use the color property to style text:

Syntax


color: value;

Color Format values

1. Named Colors:


p {
  color: red;
}

2. HEX Values:


p {
  color: #ff0000;
}

3. RGB Values:


p {
  color: rgb(255, 0, 0);
}

4. RGBA Values:


p {
  color: rgba(255, 0, 0, 0.5); /* The last value is the alpha (opacity) */
}

5. HSL Values:


p {
  color: hsl(0, 100%, 50%);
}

6. HSLA Values:


p {
  color: hsla(0, 100%, 50%, 0.5); /* The last value is the alpha (opacity) */
}

Example: Basic Example with Named Colors


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        p {
            color: blue;
        }
    </style>
</head>
<body>
    <p>This is a paragraph with blue text.</p>
</body>
</html>

This is a paragraph with blue text.

CSS Height and Width

In CSS, the height and width properties are used to set the height and width of an element. Here’s a detailed guide on how to use these properties:

Syntax: for height


height: value;

Syntax: for Width


width: value;

Values of height and width

auto: Default value. The browser calculates the height/width.

length: Defines the height/width in px, cm, etc.

%: Defines the height/width in percent of the containing block.

initial: Sets the height/width to its default value.

inherit: Inherits the height/width from its parent element.

Examples

1. Fixed Height and Width:


.box {
  height: 200px;
  width: 300px;
  border: 1px solid #000;
}

2. Percentage-Based Height and Width:


.container {
  height: 100%; /* Takes up 100% of the parent's height */
  width: 50%;   /* Takes up 50% of the parent's width */
  border: 1px solid #000;
}

3. Height and Width with Auto Value:


.box {
  height: auto; /* Automatically calculated height */
  width: auto;  /* Automatically calculated width */
  border: 1px solid #000;
}

4. Using max-width and max-height:


.image {
  max-width: 100%;  /* Ensures the image does not exceed the container's width */
  max-height: 100%; /* Ensures the image does not exceed the container's height */
}

min-width and min-height

Use min-width and min-height to set the minimum dimensions an element can have.


.box {
  min-height: 100px;
  min-width: 200px;
  border: 1px solid #000;
}

max-width and max-height

Use max-width and max-height to set the maximum dimensions an element can have.


.box {
  max-height: 300px;
  max-width: 400px;
  border: 1px solid #000;
}

box-sizing

The box-sizing property can affect the actual rendered dimensions of an element by including/excluding padding and border in the element’s total width and height.


.box {
    width: 300px;
    height: 200px;
    padding: 20px;
    border: 10px solid #000;
    box-sizing: border-box; /* Ensures the padding and border are included in the width and height */
}

CSS Paddings

In CSS, the padding property is used to generate space around an element’s content, inside of any defined borders.

Syntax

1. All four sides: Adds 10px padding to all sides.


padding: 10px;

container1

2. Vertical and Horizontal: Adds 10px padding to top and bottom, 20px to left and right


padding: 10px 20px;

container2

3. Top, Horizontal and Bottom:


padding: 10px 20px 30px;

container3

4. Top, Right, Bottom and Left: Adds 10px to top, 20px to right, 30px to bottom, 40px to left.


padding: 10px 20px 30px 40px;

container4

5. Individual sides padding: Adds 10px to top, 20px to right, 30px to bottom, 40px to left.


padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;

container5

Difference between Padding and Margin

Padding is the space between the content and the border of an element.

Margin is the space outside the border of an element.

Example:- Suppose you have a <div> element with some text, and you want to add padding around the text to make it look more spacious:


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .box {
            padding: 20px;
            border: 1px solid #000;
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
    <div class="box">
        This is a box with padding.
    </div>
</body>
</html>
This is a box with padding.

CSS Margins

The margin property in CSS is used to create space around elements, outside of any defined borders. The margin property can be set individually for each side or as a shorthand for all sides.

Syntax:

Individual Properties:

  • margin-top: value;
  • margin-right: value;
  • margin-bottom: value;
  • margin-left: value;

Shorthand Property:


margin: [top] [right] [bottom] [left];

Shorthand Values:

1. One Value:


/* All sides will have 10px margin */
p {
    margin: 10px;
}

container1

All sides will have 10px margin

2. Two Values:


/* Vertical (top and bottom) margins are 10px, horizontal (right and left) margins are 20px */
p {
     margin: 10px 20px;
}

container1

Vertical (top and bottom) margins are 10px, horizontal (right and left) margins are 20px

3. Three Values:


/* Top margin is 10px, horizontal (right and left) margins are 20px, bottom margin is 30px */
p {
     margin: 10px 20px 30px;
}

container1

Top margin is 10px, horizontal (right and left) margins are 20px, bottom margin is 30px

4. Four Values:


/* Top margin is 10px, right margin is 20px, bottom margin is 30px, left margin is 40px */
p {
      margin: 10px 20px 30px 40px;
}

container1

Top margin is 10px, right margin is 20px, bottom margin is 30px, left margin is 40px

Auto Margin: You can use margin: auto; to center an element horizontally within its container. This works when the element has a defined width.


/* Horizontally centering a block element */
.centered {
    width: 50%;
    margin: 0 auto;
}

Negative Margins: Negative values are allowed for margins, which can pull elements closer together.


/* Negative margin example */
.negative-margin {
    margin-top: -10px;
}

border shorthand

In CSS, the border shorthand property allows you to define the width, style, and color of an element’s border in a single declaration. Here is the general syntax and some examples:

Syntax:


border: [border-width] [border-style] [border-color];

Examples:

1. A solid red border with 2px width


p {
    border: 2px solid red;
}

A solid red border with 2px width

2. A solid black border with medium width


p {
     border: solid;
}

A solid black border with medium width

Individual Borders:

You can also set the border for individual sides using these properties:


border-top: 1px solid black;
border-right: 2px dotted red;
border-bottom: 3px dashed blue;
border-left: 4px double green;

Example: Combining Styles


p {
    border-top: 2px solid red;
    border-right: 4px dotted green;
    border-bottom: 6px dashed blue;
    border-left: 8px double purple;
}

Example of Combining Styles

border color

The border-color property in CSS is used to set the color of an element’s border. You can specify the color using various formats, such as color names, hexadecimal values, RGB/RGBA values, or HSL/HSLA values. The border-color property can be applied to all sides of an element’s border simultaneously or to each side individually.

Syntax


element {
    border-color: colorName;  /* you can set any color into border-color property */
}

1. Apply the same color to all four sides


p {
    border-color: green;  /* you can set any color into border-color property */
}

Apply the same color to all four sides

2. Apply different colors to each side


p {
     border-color: red green blue yellow; /* top right bottom left */
}

Apply the same color to all four sides

3. Apply different colors to two sides


p {
     border-color: red green;
}

Apply different colors to two sides

4. Individual sides


p {
    border-top-color: red;
    border-right-color: green;
    border-bottom-color: blue;
    border-left-color: yellow;
}

Individual sides

Use border-color property values

Color Name: Use a predefined color name.


element {
    border-color: red;
}

Use a predefined color name

Hexadecimal: Use a hexadecimal value.


element {
    border-color: #ff0000;
}

Use a hexadecimal value

RGB: Use an RGB value.


element {
    border-color: rgb(255, 0, 0);
}

Use an RGB value

RGBA: Use an RGBA value for transparency.


element {
    border-color: rgba(255, 0, 0, 0.5); /* 50% transparent red */
}

Use an RGB value

HSL: Use an HSL value.


element {
    border-color: hsl(0, 100%, 50%);
}

Use an HSL value

HSLA: Use an HSLA value for transparency.


element {
    border-color: hsla(0, 100%, 50%, 0.5); /* 50% transparent red */
}

Use an HSLA value for transparency

border width

The border-width property in CSS is used to specify the width of an element’s border. It can be set using specific length values (e.g., pixels, ems, rems) or predefined keywords. This property can be applied to all sides of an element’s border simultaneously or to each side individually.

Syntax:-


element {
    border-width: 5px; /* you can define width according your requirement*/
}

1. Apply the same width to all four sides


p {
    border-width: 5px;
}

Apply the same width to all four sides

2. Apply different widths to each side


p {
     border-width: 2px 4px 6px 8px; /* top right bottom left */
}

Apply different widths to each side

3. Apply different widths to two sides


p {
    border-width: 2px 4px; /* top & bottom right & left */
}

Apply different widths to two sides

4. Individual sides


p {
    border-top-width: 5px;
    border-right-width: 10px;
    border-bottom-width: 15px;
    border-left-width: 20px;
}

Apply different widths to two sides

CSS border

The border property in CSS is used to set the border around an element. You can specify the border’s width, style, and color. The border property is a shorthand that combines these individual properties:

  1. border-width: Specifies the width of the border.
  2. border-style: Specifies the style of the border.
  3. border-color: Specifies the color of the border.

Border Styles

there are many border-style property.

  1. none: No border (default).
  2. solid: A solid line.
  3. dotted: A series of dots.
  4. dashed: A series of dashes.
  5. double: Two solid lines.
  6. hidden: A hidden border.
  7. groove: A 3D grooved border.
  8. ridge: A 3D ridged border.
  9. inset: A 3D inset border.
  10. outset: A 3D outset border.

Example:-

1. border:none


<p style="border:none;">border none Example</p>

Try it Yourself

border none Example

2. border:solid


<p style="border:solid;">border solid Example</p>

border solid Example

3. border:dotted


<p style="border:dotted;">Dotted Example</p>

Try it Yourself

border dotted Example

4. border:dashed


<p style="border:dashed;">border dashed Example</p>

Try it Yourself

border dashed Example

5. border:double


<p style="border:double;">border double Example</p>

Try it Yourself

border double Example

6. border:groove


<p style="border:groove;">border groove Example</p>

border groove Example

7. border:ridge


<p style="border:ridge;">border ridge Example</p>

border ridge Example

8. border:inset


<p style="border:inset;">border inset Example</p>

border inset Example

9. border:outset


<p style="border:outset;">border outset Example</p>

border outset Example

10. border:hidden


<p style="border:hidden;">border hidden Example</p>

border hidden Example

CSS background

CSS background is a shorthand property used to set multiple background-related properties for an element in one declaration. This can include background color, image, position, size, repeat, origin, clip, and attachment. Here’s a breakdown of the properties that can be included in the background shorthand:

background-color

Sets the background color of an element.


background-color: #ff0000; /* Red */

background-image

Sets the background image of an element.


background-image: url('image.jpg');

background-position

The background-position property in CSS is used to specify the initial position of a background image within an element. This property allows you to precisely control where the background image is placed relative to the element’s background area. You can set the position using keywords, length units, or percentages.

1. Predefined Keywords: You can use predefined keywords to position the background image.

top, right, bottom, left, center.

Syntax:


background-position: top left; 
background-position: bottom right;
background-position: center center; /* or just center */

Example: Image positioned at the top left corner


background-image: url('image.jpg');
background-position: top left; /* Image positioned at the top left corner */

2. Length Units: You can use length units such as pixels (px), ems (em), rems (rem), etc.


background-position: 10px 20px; /* 10px from the left, 20px from the top */

Example:- Image positioned 30px from the left and 40px from the top


element {
    background-image: url('image.jpg');
    background-position: 30px 40px; /* Image positioned 30px from the left and 40px from the top */
}

3. Percentages: You can use percentages to position the background image relative to the element’s size. 0% represents the start (top or left), and 100% represents the end (bottom or right).


background-position: 50% 50%; /* Centered */
background-position: 0% 100%; /* Bottom left */

Example:- Image centered through percentages


element {
    background-image: url('image.jpg');
    background-position: 50% 50%; /* Image centered */
}

4. Combination of Length and Percentage


background-position: 50% 10px; /* Center horizontally, 10px from the top */

Example:- Image centered horizontally, 20px from the top


element {
    background-image: url('image.jpg');
    background-position: 50% 20px; 
}

5. Using calc(): For more complex positioning, you can use the calc() function.


background-position: calc(100% - 10px) calc(100% - 20px);

Example:- Image positioned 10px from the right and 20px from the bottom


element {
    background-image: url('image.jpg');
    background-position: calc(100% - 10px) calc(100% - 20px);
}

background-size

The background-size property in CSS is used to specify the size of the background images of an element. This property allows you to control how a background image is scaled and displayed within an element. Here are the possible values for background-size

1. auto: The background image is displayed at its original size. This is the default value.


background-size: auto;

2. length: You can specify the width and height of the background image using length units (e.g., pixels, ems, etc.). If only one value is provided, the second value is set to auto.


background-size: 100px 200px; /* Width 100px, height 200px */
background-size: 100px;      /* Width 100px, height auto */

3. percentage: The background image is scaled relative to the element’s dimensions. The first value sets the width, and the second value sets the height. If only one value is provided, the second value is set to auto.


background-size: 50% 50%;   /* 50% of the element's width and height */
background-size: 50%;       /* Width 50%, height auto */

background-repeat

The background-repeat property in CSS is used to control how background images are repeated (tiled) within an element. By default, background images are repeated both horizontally and vertically. The background-repeat property allows you to change this behavior. Here are the possible values for background-repeat:

1. repeat: The background image is repeated both horizontally and vertically. This is the default value.


background-repeat: repeat;

2. repeat-x: The background image is repeated only horizontally.


background-repeat: repeat-x;

3. repeat-y: The background image is repeated only vertically.


background-repeat: repeat-y;

4. no-repeat: The background image is not repeated.


background-repeat: no-repeat;

CSS color

CSS color refers to the specification and application of color in web design using Cascading Style Sheets (CSS). CSS allows you to set the color of text, backgrounds, borders, and other elements on a webpage. There are several ways to define colors in CSS:

Named Colors

CSS includes a set of named colors that can be used directly. For example:


color: red;

Hexadecimal Colors

Colors can be defined using hexadecimal (hex) values, which start with a # followed by six hexadecimal digits. The first two digits represent the red component, the next two represent green, and the last two represent blue. For example:


color: #ff0000; /* red */

RGB and RGBA Colors

Colors can be specified using the rgb() or rgba() functions. The rgb() function takes three parameters (red, green, and blue), each ranging from 0 to 255. The rgba() function includes an additional parameter for alpha (opacity) which ranges from 0 (completely transparent) to 1 (completely opaque). For example:


color: rgb(255, 0, 0); /* red */

HSL and HSLA Colors

Colors can also be defined using the hsl() or hsla() functions. The hsl() function takes three parameters: hue (0-360), saturation (0%-100%), and lightness (0%-100%). The hsla() function adds an alpha parameter for opacity. For example:


color: hsl(0, 100%, 50%); /* red */

CSS Comments

CSS comments are used to add explanatory notes or disable parts of the CSS code temporarily. They are ignored by the browser and do not affect how the CSS is rendered. Here’s how you can use comments in CSS:

Syntax:

CSS comments start with /* and end with */. Any text between these symbols is considered a comment and will not be processed by the browser.

Single-Line Comment

You can use a single-line comment to explain a single line of CSS code.


/* This is a single-line comment */
p {
    color: blue; /* This comment is on the same line as the property */
}

Multi-Line Comment

You can use a multi-line comment to explain a block of CSS code or to provide more detailed explanations.


/*
  This is a multi-line comment.
  Author: John
*/
body {
    background-color: Gray; /* This comment is on the same line as the property */
}

Disabling Code with Comments

Comments can also be used to temporarily disable a section of code. This is useful for debugging.


/*
p {
    color: red;
}
*/

h1 {
    color: green;
}

Why we use comments?

Explain Complex Code: Use comments to explain complex or non-intuitive sections of your CSS.

Consistency: Maintain a consistent style for comments throughout your CSS files.

Avoid Overuse: While comments are helpful, overusing them can make your CSS harder to read. Use them judiciously.

Keep Comments Updated: Ensure that comments remain accurate as you update your CSS.

Example

Here’s an example demonstrating various uses of comments in CSS:


/* Main layout styles */
body {
    margin: 0; /* Remove default margin */
    padding: 0; /* Remove default padding */
    font-family: Arial, sans-serif; /* Set default font */
}

/* Header styles */
header {
    background-color: #333; /* Dark background for header */
    color: #fff; /* White text color */
    text-align: center; /* Center align text */
    padding: 1em 0; /* Vertical padding */
}

/* Main content styles */
.main-content {
    padding: 20px; /* Add padding around content */
}

/*
.highlight {
    background-color: yellow; 
    This block is currently disabled 
}
*/

footer {
    text-align: center; /* Center align footer text */
    font-size: 0.8em; /* Smaller text for footer */
    color: #999; /* Gray text color */
}

CSS Selectors

Selectors are used to target HTML elements you want to style. Common types include:

Element Selector: Targets all elements of a specific type.


p {
    color: green;
}

Try it Yourself

Class Selector: Targets elements with a specific class attribute.


.className {
    color: blue;
}

Try it Yourself

ID Selector: Targets an element with a specific ID attribute.


#idname {
    color: green;
}

Try it Yourself

Universal Selector: Targets all elements.


* {
    color: blue;
}

Try it Yourself

Attribute Selector: Targets elements with a specific attribute.


[type="text"] {
    border: 2px solid black;
}

Try it Yourself

Pseudo-class Selector: Targets elements in a specific state.


a:hover {
    color: green;
}

Try it Yourself

Properties and Values


body {
    background-color: lightblue;
    font-size: 16px;
    margin: 0;
    padding: 0;
}

Combining Selectors

Selectors can be combined to target elements more precisely.

Descendant Selector: Targets elements that are descendants of a specified element.


div p {
    color: green;
}

Try it Yourself

Child Selector: Targets direct child elements of a specified element.


div > p {
    color: blue;
}

Try it Yourself

CSS Syntax

CSS (Cascading Style Sheets) is used to style and layout web pages. Here’s an overview of the basic syntax and how to use it:

Basic Structure

A CSS rule consists of a selector and a declaration block:


selector {
    property: value;
    property: value;
    ...
}

Example:- In this example, I created class container and defined property background-color which has value #ff0000 (It is a red color) and property color which has #FFFF00 ( it is a yellow color)


.container {
 background-color: "#ff0000";  /*red color*/
 color: "#FFFF00";   /*yellow color*/
} 

Try it Yourself

Adding CSS to HTML

Adding CSS to HTML can be done in three main ways: inline CSS, internal CSS, and external CSS. Here’s how each method works:

Inline CSS

Inline CSS is used to apply a unique style to a single HTML element. To use inline CSS, add the style attribute directly within the HTML tag and set the CSS properties and values.

Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inline CSS Example</title>
</head>
<body>
    <h1 style="color: blue; text-align: center;">Hello, world!</h1>
</body>
</html>

Internal CSS

Internal CSS is used to define styles for a single HTML page. You define internal CSS within a <style> element inside the <head> section of the HTML document.

Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Internal CSS Example</title>
    <style>
        body {
            background-color: lightblue;
        }
        h1 {
            color: navy;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>Hello, world!</h1>
</body>
</html>

External CSS

External CSS is used to define styles for multiple HTML pages. You link an external CSS file to an HTML document using the <link> element within the <head> section. This method is the most efficient way to manage and maintain styles across multiple pages.

Example: Create an external CSS file (styles.css):


body {
    background-color: lightblue;
}
h1 {
    color: navy;
    text-align: center;
}

Link the external CSS file in your HTML document:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>External CSS Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Hello, world!</h1>
</body>
</html>

Best Practices

Use external CSS: Whenever possible, use external CSS for better maintainability and separation of concerns.

Keep it organized: Group related styles together in your CSS files and use comments to describe sections.

Use meaningful names: Use descriptive class and ID names to make your CSS easier to understand and maintain.

Avoid inline CSS: Inline CSS should be avoided unless necessary for quick tests or overrides.

CSS Introduction

CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of a document written in HTML or XML. CSS describes how elements should be rendered on screen, on paper, in speech, or on other media.

Basic Structure of CSS

CSS is made up of rules. Each rule consists of a selector and a declaration block.


selector {
  propertyName1: value1;
  propertyName2: value2;
}

Selector: This is the HTML element you want to style.

Declaration block: This contains one or more declarations separated by semicolons. Each declaration includes a CSS property name and a value, separated by a colon.

Example: Here’s a simple example:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS Example</title>
  <style>
    body {
      background-color: lightblue;
    }
    h1 {
      color: navy;
      margin-left: 20px;
    }
  </style>
</head>
<body>
  <h1>Hello, world!</h1>
</body>
</html>

Try it Yourself

In this example:

The body selector styles the entire page’s background to be light blue.

The h1 selector changes the color of the heading to navy and adds a left margin.

HTML Input attributes

An HTML input attribute is a property or setting applied to an <input> element in an HTML form that defines the behavior, appearance, or constraints of that input field. Attributes provide additional information about how the input should function, such as specifying the type of data the input should accept, setting a default value, or enforcing validation rules. Here are some commonly used attributes:

1. type: Specifies the type of input element.


<input type="text" name="firstName">

2. name: Specifies the name of the input element, which is used to reference the form data after it is submitted.


<input type="text" name="firstName">

3. value: Specifies the initial value of the input element.


<input type="text" name="firstName" value="John">

4. placeholder: Provides a short hint that describes the expected value of the input field.


<input type="text" name="firstName" placeholder="Enter your First Name">

5. required: Specifies that an input field must be filled out before submitting the form.


<input type="text" name="firstName" required>

6. readonly: Makes the input field read-only.


<input type="text" name="firstName" value="John" readonly>

7. disabled: Disables the input field, making it uneditable and non-submittable.


<input type="text" name="firstName" disabled>

8. maxlength: Specifies the maximum number of characters allowed in the input field.


<input type="text" name="firstName" maxlength="10">

9. minlength: Specifies the minimum number of characters required in the input field.


<input type="text" name="firstName" minlength="5">

10. min and max: Specifies the minimum and maximum values for numeric input fields.


<input type="number" name="age" min="18" max="90">

11. step: Specifies the legal number intervals for numeric input fields.


<input type="number" name="quantity" step="2">

12. pattern: Specifies a regular expression that the input field’s value must match


<input type="text" name="email" pattern="/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/">

13. autocomplete: Specifies whether the input field should have autocomplete enabled.


<input type="text" name="firstName" autocomplete="on">

14. autofocus: Specifies that the input field should automatically get focus when the page loads.


<input type="text" name="firstName" autofocus>

15. multiple: Allows multiple values to be entered in an input field.


<input type="file" name="files" multiple>

16. size: Specifies the visible width, in characters, of the input field.


<input type="text" name="firstName" size="10">

HTML Form elements

HTML form elements are used to collect user input. Here are some of the most commonly used form elements:

1. Form (<form>):

The container for all form elements.


<form action="/submit" method="post">
    <!-- form elements go here -->
</form>

2. Input (<input>): Used for various types of user input.


<!-- Text input -->
<input type="text" name="username">

<!-- Password input -->
<input type="password" name="password">

<!-- Checkbox input -->
<input type="checkbox" name="remember_me">

<!-- Radio button input -->
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female

<!-- Submit button -->
<input type="submit" value="Submit">

3. Label (<label>): Used to define labels for input elements.


<label for="username">Username:</label>
<input type="text" id="username" name="username">

4. TextArea (<textarea>): Multi-line text input.


<textarea name="message" rows="4" cols="50"></textarea>

5. Select (<select>): Dropdown list.


<select name="options">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
</select>

6. Button (<button>): Button element.


<button type="submit">Submit</button>

7. Fieldset (<fieldset>) and Legend (<legend>): Used to group related elements and provide a caption.


<fieldset>
    <legend>Personal Information</legend>
    <label for="firstname">First name:</label>
    <input type="text" id="firstname" name="firstname">
    <label for="lastname">Last name:</label>
    <input type="text" id="lastname" name="lastname">
</fieldset>

8. Datalist (<datalist>): Provides a list of predefined options for an input element.


<input list="browsers" name="browser">
<datalist id="browsers">
    <option value="Chrome">
    <option value="Firefox">
    <option value="Safari">
    <option value="Edge">
    <option value="Opera">
</datalist>

9. Output (<output>): Represents the result of a calculation or user action.


<output name="result" for="a b">0</output>

10. Input types: There are many other types of input elements, such as color, date, email, file, number, range, search, tel, time, url, etc.


<!-- Date input -->
<input type="date" name="birthday">

<!-- Email input -->
<input type="email" name="email">

<!-- Number input -->
<input type="number" name="quantity" min="1" max="10">

HTML form attributes

HTML form attributes control various aspects of how a form behaves and interacts with the user. Here’s a detailed look at some of the key HTML form attributes:

1. action

Specifies the URL where the form data should be sent when the form is submitted.


<form action="/submit-form">
2. method

Defines the HTTP method (either GET or POST) used to send form data.


<form method="post">

GET: Appends form data to the URL (not recommended for sensitive data).

POST: Sends form data as part of the HTTP request body (more secure for sensitive data).

3. target

Specifies where to open the response after form submission.


<form target="_blank">

_blank: Opens in a new tab or window.

_self: Opens in the same frame as the form.

_parent: Opens in the parent frame.

_top: Opens in the full window.

4. enctype

Specifies how the form data should be encoded when submitting it to the server. Used with POST method.


<form enctype="multipart/form-data">

application/x-www-form-urlencoded: Default encoding, suitable for most forms.

multipart/form-data: Used for forms that include file uploads.

text/plain: Submits data as plain text (rarely used).

5. autocomplete

Controls whether the browser should automatically complete fields based on previous entries.


<form autocomplete="on">

on: Enables auto-completion.

off: Disables auto-completion.

6. novalidate

Disables form validation when submitting the form.


<form novalidate>
7. name

Assigns a name to the form, which can be used for referencing it in scripts.


<form name="myForm">
8. accept-charset

Specifies the character encodings that the server can handle.


<form accept-charset="UTF-8">

Example Form Using Various Attributes


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form with Attributes</title>
</head>
<body>
    <h2>Form with Various Attributes</h2>
    <form action="/submit-form" 
          method="post" 
          target="_blank" 
          enctype="multipart/form-data" 
          autocomplete="on" 
          novalidate 
          accept-charset="UTF-8">
        
        <!-- Text Input -->
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username" placeholder="Enter your username" required><br><br>

        <!-- Password Input -->
        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password" minlength="6" required><br><br>

        <!-- Email Input -->
        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email" required><br><br>

        <!-- File Upload -->
        <label for="resume">Upload Resume:</label><br>
        <input type="file" id="resume" name="resume" accept=".pdf,.doc,.docx"><br><br>

        <!-- Submit Button -->
        <input type="submit" value="Submit">
    </form>
</body>
</html>

HTML Form

HTML forms are used to collect user input. They are essential for tasks such as user registration, login, and submitting information. A form can include various input elements like text fields, radio buttons, checkboxes, and more.

HTML input element

The HTML <input> element is a versatile and essential part of web forms, allowing users to enter data in various formats. Different types of <input> elements can be used to capture a wide range of user input, from text and numbers to dates and files. Each type of input can have specific attributes to customize its behavior.

Text input


 <form>
	<!-- Text Input -->
	<label for="username">Username:</label><br>
	<input type="text" id="username" name="username" placeholder="Enter your username">
</form>

Password Input


 <form>
	 <label for="password">Password:</label><br>
     <input type="password" id="password" name="password" minlength="6">
</form>


Email Input


 <form>
	    <label for="email">Email:</label><br>
        <input type="email" id="email" name="email">
</form>

Radio Buttons


 <form>
  <label>Gender:</label><br>
        <input type="radio" id="male" name="gender" value="male" checked>
        <label for="male">Male</label><br>
        <input type="radio" id="female" name="gender" value="female">
        <label for="female">Female</label>
</form>


Checkboxes


<form>
<label>Hobbies:</label><br>
        <input type="checkbox" id="hobby1" name="hobbies" value="reading">
        <label for="hobby1">Reading</label><br>
        <input type="checkbox" id="hobby2" name="hobbies" value="traveling">
        <label for="hobby2">Traveling</label><br>
        <input type="checkbox" id="hobby3" name="hobbies" value="gaming">
        <label for="hobby3">Gaming</label>
</form>



Dropdown Select


<form>
 <label for="country">Country:</label><br>
        <select id="country" name="country">
            <option value="in">India</option>
            <option value="us">Unites States</option>
            <option value="uk">United Kingdom</option>
            <option value="au">Australia</option>
        </select>
</form>

File Upload


<form>
<label for="resume">Upload Resume:</label><br>
<input type="file" id="resume" name="resume" accept=".pdf,.doc,.docx">
</form>

Number Input


<form>
<label for="age">Age:</label><br>
<input type="number" id="age" name="age" min="18" max="100">
</form>

Date Input


<form>
<label for="dob">Date of Birth:</label><br>
<input type="date" id="dob" name="dob">
</form>

HTML Responsive

HTML responsive design refers to the practice of creating web pages that adapt and provide an optimal viewing experience across a wide range of devices, including desktops, tablets, and mobile phones. This involves using flexible layouts, images, and CSS media queries to ensure that the content is readable and accessible on any device.

Key Concepts in Responsive Design

1. Viewport Meta Tag: Controls the layout on mobile browsers.

2. Flexible Grid Layouts: Uses relative units like percentages instead of fixed units like pixels.

3. Flexible Images: Ensures images scale within their containing elements.

4. CSS Media Queries: Applies different styles for different screen sizes.

Viewport Meta Tag

The viewport meta tag is essential for responsive web design. It ensures that the web page is properly scaled on mobile devices.


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

Flexible Grid Layouts

Using relative units like percentages allows your layout to adapt to various screen sizes.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Grid Layout</title>
    <style>
        .container {
            display: flex;
            flex-wrap: wrap;
        }
        .item {
            flex: 1 1 100%; /* Flex-grow, flex-shrink, and flex-basis */
            box-sizing: border-box;
            padding: 10px;
        }
        @media (min-width: 600px) {
            .item {
                flex: 1 1 50%; /* Two columns layout for screens 600px and up */
            }
        }
        @media (min-width: 900px) {
            .item {
                flex: 1 1 33.33%; /* Three columns layout for screens 900px and up */
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="item" style="background-color: lightcoral;">Item 1</div>
        <div class="item" style="background-color: lightblue;">Item 2</div>
        <div class="item" style="background-color: lightgreen;">Item 3</div>
    </div>
</body>
</html>

Flexible Images

Make images responsive by setting their maximum width to 100% of their containing element.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Images</title>
    <style>
        img {
            max-width: 100%;
            height: auto;
        }
    </style>
</head>
<body>
    <img src="image.jpg" alt="Responsive Image">
</body>
</html>

CSS Media Queries

Media queries allow you to apply different styles based on the device’s characteristics, such as width, height, and orientation.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Design with Media Queries</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .container {
            padding: 20px;
        }
        .box {
            background-color: lightblue;
            padding: 20px;
            margin: 10px 0;
        }
        @media (min-width: 600px) {
            .box {
                background-color: lightgreen;
            }
        }
        @media (min-width: 900px) {
            .box {
                background-color: lightcoral;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="box">Resize the browser window to see the effect.</div>
    </div>
</body>
</html>

Frameworks for Responsive Design

Several CSS frameworks provide built-in responsiveness and can speed up the development process. Popular frameworks include:

Bootstrap: Uses a grid system and responsive utilities.

HTML Head

The <head> element in HTML is a container for metadata (data about data) and links to external resources that are related to the document. It is placed between the <html> and <body> tags and typically includes information such as the document title, character set, styles, scripts, and other meta-information.

Common Elements in the <head>

1. <title>: Specifies the title of the document, which is displayed in the browser’s title bar or tab.

2. <meta>: Provides metadata such as character set, author, description, keywords, and viewport settings.

3. <link>: Links to external resources like stylesheets, icons, and prefetching.

4. <style>: Embeds internal CSS styles.

5. <script>: Embeds or links to JavaScript code.

Example

Here’s a basic example of a <head> section:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="A brief description of the page">
    <meta name="keywords" content="HTML, CSS, JavaScript, tutorial">
    <meta name="author" content="Your Name">
    <title>Document Title</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <style>
        /* Internal CSS */
        body {
            font-family: Arial, sans-serif;
        }
    </style>
    <script src="script.js" defer></script>
</head>
<body>
    <!-- Page content goes here -->
</body>
</html>

Explanation of the Example

1. <meta charset="UTF-8">: Sets the character encoding for the document to UTF-8.

2. <meta name="viewport" content="width=device-width, initial-scale=1.0">: Ensures proper rendering and touch zooming on mobile devices.

3. <meta name="description" content="A brief description of the page">: Provides a short description of the page, useful for search engines.

4. <meta name="keywords" content="HTML, CSS, JavaScript, tutorial">: Lists keywords relevant to the page content, aiding in SEO.

5. <meta name="author" content="Your Name">: Specifies the author of the document.

6. <title>Document Title</title>: Sets the title of the web page.

7. <link rel="stylesheet" href="styles.css">: Links to an external CSS stylesheet.

8. <link rel="icon" href="favicon.ico" type="image/x-icon">: Links to the favicon of the website.

9. <style>: Contains internal CSS styles.

10. <script src="script.js" defer></script>: Links to an external JavaScript file with the defer attribute, ensuring the script is executed after the document has been parsed.

Importance of the <head> Element

SEO: Meta tags like description and keywords help search engines understand the content and relevance of the page.

Accessibility: Proper metadata can improve the accessibility of the webpage.

Performance: External resources such as stylesheets and scripts linked in the <head> can be loaded efficiently to optimize page performance.

User Experience: The title and favicon enhance the user experience by providing meaningful information and visual cues.

By organizing these elements within the <head>, you can ensure that your webpage is well-optimized, accessible, and user-friendly.

HTML JavaScript

HTML and JavaScript are often used together to create interactive and dynamic web pages. JavaScript is a programming language that can manipulate the content, structure, and style of a web page in real-time. You can embed JavaScript directly within HTML documents or link to external JavaScript files.

Embedding JavaScript in HTML

There are several ways to include JavaScript in an HTML document:

1. Inline JavaScript: Using the script tag directly within the HTML.

2. Internal JavaScript: Including JavaScript in the head or body of the HTML document within script tags.

3. External JavaScript: Linking to a separate JavaScript file.

Inline JavaScript

You can write JavaScript directly within HTML tags using the onclick, onload, and other event attributes.


<!DOCTYPE html>
<html lang="en">
<head>
    <title>Inline JavaScript Example</title>
</head>
<body>
    <button onclick="alert('Button clicked!')">Click Me</button>
</body>
</html>

Internal JavaScript

You can include JavaScript code within script tags inside the head or body of the HTML document.


<!DOCTYPE html>
<html lang="en">
<head>
    <title>Internal JavaScript Example</title>
    <script>
        function showMessage() {
            alert('Hello, World!');
        }
    </script>
</head>
<body>
    <button onclick="showMessage()">Click Me</button>
</body>
</html>

External JavaScript

You can create a separate JavaScript file and link to it using the src attribute of the script tag.

app.js


function showMessage() {
    alert('Hello, World!');
}

index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <title>External JavaScript Example</title>
    <script src="app.js"></script>
</head>
<body>
    <button onclick="showMessage()">Click Me</button>
</body>
</html>

HTML Iframe

An HTML <iframe> (Inline Frame) is used to embed another HTML document within the current document. This allows you to display a webpage within a webpage, making it a powerful tool for including external content such as videos, maps, or other web applications.

Syntax

The basic syntax for an <iframe> is:


<iframe src="URL" width="width" height="height"></iframe>

Iframe Attributes

src: Specifies the URL of the document to be embedded.

width: Sets the width of the iframe (in pixels or as a percentage).

height: Sets the height of the iframe (in pixels or as a percentage).

allow: Specifies a feature policy for the iframe.

allowfullscreen: Allows the iframe to be viewed in full-screen mode.

loading: Specifies the loading behavior of the iframe (lazy or eager).

Example: Here’s an example of how to use an <iframe> to embed a Google website:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Iframe Example</title>
</head>
<body>
    <h1>Embedding a Google Map</h1>
    <div class="iframe-container">
        <iframe src="https://www.google.com" allowfullscreen loading="lazy">
        </iframe>
    </div>
</body>
</html>

Explanation of the Example

1. HTML Structure: The document includes a heading and a div container for the iframe.

Iframe Source: The src attribute is set to the URL of a Google Map embed link.

Use Cases:

Embedding Videos: Commonly used to embed YouTube or Vimeo videos.

Displaying Maps: Embed maps from services like Google Maps.

Including External Web Pages: Display content from another website or application within your site.

HTML Id

HTML id attributes are used to uniquely identify an element within an HTML document. Unlike classes, which can be applied to multiple elements, an id should be unique within the document. This uniqueness makes id attributes particularly useful for styling specific elements and for selecting elements with JavaScript.

Syntax

To add an id to an HTML element, use the id attribute:


<tag id="unique-id">Content</tag>

Where tag is HTML element like <div>, <p>, etc.

Example

Here’s an example demonstrating how to use id in HTML:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Id Example</title>
    <style>
        #header {
            background-color: blue;
            color: white;
            padding: 10px;
            text-align: center;
        }
        #content {
            padding: 20px;
            background-color: lightgrey;
        }
        #footer {
            background-color: blue;
            color: white;
            padding: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="header">
        <h1>Header Section</h1>
    </div>
    <div id="content">
        <p>This is the main content area.</p>
    </div>
    <div id="footer">
        <p>Footer Section</p>
    </div>
</body>
</html>

Explanation of the Example

1. HTML Structure: The HTML document includes three main sections: header, content, and footer.

2. Id Assignment: Each section is assigned an id (header, content, footer) using the id attribute.

3. CSS Styling: In the <style> block, each id is styled

  • #header: Blue background, white text, padding, and center-aligned text.
  • #content: Light grey background and padding.
  • #footer: Similar styling to the header.

Benefits of Using Ids

Uniqueness: Ensures that each id is unique within the document, providing a way to specifically target individual elements.

Specificity: Provides higher specificity in CSS, which can be useful for overriding other styles.

JavaScript Targeting: Easily select and manipulate elements with JavaScript using methods like getElementById.

JavaScript Example

Ids are commonly used in JavaScript to access and manipulate specific elements:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Id Example</title>
    <style>
        #header {
            background-color: blue;
            color: white;
            padding: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="header">
        <h1>Header Section</h1>
    </div>
    <button onclick="changeHeaderColor()">Change Header Color</button>

    <script>
        function changeHeaderColor() {
            document.getElementById('header').style.backgroundColor = 'green';
        }
    </script>
</body>
</html>

Explanation of the JavaScript Example

1. HTML Structure: The document includes a header and a button.

2. Id Assignment: The header div is assigned an id of header.

3. JavaScript Function: The changeHeaderColor function uses getElementById to select the header element and change its background color to green when the button is clicked.

By using id attributes effectively, you can create specific, targeted styles and behaviors for individual elements within your web pages.

HTML Classes

HTML classes are used to group elements for styling and scripting purposes. By assigning a class attribute to HTML elements, you can apply specific styles and behaviors to those elements using CSS and JavaScript.

Syntax

To add a class to an HTML element, use the class attribute:


<tag class="class-name">Content</tag>

Benefits of Using Classes

Reusability: Apply the same styles to multiple elements by using the same class name.

Maintainability: Easily update styles in one place by modifying the CSS for a class.

Organization: Helps to keep the HTML structure organized and readable.

JavaScript Targeting: Classes can be used to select and manipulate elements with JavaScript.

Example

Here’s an example demonstrating how to use classes in HTML:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Classes Example</title>
    <style>
        .header {
            background-color: blue;
            color: white;
            padding: 10px;
            text-align: center;
        }
        .content {
            padding: 20px;
            background-color: lightgrey;
        }
        .footer {
            background-color: blue;
            color: white;
            padding: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>Header Section</h1>
    </div>
    <div class="content">
        <p>This is the main content area.</p>
    </div>
    <div class="footer">
        <p>Footer Section</p>
    </div>
</body>
</html>

Explanation of the Example

  1. HTML Structure: The HTML document includes three main sections: header, content, and footer.
  2. Class Assignment: Each section is assigned a class (header, content, footer) using the class attribute.
  3. CSS Styling: In the <style> block, each class is styled:
    • .header: Blue background, white text, padding, and center-aligned text.
    • .content: Light grey background and padding.
    • .footer: Similar styling to the header.

Multiple Classes

An element can have multiple classes, separated by spaces:


<div class="class1 class2">Content</div>

This allows for combining different styles and behaviors for a single element.

Example with Multiple Classes


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple Classes Example</title>
    <style>
        .highlight {
            background-color: yellow;
        }
        .italic {
            font-style: italic;
        }
    </style>
</head>
<body>
    <p class="highlight italic">This paragraph is highlighted and italicized.</p>
</body>
</html>

In this example, the paragraph is both highlighted and italicized by combining the highlight and italic classes.

HTML Div

An HTML <div> is a block-level element used to group other HTML elements together. It’s often used for styling and layout purposes with CSS and can contain various other HTML elements such as text, images, links, and other nested <div> elements.

Basic Syntax


<div>
  <!-- Content goes here -->
</div>

Characteristics of <div>:

Block-Level Element: Occupies the full width available and starts on a new line.

Generic Container: Can contain various other HTML elements such as text, images, links, other nested <div> elements, etc.

No Default Styling: By itself, it doesn’t apply any styles or formatting, making it a flexible tool for layout and design.

Example:

Here’s an example of how a <div> can be used to structure a simple webpage:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example Div</title>
    <style>
        .container {
            width: 100%;
            background-color: lightgrey;
        }
        .header {
            background-color: blue;
            color: white;
            padding: 10px;
        }
        .content {
            padding: 20px;
        }
        .footer {
            background-color: blue;
            color: white;
            padding: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Header</h1>
        </div>
        <div class="content">
            <p>This is the content area.</p>
        </div>
        <div class="footer">
            <p>Footer</p>
        </div>
    </div>
</body>
</html>

Explanation of the Example:

Container Div: The .container div wraps the entire content, creating a main container for the page.

Header Div: The .header div contains the header section, styled with a blue background and white text.

Content Div: The .content div holds the main content, with padding applied for spacing.

Footer Div: The .footer div contains the footer, styled similarly to the header.

HTML Block and Inline

In HTML, elements are classified as either block-level elements or inline elements. This classification determines how the elements are rendered on the web page.

Block-Level Elements

Always start on a new line.

Take up the full width available (stretches out to the left and right as far as it can).

Have top and bottom margins.

Can contain other block-level elements and inline elements.

Examples of block-level elements include:

  • <div>
  • <p>
  • <h1> to <h6>
  • <ul> and <ol>
  • <li>
  • <table>
  • <header>
  • <footer>
  • <section>
  • <article>

Example:


<div>
  <h1>Title</h1>
  <p>This is a paragraph inside a div.</p>
</div>
Inline Elements

Do not start on a new line.

Only take up as much width as necessary.

Do not force other content to move to a new line.

Can only contain other inline elements or text content.

Examples of inline elements include:

  • <span>
  • <a>
  • <img>
  • <strong> and <b>
  • <em> and <i>
  • <code>
  • <br>

Example:


<p>This is a paragraph with <strong>bold text</strong> and <em>italic text</em>.</p>

Key Differences

  1. Rendering: Block-level elements create larger blocks of content, whereas inline elements are contained within block-level elements and do not disrupt the flow of content.
  2. Containment: Block-level elements can contain both block-level and inline elements, while inline elements can only contain other inline elements or text.

HTML Lists

HTML lists are used to group related items together, and there are three main types of lists in HTML:

1. Ordered List (<ol>): Used to create a list of items where the order matters. Each list item is numbered.

2. Unordered List (<ul>): Used to create a list of items where the order doesn’t matter. Each list item is typically marked with a bullet point.

3. Definition List (<dl>): Used to create a list of terms and their definitions.

Ordered List (<ol>)

An ordered list is created using the <ol> tag, and each item within the list is wrapped in an <li> (list item) tag.

Example:


<ol>
  <li>First item</li>
  <li>Second item</li>
  <li>Third item</li>
</ol>

This would render as:

  1. First item
  2. Second item
  3. Third item

Unordered List (<ul>)

An unordered list is created using the <ul> tag, and like ordered lists, each item is wrapped in an <li> tag.

Example:


<ul>
  <li>Item one</li>
  <li>Item two</li>
  <li>Item three</li>
</ul>

This would render as:

  • Item one
  • Item two
  • Item three

Definition List (<dl>)

A definition list is created using the <dl> tag. Inside a definition list, each term is wrapped in a <dt> (definition term) tag, and each definition is wrapped in a <dd> (definition description) tag.

Example:


<dl>
  <dt>HTML</dt>
  <dd>A markup language for creating web pages</dd>
  <dt>CSS</dt>
  <dd>A style sheet language for describing the presentation of a document</dd>
</dl>

This would render as:

HTML: A markup language for creating web pages

CSS: A style sheet language for describing the presentation of a document

Nesting Lists

Lists can be nested within each other to create more complex structures.

Example:


<ul>
  <li>Item one
    <ul>
      <li>Subitem one</li>
      <li>Subitem two</li>
    </ul>
  </li>
  <li>Item two</li>
</ul>

This would render as:

  • Item one
    • Subitem one
    • Subitem two
  • Item two

HTML Tables

HTML tables are used to organize and display data in a tabular format on web pages. They are created using a combination of HTML tags to define the structure and content of the table. Here’s a brief overview of the main elements used to create HTML tables:

<table>: This tag defines the beginning and end of the table.

<tr>: This tag defines a table row.

<th>: This tag defines a table header cell, which is typically bold and centered.

<td>: This tag defines a table data cell.

Here is a simple example of an HTML table:


<table border="1">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>John</td>
    <td>Taylor</td>
    <td>35</td>
  </tr>
  <tr>
    <td>Tom</td>
    <td>Taylor</td>
    <td>30</td>
  </tr>
</table>

In this example:

The <table border="1"> element creates a table with a border.

The <tr> elements define rows in the table.

The first row uses <th> elements for headers: “First Name,” “Last Name,” and “Age.”

Subsequent rows use <td> elements for data cells, such as “John,” “Taylor,” and “35.”

HTML Page Title

The HTML page title is the text displayed in the title bar or tab of a web browser. It is defined using the <title> tag within the <head> section of an HTML document. The title is important for several reasons, including usability, accessibility, and search engine optimization (SEO).

Basic Syntax


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Web Page</title>
</head>
<body>
  <h1>Welcome to My Web Page</h1>
</body>
</html>

In this example, the content of the <title> tag is “My Web Page”. This text will appear in the browser tab and as the title of the page when bookmarked.

Importance of the HTML Page Title

1. Browser Tabs: The title helps users identify and switch between multiple open tabs.

2. Bookmarks/Favorites: When users bookmark a page, the title is used as the default name for the bookmark.

3. Search Engine Optimization (SEO): Search engines use the title to understand the content of the page. A well-crafted title can improve a page’s search ranking and click-through rate.

4. Accessibility: Screen readers announce the title of the page when it loads, helping users understand the page’s content.

HTML favicon

A favicon (short for “favorite icon”) is a small icon associated with a specific website or web page, typically displayed in the browser’s address bar, bookmarks, and tabs. It helps users quickly identify and navigate to their favorite sites.

Basic Syntax

To add a favicon to your website, you use the <link> tag inside the <head> section of your HTML document. Here’s a basic example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple Classes Example</title>
    <style>
        .highlight {
            background-color: yellow;
        }
        .italic {
            font-style: italic;
        }
    </style>
</head>
<body>
    <p class="highlight italic">This paragraph is highlighted and italicized.</p>
</body>
</html>

Steps to Add a Favicon

1. Create a Favicon Image:

Design a small image, typically 16×16 pixels or 32×32 pixels in size.

Save the image in a format like .ico, .png, .gif, or .svg.

2. Upload the Favicon to Your Website:

Place the favicon file in your website’s root directory or a specific directory for images.

3. Add the Favicon to Your HTML:

Add the <link> tag in the <head> section of your HTML document.

Example Using Different Image Formats


<head>
  <!-- ICO format (most commonly used) -->
  <link rel="icon" href="/favicon.ico" type="image/x-icon">

  <!-- PNG format -->
  <link rel="icon" href="/favicon.png" type="image/png">

  <!-- SVG format -->
  <link rel="icon" href="/favicon.svg" type="image/svg+xml">
</head>

HTML images

HTML images are elements used to embed pictures and other visual media into web pages. They are created using the <img> tag in HTML. Unlike most other tags, the <img> tag is self-closing and does not have a closing tag.

Basic Syntax

Here is a basic example of an HTML image:


<img src="image.jpg" alt="Description of image">

In this example:

The <img> tag defines the image.

The src attribute specifies the path to the image file.

The alt attribute provides alternative text for the image, which is important for accessibility and is displayed if the image cannot be loaded.

Attributes of the <img> Tag

src: Specifies the URL or path to the image file.

alt: Provides alternative text for the image, which is used by screen readers and displayed if the image fails to load.

width: Specifies the width of the image (in pixels or as a percentage).

height: Specifies the height of the image (in pixels or as a percentage).

title: Provides additional information about the image, often shown as a tooltip when the mouse hovers over the image.

Example with More Attributes


<img src="https://www.example.com/image.jpg" alt="A beautiful scenery" width="600" height="400" title="Scenery">

Using Relative and Absolute URLs

Absolute URLs: Full web addresses (e.g., https://www.example.com/images/pic.jpg).

Relative URLs: Links relative to the current page (e.g., images/pic.jpg, ../images/pic.jpg).

Responsive Images

To make images responsive, you can use CSS or HTML attributes. A common method is to set the width to 100% and the height to auto:


<img src="image.jpg" alt="Responsive image" style="width:100%; height:auto;">

HTML links

HTML links, or hyperlinks, are elements in a web page that users can click on to navigate to another web page or resource. They are created using the <a> (anchor) tag in HTML. Here is a basic example:


<a href="https://www.abc.com">Visit Example</a>

In this example:

  1. The <a> tag defines the link.
  2. The href attribute specifies the URL of the page the link goes to.
  3. The text between the opening and closing <a> tags (“Visit Example”) is the clickable part of the link.

Attributes of the <a> Tag

  1. href: Specifies the URL of the page the link goes to.
  2. target: Specifies where to open the linked document (e.g., _blank for a new tab/window, _self for the same frame, _parent for the parent frame, _top for the full body of the window).
  3. title: Provides additional information about the link, often shown as a tooltip when the mouse hovers over the link.
  4. rel: Specifies the relationship between the current document and the linked document (e.g., nofollow, noopener, noreferrer).

Example with more Attributes


<a href="https://www.abc.com" target="_blank" title="Visit Example" rel="noopener noreferrer">Visit Example</a>

Types of Links

  1. Absolute URLs: Full web addresses (e.g., https://www.abc.com/page1.html).
  2. Relative URLs: Links relative to the current page (e.g., page2.html, ../images/pic.jpg).
  3. Email Links: mailto: followed by an email address (e.g., mailto:someone@example.com)

Linking to a Specific Part of a Page

You can also link to a specific part of the same or another page using an anchor. This is done by setting an id on the target element and linking to it with a # prefix:


<!-- Target element with an id -->
<h2 id="section1">Section 1</h2>

<!-- Link to the target element -->
<a href="#section1">Go to Section 1</a>

External Links vs. Internal Links

External Links: Point to a different website (e.g., https://www.google.com).

Internal Links: Point to a different page on the same website (e.g., about.html).

HTML CSS

CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of a document written in HTML or XML. It controls the layout, design, and visual aspects of web pages, allowing developers to separate content from design for easier maintenance and more flexible presentation.

Key Features of CSS

1. Selectors: CSS uses selectors to target HTML elements that you want to style.


p {
    color: blue;
}

This rule applies to all <p> elements, setting their text color to blue.

2. Properties and Values: CSS rules consist of properties and values.


p {
    color: blue;     /* property: value */
    font-size: 20px; /* property: value */
}

3. Cascading: The term “cascading” refers to the way CSS rules are applied based on their order and specificity. Rules can be applied from:

  1. Browser default styles
  2. External stylesheets
  3. Internal stylesheets (within a <style> tag)
  4. Inline styles (within an element’s style attribute)

4. Specificity: Determines which CSS rule is applied when multiple rules match the same element. Specificity is calculated based on the types of selectors used.


/* ID selector - higher specificity */
#header {
    color: red;
}

/* Class selector - lower specificity than ID */
.header {
    color: blue;
}

/* Element selector - lowest specificity */
h1 {
    color: green;
}

Ways to Use CSS

1. Inline CSS: Applied directly within an HTML element using the style attribute.


<p style="color: blue; font-size: 20px;">This is a blue paragraph with a font size of 20px.</p>

2. Internal CSS: Defined within a <style> tag in the <head> section of the HTML document.


<!DOCTYPE html>
<html>
<head>
    <style>
        p {
            color: blue;
            font-size: 20px;
        }
    </style>
</head>
<body>
    <p>This is a blue paragraph with a font size of 20px.</p>
</body>
</html>

3. External CSS: Defined in an external stylesheet file (e.g., styles.css) and linked to the HTML document using the <link> tag.

in index.html file


<!-- HTML File -->
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <p>This is a styled paragraph.</p>
</body>
</html>

in styles.css file


/* styles.css */
p {
    color: blue;
    font-size: 20px;
}

CSS Syntax

A CSS rule set consists of a selector and a declaration block.


selector {
    property: value;
}

Example:


h1 {
    color: blue;
    font-size: 24px;
}
Common CSS Properties

Color: Sets the color of text.


p {
    color: red;
}

Font: Controls font properties like font-size, font-family, font-weight, etc.


p {
    font-size: 16px;
    font-family: Arial, sans-serif;
}

Background: Sets background properties like background-color, background-image, etc.


body {
    background-color: #f0f0f0;
}

Margin: Sets the space outside an element.


p {
    margin: 10px;
}

Padding: Sets the space inside an element, between the content and the border.


p {
    padding: 10px;
}

Border: Sets the border around an element.


p {
    border: 1px solid black;
}

Benefits of Using CSS

Separation of Content and Presentation: Keeps HTML clean and focused on content, while CSS handles design.

Reusability: Apply the same styles across multiple pages.

Consistency: Ensures a uniform look and feel across a website.

Maintainability: Easier to update and manage styles from a single location.

HTML colors

HTML colors are used to set the color of various elements on a webpage. Colors can be defined in several ways in HTML, including by name, hexadecimal values, RGB values, RGBA values (which include an alpha channel for opacity), HSL values, and HSLA values.

Here are the different ways to specify colors in HTML:

1. Color Names: There are 140 predefined color names in HTML.


<p style="color: red;">This is a red paragraph.</p>

2. Hexadecimal Values: Colors can be specified using a hex code, which starts with # followed by six hexadecimal digits.


<p style="color: #ff0000;">This is a red paragraph.</p>

3. RGB Values: Colors can be defined using the rgb() function, with values ranging from 0 to 255 for red, green, and blue.


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

4. RGBA Values: Similar to RGB, but includes an alpha channel for opacity, with values ranging from 0 (fully transparent) to 1 (fully opaque).


<p style="color: rgba(255, 0, 0, 0.5);">This is a semi-transparent red paragraph.</p>

5. HSL Values: Colors can be defined using the hsl() function, with values for hue (0-360 degrees), saturation (0%-100%), and lightness (0%-100%).


<p style="color: hsl(0, 100%, 50%);">This is a red paragraph.</p>

6. HSLA Values: Similar to HSL, but includes an alpha channel for opacity.


<p style="color: hsla(0, 100%, 50%, 0.5);">This is a semi-transparent red paragraph.</p>

By using these methods, you can apply colors to text, backgrounds, borders, and other elements on a webpage to enhance its visual appeal and usability.

HTML comments

HTML comments are used to add notes or explanations within the HTML code, which are not displayed in the web browser. They are useful for documenting the code, explaining the structure, or temporarily disabling parts of the code. HTML comments are enclosed within <!-- and --> tags.

Here is an example of an HTML comment:


<!-- This is a comment -->
<p>This is a paragraph.</p>
<!-- <p>This paragraph is commented out and will not be displayed.</p> -->

In this example, the first line is a comment that won’t be displayed on the web page, and the second comment surrounds a paragraph tag, making the browser ignore it. Comments can be very useful for developers to leave notes or explanations about the code.

HTML Text formatting

HTML text formatting involves using HTML tags to define the appearance and structure of text on a webpage. Here are some commonly used HTML tags for text formatting:

  1. Bold Text: <b> or <strong>

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

2. Italic Text: <i> or <em>


<i>This text is italic.</i>
<em>This text is emphasized and italic.</em>

3. Underlined Text: <u>


<u>This text is underlined.</u>

4. del Text: <del>


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

5. Marked Text: <mark>


<mark>This text is highlighted.</mark>

6. Small Text: <small>


<small>This text is small.</small>

7. Subscript Text: <sub>


H<sub>2</sub>O

8. Superscript Text: <sup>


E = mc<sup>2</sup>

HTML styles

HTML styles refer to the way elements on a web page are presented and formatted. These styles are typically defined using CSS (Cascading Style Sheets), which allows you to control the appearance of HTML elements, such as text, images, and layouts. Here are some key concepts:

  1. Inline Styles: These are applied directly within an HTML element using the style attribute.

<p style="color: blue; font-size: 16px;">This is a blue paragraph.</p>

2. Internal Styles: These are defined within the <style> tag in the <head> section of an HTML document.


<head>
  <style>
    p {
      color: blue;
      font-size: 16px;
    }
  </style>
</head>
<body>
  <p>This is a blue paragraph.</p>
</body>

3. External Styles: These are defined in a separate CSS file, which is linked to the HTML document.


<head>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <p>This is a blue paragraph.</p>
</body>

And in the styles.css file:


p {
  color: blue;
  font-size: 16px;
}

4. CSS Selectors: These are patterns used to select the elements you want to style.

Element Selector: Selects elements based on the element name.


p {
  color: blue;
}

Class Selector: Selects elements based on the class attribute.

in css file


.blue-text {
  color: blue;
}

in html file


<p class="blue-text">This is a blue paragraph.</p>

ID Selector: Selects a single element based on the id attribute.

in css file


#unique-text {
  color: blue;
}

in html file


<p id="unique-text">This is a blue paragraph.</p>

5. CSS Properties: These define the specific style characteristics of an element. Common properties include:

  1. color: Sets the text color.
  2. font-size: Sets the size of the text.
  3. background-color: Sets the background color of an element.
  4. margin: Sets the space around elements.
  5. padding: Sets the space inside elements.
  6. border: Sets the border around elements.

HTML Paragraph

In HTML, a paragraph is defined using the <p> tag. Paragraphs are blocks of text that are separated from adjacent blocks by a blank line in the rendered output. The <p> tag is a block-level element, meaning it creates a block of content that typically begins on a new line.

Syntax

The basic syntax for a paragraph in HTML is as follows:


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

Example

Here is a simple HTML document with a few paragraphs:


<!DOCTYPE html>
<html>
<head>
    <title>HTML Paragraph Example</title>
</head>
<body>
    <p>This is the first paragraph. It contains some text.</p>
    <p>This is the second paragraph. It contains some more text.</p>
    <p>This is the third paragraph. It also contains text.</p>
</body>
</html>

When rendered in a web browser, each paragraph will appear on its own line with some space between each one.

use Attributes in the paragraph

The <p> tag can use various global attributes to control its behavior and appearance. Here are some common attributes:

id: Specifies a unique id for the paragraph.


<p id="intro">This is an introductory paragraph.</p>

class: Specifies one or more class names for the paragraph (used for CSS styling).


<p class="highlight">This paragraph is highlighted.</p>

style: Specifies inline CSS styles for the paragraph.


<p style="color:blue;">This paragraph is blue.</p>

title: Provides additional information about the paragraph (displayed as a tooltip when hovering over the paragraph).


<p title="Tooltip text">Hover over this paragraph to see the tooltip.</p>

Best Practices

Use paragraphs to group related sentences: Paragraphs should be used to group sentences that belong together. Each paragraph should represent a single idea or topic.

Avoid nesting paragraphs: Paragraphs should not be nested within other block-level elements like <div> or within each other.

Keep paragraphs concise: Shorter paragraphs are easier to read, especially on screens. Break up long blocks of text into multiple paragraphs.

HTML Headings

HTML headings are used to define the headings of a web page. Headings are important for both organizing content and improving accessibility and SEO (Search Engine Optimization). HTML provides six levels of headings, from <h1> to <h6>, with <h1> being the highest level (most important) and <h6> being the lowest level (least important).

Syntax and Usage

<h1> to <h6> Tags

each heading level is defined with a specific tag:

<h1>: Defines the most important heading.

<h2>: Defines the second most important heading.

<h3>: Defines the third most important heading.

<h4>: Defines the fourth most important heading.

<h5>: Defines the fifth most important heading.

<h6>: Defines the least important heading.

Example:-


<!DOCTYPE html>
<html>
<head>
    <title>HTML Headings Example</title>
</head>
<body>
    <h1>This is an H1 heading</h1>
    <p>This is a paragraph under the H1 heading.</p>
    
    <h2>This is an H2 heading</h2>
    <p>This is a paragraph under the H2 heading.</p>
    
    <h3>This is an H3 heading</h3>
    <p>This is a paragraph under the H3 heading.</p>
    
    <h4>This is an H4 heading</h4>
    <p>This is a paragraph under the H4 heading.</p>
    
    <h5>This is an H5 heading</h5>
    <p>This is a paragraph under the H5 heading.</p>
    
    <h6>This is an H6 heading</h6>
    <p>This is a paragraph under the H6 heading.</p>
</body>
</html>

Importance of Headings

Organizational Structure: Headings help to structure the content, making it easier for readers to understand and navigate through the document.

SEO (Search Engine Optimization): Search engines use headings to understand the content of a webpage. Proper use of headings can improve the page’s ranking in search results.

Accessibility: Screen readers and other assistive technologies use headings to help users navigate through the content. Properly structured headings can enhance the accessibility of a web page.

Best Practices

Use headings hierarchically: Start with <h1> for the main heading and use <h2> to <h6> for subheadings in a hierarchical manner.

Avoid skipping heading levels: Do not skip heading levels (e.g., from <h1> directly to <h3>) as it can confuse both users and search engines.

Keep headings concise and descriptive: Headings should clearly indicate the content of the section they introduce.

Use one <h1> per page: Typically, a webpage should have only one <h1> element that represents the main topic or title of the page. Use <h2> to <h6> for subheadings.

HTML Attribute

HTML attributes provide additional information about HTML elements. They are always included in the opening tag of the element and come in name/value pairs like name="value". Attributes help customize elements, specify their behavior, and provide metadata.

Key Points About HTML Attributes

  1. Attributes are placed in the opening tag: They are written inside the opening tag of an HTML element.
  2. Attributes come in name/value pairs: The name is the attribute itself, and the value is assigned to it. The value is enclosed in quotes.
  3. Not all elements have the same attributes: Some attributes are specific to certain elements, while others are global and can be used with any element.

Common HTML Attributes

1. Global Attributes

id: Specifies a unique id for an element.


<div id="header">This is the header</div>

class: Specifies one or more class names for an element (used for CSS and JavaScript).


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

style: Contains inline CSS to style an element.


<h1 style="color:blue;">This is a blue heading</h1>

lang: Specifies the language of the element’s content.


<p lang="en">This paragraph is in English.</p>

2. Specific Attributes

href: Specifies the URL of a link (used in <a> tags).


<a href="https://www.example.com">Visit Example</a>

src: Specifies the path to an image (used in <img> tags).


<img src="image.jpg" alt="Description of image" />

alt: Provides alternative text for an image, which is important for accessibility (used in <img> tags).


<img src="image.jpg" alt="A beautiful scenery" />

width and height: Specifies the width and height of an image or other element.


<img src="image.jpg" width="500" height="600" />

type: Specifies the type of input element (used in <input> tags).


<input type="text">
<input type="password">
<input type="submit">

value: Specifies the initial value of an input element (used in <input> tags).


<input type="text" value="John">

name: Specifies the name of an input element (used in forms).


<input type="text" value="John">

placeholder: Provides a hint to the user of what can be entered in the input field.


<input type="text" placeholder="Enter your name">

disabled: Specifies that an input element should be disabled.


<input type="text" disabled>

checked: Specifies that an input element (checkbox or radio button) should be pre-selected when the page loads.


<input type="checkbox" checked>

action: Specifies where to send the form data when a form is submitted (used in <form> tags).


<form action="/submit-form">

method: Specifies the HTTP method to use when sending form data (used in <form> tags).


<form action="/submit-form" method="post">

Example Usage of Attributes

Here’s an example of a form that uses various HTML attributes:


<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <form action="/submit-form" 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"><br><br>
        
        <label for="password">Password:</label>
        <input type="password" id="password" name="password"><br><br>
        
        <input type="submit" value="Submit">
    </form>
</body>
</html>

In this example:

  1. The action attribute in the <form> tag specifies where to send the form data.
  2. The method attribute specifies the HTTP method (post) to use.
  3. The id, name, placeholder, and required attributes are used in the <input> tags to define their behavior and provide hints to the user.

HTML Elements

HTML elements are the building blocks of an HTML document. They define the structure and content of a web page. Here is a comprehensive guide to the most common HTML elements:

1. Basic Elements

<!DOCTYPE html>: Declares the document type and version of HTML.

<html>: The root element of an HTML document.

<head>: Contains meta-information about the document.

<title>: Sets the title of the document, shown in the browser’s title bar or tab.

<body>: Contains the content of the HTML document.

2. Text Elements

<h1> to <h6>: Headings, with <h1> being the highest (most important) and <h6> the lowest (least important).

<p>: Defines a paragraph.

<br>: Inserts a line break.

<hr>: Defines a thematic break (horizontal rule).

3. Formatting Elements

<b>: Bold text.

<strong>: Important text (typically rendered as bold).

<i>: Italic text.

<em>: Emphasized text (typically rendered as italic).

<mark>: Marked/highlighted text.

<small>: Smaller text.

<del>: Deleted (strikethrough) text.

<ins>: Inserted (underlined) text.

<sub>: Subscript text.

<sup>: Superscript text

4. Lists

<ul>: Unordered list (bulleted).

<ol>: Ordered list (numbered).

<li>: List item.

<dl>: Description list.

<dt>: Term in a description list.

<dd>: Description of the term in a description list.

5. Links

<a>: Anchor (hyperlink). The href attribute specifies the URL of the page the link goes to.


<a href="https://www.example.com">Visit Example</a>

6. Images

<img>: Embeds an image. The src attribute specifies the path to the image, and the alt attribute provides alternative text.


<img src="image.jpg" alt="Description of image">

7. Tables

<table>: Defines a table.

<tr>: Table row.

<th>: Table header cell.

<td>: Table data cell.

<caption>: Table caption.


<table>
  <caption>Table Title</caption>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
  </tr>
  <tr>
    <td>Data 1</td>
    <td>Data 2</td>
  </tr>
</table>

What is HTML?

HTML (HyperText Markup Language) is the standard language used to create and design web pages. It describes the structure of a webpage and consists of a series of elements that tell the browser how to display content.

History and Versions of HTML

HTML 1.0 (1991): The first version, a very basic version of HTML.

HTML 2.0 (1995): Standardized version with additional features.

HTML 3.2 (1997): Included new features such as tables and applets.

HTML 4.01 (1999): Introduced more complex features like CSS support.

XHTML (2000): A stricter, XML-based version of HTML.

HTML5 (2014): The latest version, which includes powerful new features like video playback and improved semantics for better accessibility and SEO.

How HTML Works

HTML uses “tags” to mark up content. Tags are enclosed in angle brackets (< >) and typically come in pairs: an opening tag and a closing tag. The content goes between the tags.

Example of a simple HTML element:

<p> is the opening tag.

</p> is the closing tag.

This is a paragraph. is the content.

Basic Structure of an HTML Document

An HTML document has a basic structure that includes several key elements:


<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <h1>This is a Heading</h1>
    <p>This is a paragraph.</p>
</body>
</html>

<!DOCTYPE html>: This declaration defines the document type and version of HTML.

<html>: The root element of an HTML page.

<head>: Contains meta-information about the document (like the title, character set, styles, links, etc.).

<title>: Specifies the title of the document, which is shown in the browser’s title bar or tab.

<body>: Contains the content of the HTML document, such as text, images, links, tables, etc.

install bootstrap in Reactjs

Bootstrap in a React application, you can install it via npm and then import it into your project.

1. Create a React Project (if you haven’t already)


npx create-react-app my-app
cd my-app

2. Install Bootstrap

Install Bootstrap via npm:


npm install bootstrap

3. Import Bootstrap CSS

You need to import the Bootstrap CSS file into your project. You can do this in the src/index.js file:


import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

4. Use Bootstrap Components

Now you can use Bootstrap classes in your React components. Here’s an example of using Bootstrap classes in a component:


import React from 'react';

export default function BootstrapExample() {
   return (
    <div className="container mt-5">
      <h1 className="text-center">Hello, Bootstrap!</h1>
      <button className="btn btn-primary">Click Me</button>
    </div>
  );
}

5. Optionally, Use React Bootstrap

If you prefer to use React components that wrap Bootstrap styles, you can install React Bootstrap:


npm install react-bootstrap

Then, import and use the React Bootstrap components:


import React from 'react';
import { Button, Container } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

export default function ReactBootstrapExample() {
  return (
    <Container className="mt-5">
      <h1 className="text-center">Hello, React Bootstrap!</h1>
      <Button variant="primary">Click Me</Button>
    </Container>
  );
}

Bootstrap in Project Structure

Here is an example of what your project structure might look like after setting up Bootstrap:


my-app/
├── node_modules/
├── public/
├── src/
│   ├── App.js
│   ├── BootstrapExample.js
│   ├── ReactBootstrapExample.js
│   ├── index.css
│   └── index.js
├── .gitignore
├── package.json
├── README.md
└── yarn.lock

axios in Reactjs

Axios is a popular promise-based HTTP client for making HTTP requests, often used in React applications for interacting with APIs. It can be used to perform all types of HTTP requests and works in both the browser and Node.js environments.

How to Install

install Axios using npm or yarn:


npm install axios
# or
yarn add axios

Basic Usage

To use Axios in a React component, you typically import it and then make requests inside useEffect or event handlers.

Example:- get the products list through axios


import React, {useState} from 'react'
import axios from 'axios';
import { useEffect } from 'react';

export default function AxiosExample(){

    var [resData, SetresData] = useState([]);

    async function getProducts()
    {
    var data =  await axios.get('https://fakestoreapi.com/products')
    var results = data.data;
    SetresData(results); 
    }

    useEffect(()=>{
        getProducts()
    },[])

    return(
        <>
        <h1>Axios Example</h1>
        <div>
        {
           resData.map((item, index)=>{
            return <div key={index}>
                {item.title}
             </div>
           });
        
        }
        </div>
        </>
    )
}

Note:- in return we can use <> tag instead of div tag

apply css in reactjs

In React, there are several ways to apply CSS to your components, each with its own advantages. Here are the most common methods:

1. Inline Styles

Inline styles are defined directly within the component using the style attribute. The styles are written as an object, where the property names are camelCased versions of the CSS properties.


import React from 'react';
//MyComponent.jsx
export default function MyComponent() {
  const style = {
    color: 'green',
    backgroundColor: 'yellow',
    padding: '5px',
    borderRadius: '3px'
  };
  return <div style={style}>Hello World text with inline styles!</div>;
}

2. CSS Stylesheets

You can use traditional CSS stylesheets by importing them into your React component. This is the most straightforward way to style your components.

CSS File (styles.css)


.my-class {
    color: 'green',
    backgroundColor: 'yellow',
    padding: '5px',
    borderRadius: '3px'
}

React Component


import React from 'react';
import './styles.css';

//MyComponent.jsx
export default function MyComponent() {
  return <div className="my-class">This is styled with a CSS stylesheet!</div>;
}

3. CSS Modules

CSS Modules allow you to write CSS that is scoped locally to the component. This prevents conflicts with other styles and ensures that styles are only applied to the component they are intended for.

CSS Module (styles.module.css)


.my-class {
    color: 'green',
    backgroundColor: 'yellow',
    padding: '5px',
    borderRadius: '3px'
}

React Component


//CSSModulesComponent.jsx
import React from 'react';
import styles from './styles.module.css';

export default function CSSModulesComponent() {
  return <div className={styles.myClass}>This is styled with CSS Modules!</div>;
}

useCallback Hook

The useCallback hook in React is used to memoize callback functions. It returns a memoized version of the callback that only changes if one of the dependencies has changed. This is useful to optimize performance, particularly when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

Basic Usage


import React, { useState, useCallback } from 'react';

export default function ExampleComponent() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []); // Empty array means the callback never changes

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={increment}>Click me</button>
    </div>
  );
}

When to Use useCallback

Prevent Re-creation of Functions: Use useCallback to prevent re-creation of functions on every render.

Optimized Child Components: Use useCallback when passing functions to memoized child components (React.memo) to prevent unnecessary re-renders.

Memoized Callback for Child Components


import React, { useState, useCallback } from 'react';

const ChildComponent = React.memo(({ onClick }) => {
  console.log('ChildComponent rendered');
  return <button onClick={onClick}>Click me</button>;
});

export default function ParentComponent() {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []); // Empty array means the callback never changes

  return (
    <div>
      <p>Count: {count}</p>
      <ChildComponent onClick={handleClick} />
    </div>
  );
}

useMemo Hook

The useMemo hook in React is used to memoize the result of a function. This helps optimize performance by caching the result of an expensive computation and reusing it when the inputs (dependencies) haven’t changed.

useMemo is particularly useful when the computation is complex or when it prevents unnecessary re-rendering of child components.

Syntax:


useMemo(() => computeValue, [dependencies])

Basic Usage

useMemo takes two arguments: a function that returns the computed value and an array of dependencies.


import React, { useState, useMemo } from 'react';

export default function ExampleComponent({ items }) {
  const [filter, setFilter] = useState('');
 
  const filteredItems = useMemo(() => {
    return items.filter(item => item.includes(filter));
  }, [items, filter]);

  return (
    <div>
      <input
        type="text"
        value={filter}
        onChange={(e) => setFilter(e.target.value)}
        placeholder="Filter items"
      />
      <ul>
        {filteredItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

When to Use useMemo

Expensive Computations: Use useMemo to memoize results of expensive computations that should only re-run when dependencies change.

Avoid Re-rendering: Use useMemo to prevent unnecessary re-renders of child components by memoizing data or calculations passed as props.

Avoid Re-rendering of Child Components


import React, { useState, useMemo } from 'react';

function ChildComponent({ data }) {
  console.log('ChildComponent rendered');
  return <div>{data}</div>;
}

const MemoizedChild = React.memo(ChildComponent);

export default function ParentComponent() {
  const [count, setCount] = useState(0);

  const data = useMemo(() => {
    return `Count is ${count}`;
  }, [count]);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <MemoizedChild data={data} />
    </div>
  );
}



useEffect Hook

The useEffect hook in React allows you to perform side effects in function components. It is the combination of componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods from class components. Side effects can include data fetching, subscriptions, or manually changing the DOM.

Basic Usage

The useEffect hook takes a function as its first argument and an optional dependency array as its second argument.


import React, { useState, useEffect } from 'react';

export default function ExampleComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]); // Only re-run the effect if count changes

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Dependencies

The dependency array tells React when to re-run the effect. If it’s empty ([]), the effect runs only once after the initial render.


useEffect(() => {
  // Effect logic here
}, []); // This effect runs only once

Data Fetching

You can use useEffect to fetch data from an API when the component mounts.


import React, { useState, useEffect } from 'react';

export default function DataFetchingComponent() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then((response) => response.json())
      .then((data) => {
        setData(data);
        setLoading(false);
      });
  }, []); // Empty array means this effect runs once

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Data:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

Effect Dependencies

The dependency array is crucial for optimizing performance and avoiding unnecessary effect runs. If any value in the dependency array changes, the effect will run again.


import React, { useState, useEffect } from 'react';

export default function DependencyComponent({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch(`https://api.example.com/users/${userId}`)
      .then((response) => response.json())
      .then((data) => setUser(data));
  }, [userId]); // Effect re-runs whenever userId changes

  if (!user) {
     return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
    </div>
  );
}

useState hook

The useState hook in React is a powerful feature that allows you to add state to functional components. It lets you manage state variables within your function components without needing to convert them into class components.

Basic Usage

The useState hook returns an array containing the current state and a function to update that state.


import React, { useState } from 'react';

export default function Counter() {
  // Declare a state variable named "count" and a function "setCount" to update it
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Initial State

The argument passed to useState is the initial state value. It can be any type, including objects, arrays, or even other hooks.


import React, { useState } from 'react';

export default function UserProfile() {
  const [user, setUser] = useState({ name: 'John', age: 30 });

  const updateName = () => {
    setUser({ ...user, name: 'Jane' });
  };

  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <button onClick={updateName}>Change Name</button>
    </div>
  );
}

Updating State

The state updating function (setState) can take the new state value directly or a function that receives the current state and returns the new state.


import React, { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Functional State Update

Using a function to update state is useful when the new state depends on the previous state.


import React, { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>Click me</button>
    </div>
  );
}

Using Multiple State Variables

You can use multiple useState hooks to manage different state variables.


import React, { useState } from 'react';

export default function MultiStateComponent() {
  const [name, setName] = useState('John');
  const [age, setAge] = useState(30);

  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <button onClick={() => setName('Jane')}>Change Name</button>
      <button onClick={() => setAge(35)}>Change Age</button>
    </div>
  );
}

React Form

React Form allow for handling user input and managing form submission. React provides controlled and uncontrolled components for handling forms.

1. Controlled Components

In controlled components, form data is handled by the component’s state.

Functional Components with Hooks


import React, { useState } from 'react';

export default function MyForm() {
  const [name, setName] = useState('');
  const [age, setAge] = useState('');

  const handleNameChange = (event) => {
    setName(event.target.value);
  };

  const handleAgeChange = (event) => {
    setAge(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Name: ${name}, Age: ${age}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={handleNameChange} />
      </label>
      <br />
      <label>
        Age:
        <input type="number" value={age} onChange={handleAgeChange} />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
}

2. Uncontrolled Components

In uncontrolled components, form data is handled by the DOM itself.

Using ref in Functional Components


import React, { useRef } from 'react';

export default function MyForm() {
  const nameRef = useRef(null);
  const ageRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Name: ${nameRef.current.value}, Age: ${ageRef.current.value}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={nameRef} />
      </label>
      <br />
      <label>
        Age:
        <input type="number" ref={ageRef} />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
}

Handling Form Validation

Form validation can be added by checking the form data before submission.

Functional Components with Hooks


import React, { useState } from 'react';

export default function MyForm() {
  const [formState, setFormState] = useState({ name: '', age: '' });
  const [errors, setErrors] = useState({ name: '', age: '' });

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormState((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  const validateForm = () => {
    let valid = true;
    let errors = {};

    if (!formState.name) {
      valid = false;
      errors.name = 'Name is required';
    }

    if (!formState.age) {
      valid = false;
      errors.age = 'Age is required';
    } else if (isNaN(formState.age)) {
      valid = false;
      errors.age = 'Age must be a number';
    }

    setErrors(errors);
    return valid;
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    if (validateForm()) {
      alert(`Name: ${formState.name}, Age: ${formState.age}`);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" name="name" value={formState.name} onChange={handleChange} />
        {errors.name && <span>{errors.name}</span>}
      </label>
      <br />
      <label>
        Age:
        <input type="number" name="age" value={formState.age} onChange={handleChange} />
        {errors.age && <span>{errors.age}</span>}
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
}
create form through use react-hook-form library

install react-hook-form


npm install react-hook-form

create form through react-hook-form with validation


import React from 'react';
import { useForm } from 'react-hook-form';

export default function SignUp(){

    const {register,handleSubmit,formState: { errors }} = useForm();

    const signupSubmit = async (data) =>{
      console.log(data);
    }

    return(
        <div>
        <h1>Signup Form</h1>
        <form onSubmit={handleSubmit(signupSubmit)}>

        <div className='container'>

            <div className="row">
             FirstName:
             <input type="text" id="firstName" {...register('firstName',{required:{value:true,message:"First Name is required"},maxLength:{value:10, message:"First Name should be less than or equal to 10"}})} />
             {errors.firstName && <p className='alert alert-danger'>{errors.firstName?.message}</p> }
            </div>
            <div className="row my-2">
             LastName:
             <input type="text" id="lastName" {...register('lastName',{required:{value:true,message:"Last Name is required"},maxLength:{value:10, message:"Last Name should be less than or equal to 10"}})} />
             {errors.lastName && <p className='alert alert-danger'>{errors.lastName?.message}</p> }
            </div>
            <div><button className='btn btn-primary'>Submit</button></div>

        </div>
        </form>
        </div>
    )
}

Conditional rendering

Conditional rendering in React allows you to render different components or elements based on certain conditions. Here are some common ways to achieve conditional rendering in React:

Using if statements


//MyComponent.jsx
function MyComponent(props) {
  if (props.isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please sign up.</h1>;
  }
}

Using the ternary operator


//MyComponent.jsx
function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
   </div>
  );
}

Using logical && operator


//MyComponent.jsx
function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn && <h1>Welcome back!</h1>}
      {!props.isLoggedIn && <h1>Please sign up.</h1>}
    </div>
  );
}

Conditional rendering with switch statement


//MyComponent.jsx
function MyComponent(props) {
  switch (props.status) {
    case 'loading':
      return <div>Loading...</div>;
    case 'error':
      return <div>Error!</div>;
    case 'success':
      return <div>Data loaded successfully!</div>;
    default:
      return null;
  }
}

Using Component with conditional rendering

You can create separate components for different conditions and use them conditionally.


//welcome.jsx
function Welcome() {
  return <h1>Welcome back!</h1>;
}

//SignUp.jsx
function SignUp() {
  return <h1>Please sign up.</h1>;
}

//MyComponent.jsx
function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn ? <Welcome /> : <SignUp />}
    </div>
  );
}

React Router

React Router is a popular library for handling routing in React applications. It allows you to define routes in your application and navigate between different components or views without reloading the page.

Here’s a step-by-step example of how to set up and use React Router in a simple React application:

Install React Router:

First, you need to install React Router.


npm install react-router-dom

Create Components:

Next, create the components for Home, About, and Contact.


//home.jsx
import React from 'react';

function Home() {
  return <h2>Home</h2>;
}

Now, create the About.jsx component


// src/components/About.jsx
import React from 'react';

function About() {
  return <h2>About</h2>;
}

export default About;

Now, create the Contact.jsx component


// src/components/Contact.jsx
import React from 'react';

function Contact() {
  return <h2>Contact</h2>;
}

export default Contact;

Set up the Router:

In your src directory, create a new file headerMenu.jsx (if it doesn’t already exist) and set up the router.


import React from "react";
import {Link} from 'react-router-dom';
export default function HeaderMenu(){

    return (
    <>
    <nav className="navbar navbar-expand-lg bg-primary">
  <div className="container-fluid">
 
    <div className="collapse navbar-collapse" id="navbarSupportedContent">
      <ul className="navbar-nav me-auto mb-2 mb-lg-0">
        <li className="nav-item ">
          <Link className="nav-link active  text-light" aria-current="page" to="/">Home</Link>
        </li>
        <li className="nav-item">
          <Link className="nav-link text-light" to="/about-us">AboutUs</Link>
        </li>
        <li className="nav-item">
          <Link className="nav-link text-light" to="/contact-us">ContactUs</Link>
        </li>
      </ul>
      
    </div>
  </div>
</nav>
</>
    )

}

In the above example, we use Link instead of anchor (a) tag and we use to instead of href.

create Router.Example.jsx


import React from "react";
import HeaderMenu from "./HeaderMenu";
import {BrowserRouter,Routes,Route} from 'react-router-dom'
import Aboutus from "./About";
import ContactUs from "./Contact";
import Home from "./Home";

export default function RoutingExample(){

    return (
        <>
        <BrowserRouter>
        <HeaderMenu/>
        <Routes>
           <Route path="/" element={<Home/>}></Route>
            <Route path="/about-us" element={<Aboutus/>}></Route>
            <Route path="/contact-us" element={<ContactUs/>}></Route>
        </Routes>
        </BrowserRouter>
        
        </>
    )

}

This simple example demonstrates the basic usage of React Router. Here’s a brief explanation of the key parts:

BrowserRouter (aliased as Router): Wraps your application and enables routing.

Link: Used to create navigation links.

Switch: Renders the first child <Route> that matches the location.

Route: Defines a route and the component to render when the route matches.

What is List and keys

lists and keys are essential concepts for efficiently rendering and managing collections of elements. They help React identify which items have changed, been added, or been removed, making it possible to optimize rendering.

Lists

Lists in React are used to render multiple items dynamically. Typically, you’ll map over an array of data to create a list of elements.

Step1:- create NumberList.jsx file


import React from 'react';

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    
  • {number}
  • ); return ( <ul>{listItems}</ul> ); }

    Step2:- create App.jsx file and include NumberList component

    
    import React from 'react';
    const numbers = [1, 2, 3, 4, 5];
    function App() {
      return <NumberList numbers={numbers} />;
    }
    export default App;
    

    In this example:

    1. numbers.map((number) => <li key={number.toString()}>{number}</li>) is used to transform the array of numbers into an array of list items (<li> elements).
    2. Each item in the array is rendered as an <li> element.

    Keys

    Keys help React identify which items have changed, been added, or been removed. They are crucial for dynamic lists where items can be reordered, inserted, or deleted.

    Why Keys are Important

    Keys should be given to the elements inside the array to give them a stable identity:

    Performance Optimization: Helps React update the UI more efficiently by minimizing the number of DOM manipulations.

    Consistency: Ensures that elements are re-used and not unnecessarily recreated, which is particularly important when dealing with complex components.

    Best Practices for Keys

    Use Unique Identifiers: If your data has a unique identifier, use it as the key.

    Avoid Using Index as Key: Using array indexes as keys can lead to issues with component state and reordering. It’s usually better to use stable, unique identifiers.

    Step1:- create TodoList.jsx file

    
    //TodoList.jsx
    import React from 'react';
    
    const todos = [
      { id: 1, text: 'Learn React' },
      { id: 2, text: 'Build a React App' },
      { id: 3, text: 'Deploy the App' }
    ];
    
    function TodoList() {
      const listItems = todos.map((todo) =>
        <li key={todo.id}>{todo.text}</li>
      );
      return (
        <ul>{listItems}</ul>
      );
    }
    

    Step2:- create App.jsx file and include TodoList component

    
    //App.jsx
    function App() {
      return <TodoList />;
    }
    
    export default App;
    

    In this example, each todo item has a unique id which is used as the key.

    React Hooks

    In React, a hook is a special function that allows you to use state and other React features in functional components. Prior to hooks, state and lifecycle methods were only available in class components. Hooks were introduced in React 16.8 to allow functional components to manage state and side effects, making them more powerful and flexible.

    Basic Concepts of Hooks

    State Hook (useState): Allows you to add state to functional components.

    Effect Hook (useEffect): Lets you perform side effects in function components.

    Context Hook (useContext): Lets you use context to pass data through the component tree without having to pass props down manually at every level.

    Rules of Hooks

    1. Only call hooks at the top level: Don’t call hooks inside loops, conditions, or nested functions. This ensures hooks are called in the same order each time a component renders.
    2. Only call hooks from React functions: Call them from within React functional components or custom hooks, not regular JavaScript functions.

    Benefits of Hooks

    1. Simpler Code: Functional components with hooks are generally simpler and easier to read than class components.
    2. Reusability: Hooks allow you to reuse stateful logic across multiple components.
    3. Better Organization: Hooks let you split one component into smaller functions based on what pieces are related (e.g., setting up a subscription or fetching data).

    Basic Hooks

    useState

    The useState hook lets you add state to a functional component. It returns an array with two elements: the current state value and a function to update it.

    
    import React, { useState } from 'react';
    
    function Counter() {
      const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
      );
    }
    
    export default Counter;
    
    

    useEffect

    The useEffect hook lets you perform side effects in function components. It’s similar to lifecycle methods in class components (componentDidMount, componentDidUpdate, componentWillUnmount).

    
    import React, { useState, useEffect } from 'react';
    
    function Example() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        // Update the count
         console.log(`You clicked ${count} times`);
      }, [count]); // Only re-run the effect if count changes
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
      );
    }
    
    export default Example;
    

    useContext

    The useContext hook in React allows you to consume context in a functional component without needing to wrap your component in a Consumer component. This makes the code more concise and easier to read. Context provides a way to pass data through the component tree without having to pass props down manually at every level.

    Creating and Using Context

    1. Create a Context: Use the createContext function to create a context.
    2. Provide a Context Value: Use a Provider component to pass the context value to the tree.
    3. Consume Context: Use the useContext hook to consume the context value in a functional component.

    Step-by-Step Example

    Step 1: Create a Context

    First, create a context using the createContext function.

    
    import { createContext } from 'react';
    
    // Create a context with 'light' as the default value
    const ThemeContext = createContext('light');
    
    export { ThemeContext };
    

    Step 2: Provide a Context Value

    Wrap your component tree with a Provider component and pass the context value.

    
    //index.js
    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    import { ThemeContext } from './ThemeContext';
    
    ReactDOM.render(
      <ThemeContext.Provider value="dark">
        <App />
      </ThemeContext.Provider>,
      document.getElementById('root')
    );
    
    

    Step 3: Consume Context

    Use the useContext hook to consume the context value in a functional component.

    
    //ThemedButton.jsx
    import React, { useContext } from 'react';
    import { ThemeContext } from './ThemeContext';
    
    function ThemedButton() {
      const theme = useContext(ThemeContext);
      return <button style={{ background: theme === 'dark' ? '#333' : '#fff' }}>Themed Button</button>;
    }
    
    export default ThemedButton;
    
    

    App.jsx

    
    import React from 'react';
    import ThemedButton from './ThemedButton';
    
    function App() {
      return (
        <div>
          <ThemedButton />
        </div>
      );
    }
    
    export default App;
    
    

    Lifting state up

    Lifting state up is a common pattern in React for sharing state between multiple components. When several components need to reflect the same changing data, it is recommended to lift the shared state up to their closest common ancestor. This allows you to manage state in one place and pass it down as props to the components that need it.

    Here’s a step-by-step guide on how to lift state up in React:

    Identify the common ancestor: Determine the closest common ancestor component that needs to manage the shared state.

    Move the state to the common ancestor: Declare the state in the common ancestor component.

    Pass the state down as props: Pass the state from the common ancestor to the child components that need it.

    Pass the state updater function down as props: If child components need to update the state, pass the state updating function down to them as props.

    Example: Simple Input and Display

    Let’s create a simple React application where an input component updates a message, and the message is displayed in another component.

    Step 1: Create the Common Ancestor Component

    Let’s start by creating the common ancestor component, App, which will hold the state.

    
    import React, { useState } from 'react';
    import MessageInput from './MessageInput';
    import DisplayMessage from './DisplayMessage';
    
    function App() {
      const [message, setMessage] = useState('');
    
      return (
        <div>
          <MessageInput message={message} onMessageChange={setMessage} />
          <DisplayMessage message={message} />
        </div>
      );
    }
    
    export default App;
    
    

    Step 2: Create the Input Component

    The MessageInput component will receive the message and the state updater function as props.

    
    import React from 'react';
    
    function MessageInput({ message, onMessageChange }) {
      const handleChange = (e) => {
        onMessageChange(e.target.value);
      };
    
      return (
        <div>
          <input type="text" value={message} onChange={handleChange} placeholder="Type a message" />
        </div>
      );
    }
    
    export default MessageInput;
    
    

    Step 3: Create the Display Component

    The DisplayMessage component will receive the message as a prop and display it.

    
    import React from 'react';
    
    function DisplayMessage({ message }) {
      return (
        <div>
          <p>{message}</p>
        </div>
      );
    }
    
    export default DisplayMessage;
    

    Work Process:

    1. The App component holds the state for the message.
    2. The MessageInput component receives the current message and a function to update it as props. When the input value changes, it calls the onMessageChange function, which updates the state in the App component.
    3. The DisplayMessage component receives the current message as a prop and displays it.

    By lifting the state up to the App component, both MessageInput and DisplayMessage can share the same state and remain synchronized.

    What is state

    In React, state refers to a built-in object that holds data or information about the component. It is used to create dynamic and interactive components by enabling React to keep track of the changes in the component’s data over time. When the state of a component changes, React re-renders the component to reflect the new state, ensuring the UI is always up to date.

    Key Characteristics of State:

    Mutable: state is mutable and can be changed by the component itself while props, which are read-only.

    Private: State is local to the component where it is defined and cannot be accessed or modified directly by other components.

    Triggers Re-render: When state changes, React automatically re-renders the component to reflect the updated state.

    Managing State in Functional Components:

    With the introduction of React Hooks in version 16.8, functional components can now use state through the useState hook.

    
    import React, { useState } from 'react';
    
    function Counter() {
      // Declare a state variable named "count" with an initial value of 0
      const [count, setCount] = useState(0);
    
      // Function to increment the count
      const increment = () => {
        setCount(count + 1);
      };
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={increment}>Click me</button>
        </div>
      );
    }
    export default Counter;
    

    Explanation:

    useState Hook:

    The useState hook is used to declare a state variable. It takes an initial state value as an argument and returns an array with two elements:

    1. The current state value (count).
    2. A function to update the state (setCount).

    State Initialization:

    const [count, setCount] = useState(0); initializes the state variable count with an initial value of 0.

    Updating State:

    The increment function updates the state by calling setCount(count + 1). This triggers a re-render of the component with the new state value.

    Rendering the Component:

    The component renders a div containing a paragraph that displays the current count and a button that increments the count when clicked.

    Managing State in Class Components:

    Before hooks, class components were the primary way to manage state in React. State is managed through the this.state object and updated using the this.setState method.

    
    import React, { Component } from 'react';
    
    class Counter extends Component {
      constructor() {
        super();
        // Initialize state
        this.state = { count: 0 };
    
      }
    
      // Method to update state
      increment() {
        this.setState({count:this.state.count+1})
      }
    
      render() {
        return (
          <div>
            <p>You clicked {this.state.count} times</p>
            <button onClick={this.increment}>Click me</button>
          </div>
        );
      }
    }
    
    export default Counter;
    
    

    Explanation:

    State Initialization:

    State is initialized in the constructor using this.state = { count: 0 };.

    Updating State:

    The increment method updates the state using this.setState, which triggers a re-render.

    Rendering the Component:

    The render method returns JSX that renders the current state and a button to update the state.

    What is jsx

    JSX (JavaScript XML) is a syntax extension for JavaScript, commonly used with React to describe what the UI should look like. It allows you to write HTML structures within JavaScript code, making the code more readable and expressive. Here’s an overview of JSX in the context of React:

    Key Features of JSX:

    HTML-like Syntax: JSX allows you to write HTML-like code directly within JavaScript files. For example:

    
    const element = 

    Hello, world!

    ;

    This code creates a React element that represents an <h1> element with the text “Hello, world!”.

    Embedded Expressions: You can embed JavaScript expressions within JSX using curly braces {}. For example:

    
    const name = 'John';
    const element = 

    Hello, {name}!

    ;

    This will render as <h1>Hello, John!</h1>.

    Components: JSX is often used to define React components. Components can be functions or classes that return JSX:

    
    function Welcome(props) {
      return 

    Hello, {props.name}

    ; }

    This function component takes a name prop and renders it within an <h1> element.

    Attributes: You can use attributes in JSX similarly to HTML. However, in JSX, attribute names follow camelCase convention instead of kebab-case. For example:

    
    const element = <img src="logo.png" className="logo" alt="Logo" />;
    

    In this example, we use className attribute instead of class in jsx file in Reactjs.

    Example2:

    
    <h1 style={{color:"white", backgroundColor:"red"}}>Hello Css Example</h1>
    

    In this example, we use style attribute has backgroundColor property in a camelCase in jsx in Reactjs.

    How JSX Works:

    JSX is not valid JavaScript by itself. Browsers cannot read it directly. Therefore, it needs to be transpiled to regular JavaScript using tools like Babel. During the build process, Babel transforms JSX into React.createElement() calls:

    
    const element = <h1>Hello, world!</h1>;
    // Transpiles to:
    const element = React.createElement('h1', null, 'Hello, world!');
    

    Advantages of JSX:

    Readability: JSX makes the structure of the component more understandable and similar to HTML, making it easier to visualize the UI structure.

    Integration: Embedding JavaScript expressions directly within the markup allows for dynamic content rendering and complex UI interactions.

    Componentization: JSX promotes the creation of reusable UI components.

    Class Component

    Class components in React.js are ES6 classes that extend from React.Component and must contain a render method that returns JSX. Here’s a step-by-step guide to creating and using class components in React:

    Creating a Class Component

    A class component is a JavaScript class that extends React.Component and includes a render method.

    Create the Component File: Create a new file for your component, e.g., MyComponent.js.

    
    // src/MyComponent.jsx
    import React, { Component } from 'react';
    class MyComponent extends Component {
      render() {
        return (
          <div>
            <h1>Hello, world!</h1>
          </div>
        );
      }
    }
    export default MyComponent;
    

    Using the Component: Import and use this component in your main application file, e.g., App.js.

    
    // src/App.jsx
    import React, { Component } from 'react';
    import MyComponent from './MyComponent';
    
    class App extends Component {
      render() {
        return (
          <div>
            <MyComponent />
          </div>
        );
      }
    }
    export default App;
    

    Output will be:- Hello, World!

    Adding Props to a Class Component

    Props are used to pass data from parent to child components.

    Modify the Component to Accept Props:

    
    // src/MyComponent.jsx
    import React, { Component } from 'react';
    
    class MyComponent extends Component {
      render() {
        return (
          <div>
            <h1>Hello, {this.props.name}!</h1>
          </div>
        );
      }
    }
    export default MyComponent;
    
    

    Pass Props to the Component:

    
    // src/App.jsx
    import React, { Component } from 'react';
    import MyComponent from './MyComponent';
    
    class App extends Component {
      render() {
        return (
          <div>
            <MyComponent name="World" />
          </div>
        );
      }
    }
    export default App;
    
    

    Output will be:- Hello, World!

    Function Component

    Function components in React.js are a way to create components using JavaScript functions. These components are simpler than class components and are often easier to read and test. Here’s a step-by-step guide to creating and using function components in React:

    Creating a Function Component

    A function component is a JavaScript function that returns a React element.

    Create the Component File: Create a new file for your component, e.g., MyComponent.js.

    
    // src/MyComponent.jsx
    import React from 'react';
    
    const MyComponent = () => {
      return (
        <div>
          <h1>Hello, world!</h1>
        </div>
      );
    };
    
    export default MyComponent;
    
    

    Using the Component: Import and use this component in your main application file, e.g., App.js.

    
    // src/App.jsx
    import React from 'react';
    import MyComponent from './MyComponent';
    
    const App = () => {
      return (
        <div>
          <MyComponent />
        </div>
      );
    };
    
    export default App;
    

    Output will be: Hello, World!

    Adding Props to a Function Component

    Props are used to pass data from parent to child components.

    Modify the Component to Accept Props:

    
    // src/MyComponent.jsx
    import React from 'react';
    
    const MyComponent = (props) => {
      return (
        <div>
          <h1>Hello, {props.name}!</h1>
        </div>
      );
    };
    
    export default MyComponent;
    
    

    Pass Props to the Component:

    
    // src/App.jsx
    import React from 'react';
    import MyComponent from './MyComponent';
    
    const App = () => {
      return (
        <div>
          <MyComponent name="World" />
        </div>
      );
    };
    
    export default App;
    

    Output will be: Hello, World!

    React Component

    React components are the fundamental building blocks of a React application. They encapsulate parts of the user interface, making it easy to create complex UIs from smaller, isolated pieces of code. Components can be either functional or class-based, and they can manage their own state and lifecycle methods. Here’s an in-depth look at React components:

    Types of Components

    1. Functional Components
    2. Class Components

    Functional Components

    Functional components are simpler and are typically used for components that don’t need to manage state or lifecycle methods. They are just JavaScript functions that accept props as an argument and return React elements.

    Example of a functional component:

    
    //src/MyComponent.js
    import React from 'react';
    
    function Welcome() {
      return 

    Hello World!

    ; } export default Welcome;

    In this example, Welcome is a functional component and returns a React element.

    Class Components

    Class components are more feature-rich. They allow you to use additional features like local state and lifecycle methods. Class components extend React.Component.

    Example of a class component:

    
    src/Greetings.js
    import React, { Component } from 'react';
    
    class Greetings extends React.Component {
      render() {
        return 

    Hello World!

    ; } } export default Greetings;

    In this example, Greetings is a class component that renders the same output as the functional component.

    Rendering a component

    Rendering a component in React.js involves creating a component and then rendering it in the DOM.

    Import and use the component in your main application file (src/App.js).

    Rendering a function component
    
    // src/App.js
    import React from 'react';
    import MyComponent from './MyComponent';
    
    const App = () => {
      return (
        <div>
           <MyComponent />
         </div>
      );
    };
    
    export default App;
    

    In this example, output will be Hello World!

    Rendering a class component

    It will be same as a function component

    
    // src/App.js
    import React from 'react';
    import Greetings from './Greetings';
    
    const App = () => {
      return (
        <div>
          <Greetings />
        </div>
      );
    };
    
    export default App;
    

    In this example, output will be Hello World!

    How to install Reactjs

    To install React.js, you need to set up your development environment. Here’s a step-by-step guide to getting started:

    Prerequisites

    Node.js and npm: React.js requires Node.js and npm (Node Package Manager) to be installed on your machine. You can download and install Node.js from nodejs.org.

    Step-by-Step Installation

    Install Node.js and npm

    Download the installer for your operating system from nodejs.org and follow the installation instructions. This will install both Node.js and npm.

    Create a New React Application

    The easiest way to create a new React application is by using the Create React App CLI tool. This tool sets up a new React project with a sensible default configuration.

    1. Open your terminal or command prompt.
    2. Run the following command to install Create React App globally:
    
    npm install -g create-react-app
    

    After the installation is complete, create a new React application by running:

    
    npx create-react-app my-app
    

    Replace my-app with the name of your project.

    Navigate to your project directory:

    
    cd my-app
    

    Start the development server:

    
    npm start
    

    Your new React app should now be running on http://localhost:3000. The development server will automatically reload the page if you make edits to your code.

    Project Structure

    After creating your React application, the project directory will look something like this:

    
    my-app
    ├── README.md
    ├── node_modules
    ├── package.json
    ├── public
    │   ├── favicon.ico
    │   ├── index.html
    │   └── ...
    ├── src
    │   ├── App.css
    │   ├── App.js
    │   ├── App.test.js
    │   ├── index.css
    │   ├── index.js
    │   └── ...
    
    

    public: This folder contains the public assets of your application. The main file here is index.html, which serves as the entry point for your app.

    src: This folder contains the source code of your application. The main files to note here are index.js and App.js.

    What is Reactjs

    React (also known as React.js or ReactJS) is a JavaScript library developed by Facebook for building user interfaces, specifically single-page applications where a fast, interactive user experience is crucial. It allows developers to create large web applications that can update and render efficiently in response to data changes.

    Key Features of React

    1) Component-Based Architecture:
    Components: The building blocks of a React application. A component can be a function or a class, and it typically returns a React element (JSX) that describes how a section of the UI should appear

    Reusable: Components can be reused across the application, making code more modular and maintainable.

    2) JSX (JavaScript XML):

    Syntax Extension: JSX is a syntax extension for JavaScript that looks similar to XML or HTML. It allows developers to write UI components using a syntax that closely resembles HTML, making it easier to understand and maintain the structure of the UI.

    Transformation: JSX is transformed into JavaScript at runtime.

    3) Virtual DOM:

    Efficiency: React uses a virtual DOM to improve performance. Instead of manipulating the browser’s DOM directly, React creates a virtual DOM and updates it in response to changes. It then compares the virtual DOM with the real DOM (using a process called “reconciliation”) and updates only the parts of the DOM that have changed.

    Performance: This approach minimizes the number of direct DOM manipulations, which are typically slow, thereby enhancing the performance of the application.

    4) One-Way Data Binding:

    Unidirectional Data Flow: React enforces a one-way data flow where data flows from parent components to child components via props. This makes it easier to understand and debug the state of an application.

    5) State Management:

    State: React components can maintain local state, which allows them to manage data that changes over time. When the state of a component changes, React automatically re-renders the component and its children to reflect the new state.

    State Management Libraries: For larger applications, state management libraries like Redux, MobX, or the Context API can be used to manage complex state interactions.

    6) Lifecycle Methods:

    Class Components: React provides lifecycle methods for class components, which allow developers to execute code at specific points in a component’s life (e.g., mounting, updating, unmounting).

    Hooks: In functional components, React hooks (like useEffect) provide similar functionality, allowing developers to perform side effects in function components.

    7) React Hooks:

    State and Lifecycle: Hooks like useState and useEffect allow functional components to use state and other React features without writing class components.

    Custom Hooks: Developers can create custom hooks to encapsulate reusable logic.

    Advantages of Using React

    Declarative: React makes it easier to design interactive UIs. Developers can design views for each state in their application, and React will update and render the right components when the data changes.

    Component-Based: The ability to build encapsulated components that manage their own state, then compose them to make complex UIs.

    Efficient Updates: The virtual DOM ensures minimal updates to the actual DOM, leading to improved performance.

    Ecosystem: A vast ecosystem of libraries and tools, including React Router for navigation, Redux for state management, and many more.

    Use Cases

    React is commonly used for:

    Single-Page Applications (SPAs): Where the goal is to create a seamless user experience with fast, interactive UIs.

    Mobile Applications: With React Native, which allows developers to build native mobile apps using React.

    Web Applications: Any web application requiring a dynamic, high-performing user interface.

    Type assertions

    Type assertions in TypeScript are a way to tell the compiler explicitly that you know the type of a variable better than it does. They are used when you have more information about the type of a value than TypeScript’s type checker is able to infer. Type assertions do not perform any runtime checks or conversions; they simply inform the compiler of the assumed type.

    Syntax

    Type assertions can be done in two ways:

    Angle-bracket syntax:

    
    let someValue: any = "this is a string";
    let strLength: number = (someValue).length;
    

    as syntax:

    
    let someValue: any = "this is a string";
    let strLength: number = (someValue as string).length;
    

    Examples

    Example 1: Narrowing a type

    Consider a scenario where you know a variable is of a more specific type than what TypeScript infers:

    
    let someValue: any = "this is a string";
    let strLength: number = (someValue as string).length;
    
    console.log(strLength); // Outputs: 16
    

    Here, TypeScript would not know the exact type of someValue, but you, as the developer, know it’s a string. The type assertion someValue as string informs the compiler about this knowledge.

    Example 2: Working with DOM elements

    When working with the DOM, TypeScript often cannot infer the exact type of an element, especially when using methods like document.getElementById.

    
    let inputElement = document.getElementById("input") as HTMLInputElement;
    inputElement.value = "Hello, world!";
    

    Without the type assertion, document.getElementById would return HTMLElement | null, and TypeScript would not know about the value property of HTMLInputElement.

    Type Assertions vs Type Casting

    Type assertions in TypeScript do not perform any runtime checks or type conversions. They purely tell the compiler to treat a value as a specific type, which is different from type casting in other languages that convert the type at runtime.

    For example, in TypeScript:

    
    let someValue: any = "this is a string";
    let strLength: number = (someValue).length; // Type assertion
    

    In contrast, in languages like C# or Java, type casting may involve actual runtime type conversion.

    Type Assertions with Union Types

    When dealing with union types, type assertions can help specify the exact type you are working with.

    
    function getLength(value: string | number): number {
      if ((value as string).length !== undefined) {
        return (value as string).length;
      } else {
        return value.toString().length;
      }
    }
    
    console.log(getLength("Hello")); // Outputs: 5
    console.log(getLength(12345));   // Outputs: 5
    
    

    What is any type

    In TypeScript, the any type is a type that can hold any value. It acts as a way to opt-out of type checking and allow a variable to have any type of value. Using any gives you the flexibility of JavaScript’s dynamic typing but at the expense of losing the benefits of TypeScript’s static type checking.

    When to Use any

    The any type can be useful in several scenarios:

    Migrating from JavaScript to TypeScript: When gradually migrating a JavaScript codebase to TypeScript, any can be used to allow existing code to function without requiring complete type annotations.

    Dynamic content: When dealing with data from dynamic content like third-party libraries, user inputs, or JSON responses where the structure is not known at compile time.

    Prototyping: During the early stages of development or prototyping where the exact types are not yet defined.

    Defining and Using any

    Example

    
    let looselyTyped: any = 4;
    looselyTyped = "Now it's a string";
    looselyTyped = true; // Now it's a boolean
    
    function logMessage(message: any): void {
      console.log(message);
    }
    
    logMessage("Hello, world!");  // Outputs: Hello, world!
    logMessage(123);              // Outputs: 123
    logMessage({ key: "value" }); // Outputs: { key: 'value' }
    
    

    In the example above, the variable looselyTyped can hold any value, and the function logMessage can accept an argument of any type.

    Accessing Properties on any

    When using any, you can access properties and methods that might not exist without causing a type error. This can be useful but also risky, as it might lead to runtime errors.

    
    let obj: any = { x: 0 };
    console.log(obj.x); // Outputs: 0
    console.log(obj.y); // No error, but `y` is undefined
    obj.foo();          // No compile error, but runtime error if `foo` is not a function
    

    Losing Type Safety

    Using any can lead to losing the type safety that TypeScript provides. This means TypeScript will not help catch type-related errors at compile time.

    
    let someValue: any = "this is a string";
    let strLength: number = someValue.length; // OK
    let unknownValue: any = 4;
    console.log(unknownValue.toUpperCase()); // Runtime error: `toUpperCase` is not a function
    

    What is Enum

    In TypeScript, an enum (short for “enumeration”) is a way to define a set of named constants. Enums allow you to create a collection of related values that can be numeric or string-based. They are useful for representing a set of discrete values, such as days of the week, months of the year, or status codes.

    Types of Enums

    TypeScript supports two types of enums: numeric and string.

    Numeric Enums

    Numeric enums are the default type of enums in TypeScript. The first value in a numeric enum has a default value of 0, and each subsequent value is incremented by 1.

    
    enum Direction {
      Up,
      Down,
      Left,
      Right
    }
    
    let directionUp: Direction = Direction.Up;
    let directionRight: Direction = Direction.Right;
    console.log(directionUp); // Outputs: 0
    console.log(directionRight); // Outputs: 3
    

    You can also specify custom numeric values for the enum members:

    
    enum Direction {
      Up = 1,
      Down,
      Left = 5,
      Right
    }
    
    console.log(Direction.Up);    // Outputs: 1
    console.log(Direction.Down);  // Outputs: 2
    console.log(Direction.Left);  // Outputs: 5
    console.log(Direction.Right); // Outputs: 6
    
    

    String Enums

    String enums are enums where each member has a string value. They provide a clearer and more readable way to define enum values.

    
    enum Direction {
      Up = "UP",
      Down = "DOWN",
      Left = "LEFT",
      Right = "RIGHT"
    }
    
    let direction: Direction = Direction.Up;
    console.log(direction); // Outputs: "UP"
    
    

    Using enum in switch case

    Enums can be used to define and check for specific values within a set.

    
    enum Status {
      New,
      InProgress,
      Completed
    }
    
    function updateStatus(status: Status): void {
      switch (status) {
        case Status.New:
          console.log("Starting new task.");
          break;
        case Status.InProgress:
          console.log("Task is in progress.");
          break;
        case Status.Completed:
          console.log("Task is completed.");
          break;
      }
    }
    
    updateStatus(Status.InProgress); // Outputs: "Task is in progress."
    
    

    What is Tuple

    In TypeScript, a tuple is a typed array with a fixed number of elements whose types are known and can be different. Tuples allow you to express an array where the type of a fixed number of elements is known but need not be the same.

    Defining Tuples

    You define a tuple by specifying the types of its elements inside square brackets.

    Example:

    
    let tuple: [string, number];
    tuple = ["Hello", 42]; // OK
    // tuple = [42, "Hello"]; // Error: Type 'number' is not assignable to type 'string' and vice versa
    

    Accessing Tuple Elements

    You can access the elements of a tuple using array indexing.

    
    let tuple: [string, number];
    tuple = ["Hello", 42];
    
    console.log(tuple[0]); // Outputs: Hello
    console.log(tuple[1]); // Outputs: 42
    

    Tuple Operations

    Pushing to Tuples

    You can push new elements to a tuple, but it may lose the tuple type and become a regular array type.

    
    let tuple: [string, number];
    tuple = ["Hello", 42];
    
    tuple.push("World");
    console.log(tuple); // Outputs: ["Hello", 42, "World"]
    

    Destructuring Tuples

    You can destructure tuples just like arrays.

    
    let tuple: [string, number];
    tuple = ["Hello", 42];
    
    let [greeting, answer] = tuple;
    
    console.log(greeting); // Outputs: Hello
    console.log(answer);   // Outputs: 42
    

    Tuple Types with Optional Elements

    Tuples can also have optional elements.

    
    let tuple: [string, number?];
    tuple = ["Hello"];
    tuple = ["Hello", 42];
    
    console.log(tuple); // Outputs: ["Hello"] or ["Hello", 42]
    

    Tuple Rest Elements

    TypeScript 3.0 introduced support for rest elements in tuple types, which can represent a variable number of elements.

    
    let tuple: [string, ...number[]];
    tuple = ["Hello"];
    tuple = ["Hello", 40, 41, 42];
    
    console.log(tuple); // Outputs: ["Hello", 40, 41, 42]
    

    What is Modules

    Modules in TypeScript are a way to organize and encapsulate code into reusable and maintainable chunks. They allow you to split your code into separate files and then import/export functionalities between them. This makes the code easier to manage, especially in large projects. Here’s a detailed overview of how to work with modules in TypeScript:

    Creating and Exporting Modules

    In TypeScript, you can create a module by simply writing some code in a .ts file and exporting what you want to be accessible from other modules.

    Named Exports

    Named exports allow you to export multiple bindings from a module. Each export must be explicitly named.

    
    // math.ts
    export function add(a: number, b: number): number {
      return a + b;
    }
    
    export function subtract(a: number, b: number): number {
      return a - b;
    }
    
    

    Default Exports

    A default export can be a function, class, object, or anything else. There can only be one default export per module.

    
    // logger.ts
    export default function log(message: string): void {
      console.log(message);
    }
    

    Importing Modules

    You can import modules using the import statement.

    Importing Named Exports

    To import named exports, you use curly braces to specify the names of the exports you want to import.

    
    // app.ts
    import { add, subtract } from './math';
    
    console.log(add(5, 3));  // Outputs: 8
    console.log(subtract(5, 3));  // Outputs: 2
    
    

    Importing Default Exports

    To import a default export, you don’t use curly braces.

    
    // app.ts
    import log from './logger';
    
    log('Hello, world!');  // Outputs: Hello, world!
    
    

    Aliases

    You can use aliases when importing to avoid name conflicts or to make names clearer.

    
    // app.ts
    import { add as addition, subtract as subtraction } from './math';
    
    console.log(addition(5, 3));  // Outputs: 8
    console.log(subtraction(5, 3));  // Outputs: 2
    
    

    Re-exporting Modules

    You can re-export modules, which is useful for creating a single entry point for multiple modules.

    
    // index.ts
    export { add, subtract } from './math';
    export { default as log } from './logger';
    

    Now you can import everything from index.ts instead of importing from individual modules.

    
    // app.ts
    import { add, subtract, log } from './index';
    
    console.log(add(5, 3));  // Outputs: 8
    console.log(subtract(5, 3));  // Outputs: 2
    log('Hello, world!');  // Outputs: Hello, world!
    

    Generics

    Generics in TypeScript provide a way to create reusable components that can work with any data type. They allow you to define functions, classes, and interfaces that work with types specified by the caller, ensuring type safety while providing the flexibility to use different types as needed.

    Key Concepts of Generics

    Type Variables Generics use type variables to denote types that are specified when the generic is instantiated. The most commonly used type variable is T.

    Generic Functions Functions can be made generic to operate on a variety of types while maintaining type safety.

    Generic Classes Classes can be defined with generics to handle different types of data in a type-safe manner.

    Generic Interfaces Interfaces can use generics to define structures that can work with multiple types.

    Generic Functions

    A generic function can accept arguments of any type and return a value of that same type.

    Example

    
    function identity<T>(arg: T): T {
        return arg;
    }
    
    let output1 = identity<string>("myString"); // Explicit type
    let output2 = identity<number>(100); // Explicit type
    let output3 = identity("myString"); // Type inference
    

    Generic Classes

    A generic class can operate on various data types while ensuring type safety.

    Example

    
    class GenericNumber<T> {
        zeroValue: T;
        add: (x: T, y: T) => T;
    
        constructor(zeroValue: T, addFn: (x: T, y: T) => T) {
            this.zeroValue = zeroValue;
            this.add = addFn;
        }
    }
    
    let myGenericNumber = new GenericNumber<number>(0, (x, y) => x + y);
    console.log(myGenericNumber.add(5, 10)); // Output: 15
    
    

    Generic Interfaces

    Interfaces can use generics to describe a structure that can work with multiple types.

    Example

    
    interface GenericIdentityFn<T> {
        (arg: T): T;
    }
    
    function identity<T>(arg: T): T {
        return arg;
    }
    
    let myIdentity: GenericIdentityFn<number> = identity;
    console.log(myIdentity(5)); // Output: 5
    
    

    Using Multiple Type Variables

    Generics can use multiple type variables to create more complex and flexible components.

    Example

    
    function merge<T, U>(obj1: T, obj2: U): T & U {
        return { ...obj1, ...obj2 };
    }
    
    let mergedObj = merge({ name: "Alice" }, { age: 25 });
    console.log(mergedObj); // Output: { name: "Alice", age: 25 }
    
    

    Generic Constraints

    Sometimes you want to limit the kinds of types that can be passed as type arguments. You can use constraints to achieve this.

    Example

    
    interface Lengthwise {
        length: number;
    }
    
    function loggingIdentity<T extends Lengthwise>(arg: T): T {
        console.log(arg.length); // Now we know it has a .length property, so no error
        return arg;
    }
    
    loggingIdentity({ length: 10, value: 3 });
    
    

    Default Type Parameters

    You can provide default types for generics to make the generic components more flexible and easier to use.

    Example:

    
    function createArray<T = string>(length: number, value: T): T[] {
        return Array(length).fill(value);
    }
    
    let stringArray = createArray(3, "x"); // Output: ["x", "x", "x"]
    let numberArray = createArray<number>(3, 5); // Output: [5, 5, 5]
    
    

    Function in Typescript

    Functions in TypeScript are similar to functions in JavaScript, but TypeScript allows you to define the types of the parameters and the return type of the function, adding type safety and improving the development experience. Here, we will cover various aspects of functions in TypeScript, including basic function syntax, optional and default parameters, rest parameters, function overloading, and more.

    Basic Function Syntax

    Here is a simple example of a function in TypeScript:

    
    function greet(name: string): string {
        return `Hello, ${name}!`;
    }
    
    console.log(greet("John")); // Output: Hello, John!
    

    In this example:

    name: string specifies that the name parameter must be a string.

    : string after the parentheses specifies that the function returns a string.

    Function with Optional Parameters

    You can define optional parameters using the ? symbol:

    
    function greet(name: string, age?: number): string {
        if (age) {
            return `Hello, ${name}. You are ${age} years old.`;
        } else {
            return `Hello, ${name}.`;
        }
    }
    
    console.log(greet("John")); // Output: Hello, John.
    console.log(greet("Tom", 25)); // Output: Hello, Tom. You are 25 years old.
    
    

    Default Parameters

    You can also provide default values for parameters:

    
    function greet(name: string, greeting: string = "Hello"): string {
        return `${greeting}, ${name}!`;
    }
    
    console.log(greet("John")); // Output: Hello, John!
    console.log(greet("Tom", "Hi")); // Output: Hi, Tom!
    
    

    Rest Parameters

    Rest parameters allow you to pass an arbitrary number of arguments to a function:

    
    function sum(...numbers: number[]): number {
        return numbers.reduce((acc, num) => acc + num, 0);
    }
    
    console.log(sum(1, 2, 3)); // Output: 6
    console.log(sum(1, 2, 3, 4, 5)); // Output: 15
    
    

    Function Types

    
    type GreetFunction = (name: string) => string;
    
    const greet: GreetFunction = (name: string) => {
        return `Hello, ${name}!`;
    };
    
    console.log(greet("John")); // Output: Hello, John!
    
    

    Arrow Functions

    TypeScript also supports arrow functions, which can be especially useful for inline functions:

    
    const greet = (name: string): string => {
        return `Hello, ${name}!`;
    };
    
    console.log(greet("John")); // Output: Hello, John!
    
    

    Overloading

    TypeScript allows you to define multiple signatures for a function:

    
    function greet(name: string): string;
    function greet(name: string, age: number): string;
    function greet(name: string, age?: number): string {
        if (age !== undefined) {
            return `Hello, ${name}. You are ${age} years old.`;
        } else {
            return `Hello, ${name}.`;
        }
    }
    
    console.log(greet("John")); // Output: Hello, John.
    console.log(greet("Tom", 25)); // Output: Hello, Tom. You are 25 years old.
    
    

    In this example, there are two function signatures for greet, one with a single name parameter and one with both name and age parameters. The implementation handles both cases.

    These examples cover the basics of functions in TypeScript. You can use these concepts to write more complex functions as needed.