0% found this document useful (0 votes)
0 views98 pages

CSS

Uploaded by

infodelhigame
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
0 views98 pages

CSS

Uploaded by

infodelhigame
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 98

LEARN

CSS
BEGINNER-TO-ADVANCEd

Author :
Karan Nath
About the Author
Welcome to my e-book on CSS! I’m Karan Nath, a passionate web developer with a deep appreciation for
the art and science of creating engaging, functional, and user-friendly websites. My journey into web
development began few years ago, and since then, I have been dedicated to mastering the intricacies of
web technologies and sharing that knowledge with others.

My Journey
I started my career in web development with a strong foundation in HTML, CSS, and JavaScript. Over the
years, I’ve worked on a variety of projects ranging from small personal websites to large-scale web
applications. My experience has taught me the importance of clean, efficient code and the value of
continuous learning in this ever-evolving field.

Why This E-Book?


In my experience, understanding CSS is crucial for anyone looking to build a strong foundation in web
development. This e-book is designed to take you from the basics to more advanced concepts, providing
a clear and comprehensive guide to CSS. Whether you’re a beginner eager to learn or an experienced
developer looking to refresh your knowledge, I’ve created this resource to be both informative and
practical.

What You’ll Learn


In this e-book, you will:
Gain a solid understanding of CSS syntax and structure.
Learn how to create and manage styles, selectors, and properties.
Explore how to use CSS Grid and Flexbox for layout and design.
Discover how to handle responsive design and media queries in CSS.
Dive into advanced CSS features like animations, transitions, and custom properties.
Understand best practices for modern web development with CSS.

Connect with Me
I’m always excited to connect with fellow developers and web enthusiasts. If you have any questions,
feedback, or just want to chat about web development, feel free to reach out to me:

- Email: nathkaran327@gmail.com
- Instagram: _Code_Craze_
- LinkedIn: Karan Nath

Thank you for picking up this e-book. I hope you find it helpful and inspiring on your journey
to mastering CSS. Happy coding!

Karan Nath - E-book 1


Chapter 1: Getting Started with CSS
External Stylesheet
Internal Styles
CSS @import Rule
Inline Styles
Changing CSS with JavaScript
Styling Lists with CSS
Chapter 2: Structure and Formatting of a CSS Rule
Property Lists
Multiple Selectors
Rules, Selectors, and Declaration Blocks
Chapter 3: Comments
Single Line
Multiple Line
Chapter 4: Selectors
Basic Selectors
Attribute Selectors
Combinators
Pseudo-classes
Child Pseudo Class
Class Name Selectors
Select Element Using Its ID Without the High Specificity of the ID Selector
The
Selector
CSS3
Selector Example
The
Pseudo-class Example and
CSS Pseudo-class
Global Boolean with Checkbox
and ~ (General Sibling Combinator)
ID Selectors
How to Style a Range Input
The
Pseudo-class Selector Example
Chapter 5: Backgrounds
Background Color
Background Gradients
Background Image
Background Shorthand
Background Size
Background Position
The background-origin Property
Multiple Background Image
Background AttachmentBackground Clip
Background Repeat
background-blend-mode Property
Background Color with Opacity
Chapter 6: Centering
Using Flexbox
Using CSS Transform
Using margin: 0 auto;
Using text-align
Using position: absolute
Using calc()
Using line-height
Vertical Align Anything with 3 Lines of Code

KARAN NATH - E-BOOK 2


Centering in Relation to Another Item
Ghost Element Technique (Michał Czernow's Hack)
Centering Vertically and Horizontally Without Worrying About Height or Width
Vertically Align an Image Inside div
Centering with Fixed Size
Vertically Align Dynamic Height Elements
Horizontal and Vertical Centering Using Table Layout
Chapter 7: The Box Model
What is the Box Model?
box-sizing
Chapter 8: Margins
Margin Collapsing
Apply Margin on a Given Side
Margin Property Simplification
Horizontally Center Elements on a Page Using Margin
Example 1
Negative Margins
Chapter 9: Padding
Padding Shorthand
Padding on a Given Side
Chapter 10: Border
border-radius
border-style
Multiple Borders
border (Shorthands)
border-collapse
border-image
Creating a Multi-colored Border Using border-image
border-[left|right|top|bottom]
Chapter 11: Outlines
Overview
outline-style
Chapter 12: Overflow
overflow-wrap
overflow-x and overflow-y
overflow: scroll
overflow: visible
Block Formatting Context Created with Overflow
Chapter 13: Media Queries
Terminology and Structure
Basic Example
mediatype
Media Queries for Retina and Non-Retina Screens
Width vs Viewport
Using Media Queries to Target Different Screen Sizes
Use on Link Tag
Media Queries and IE8
Chapter 14: Floats
Float an Image Within Text
clear Property
Clearfix
In-line div Using Float
Use of Overflow Property to Clear Floats
Simple Two Fixed-Width Column Layout
Simple Three Fixed-Width Column Layout
Two-Column Lazy/Greedy Layout
Chapter 15: Typography
The Font Shorthand

KARAN NATH - E-BOOK 3


Quotes
Font Size
Text Direction
Font Stacks
Text Overflow
Text Shadow
Text Transform
Letter Spacing
Text Indent
Text Decoration
Word Spacing
Font Variant
Chapter 16: Flexible Box Layout (Flexbox)
Dynamic Vertical and Horizontal Centering (align-items, justify-content)
Sticky Variable-Height Footer
Optimally Fit Elements to Their Container
Holy Grail Layout Using Flexbox
Perfectly Aligned Buttons Inside Cards with Flexbox
Same Height on Nested Containers
Chapter 17: Cascading and Specificity
Calculating Selector Specificity
The !important Declaration
Cascading
More Complex Specificity Example
Chapter 18: Colors
currentColor
Color Keywords
Hexadecimal Value
rgb() Notation
rgba() Notation
hsl() Notation
hsla() Notation
Chapter 19: Opacity
Opacity Property
IE Compatibility for opacity
Chapter 20: Length Units
Creating Scalable Elements Using rems and ems
Font Size with rem
vmin and vmax
vh and vw
Using Percent %
Chapter 21: Pseudo-Elements
Pseudo-Elements
Pseudo-Elements in Lists
Chapter 22: Positioning
Overlapping Elements with z-index
Absolute Position
Fixed Position
Relative Position
Static Positioning
Chapter 23: Layout Control
The Display Property
To Get Old Table Structure Using div
Chapter 24: Grid
Basic Example
Chapter 25: Tables
Table Layout
Empty Cells
Border Collapse
KARAN NATH - E-BOOK 4
Border Spacing
Caption Side
Chapter 26: Transitions
Transition Shorthand
Cubic-bezier
Transition (Longhand)
Chapter 27: Animations
Animations with Keyframes
Animations with the Transition Property
Syntax Examples
Increasing Animation Performance Using the `will-change` Attribute
Chapter 28: 2D Transforms
Rotate
Scale
Skew
Multiple Transforms
Translate
Transform Origin
Chapter 29: 3D Transforms
Compass Pointer or Needle Shape Using 3D Transforms
3D Text Effect with Shadow
Backface Visibility
3D Cube
Chapter 30: Filter Property
Blur
Drop Shadow (Use box-shadow Instead if Possible)
Hue Rotate
Multiple Filter Values
Invert Color
Chapter 31: Cursor Styling
Changing Cursor Type
Pointer-events
Caret-color
Chapter 32: Box-shadow
Bottom-only Drop Shadow Using a Pseudo-element
Drop Shadow
Inner Drop Shadow
Multiple Shadows
Chapter 33: Shapes for Floats
Shape Outside with Basic Shape – circle()
Shape Margin
Chapter 34: List Styles
Bullet Position
Removing Bullets / Numbers
Type of Bullet or Numbering
Chapter 35: Counters
Applying Roman Numerals Styling to the Counter Output
Number Each Item Using CSS Counter
Implementing Multi-level Numbering Using CSS Counters
Chapter 36: Functions
calc() Function
attr() Function
var() Function
radial-gradient() Function
linear-gradient() Function
Chapter 37: Custom Properties (Variables)
Variable Color
Variable Dimensions
KARAN NATH - E-BOOK 5
Variable Cascading
Valid/Invalids
With Media Queries
Chapter 38: Single Element Shapes
Trapezoid
Triangles
Circles and Ellipses
Bursts
Square
Cube
Pyramid
Chapter 39: Columns
Simple Example (column-count)
Column Width
Chapter 40: Multiple Columns
Create Multiple Columns
Basic Example
Chapter 41: Inline-Block Layout
Justified Navigation Bar
Chapter 42: Inheritance
Automatic Inheritance
Enforced Inheritance
Chapter 43: CSS Image Sprites
A Basic Implementation
Chapter 44: Clipping and Masking
Clipping and Masking: Overview and Difference
Simple Mask That Fades an Image from Solid to Transparent
Clipping (Circle)
Clipping (Polygon)
Using Masks to Cut a Hole in the Middle of an Image
Using Masks to Create Images with Irregular Shapes
Chapter 45: Fragmentation
Media Print Page-break
Chapter 46: CSS Object Model (CSSOM)
Adding a Background-image Rule via the CSSOM
Introduction
Chapter 47: Feature Queries
Basic @supports Usage
Chaining Feature Detections
Chapter 48: Stacking Context
Stacking Context
Chapter 49: Block Formatting Contexts
Using the Overflow Property with a Value Different to visible
Chapter 50: Vertical Centering
Centering with display: table
Centering with Flexbox
Centering with Transform
Centering Text with Line Height
Centering with Position: absolute
Centering with Pseudo Element

KARAN NATH - E-BOOK 6


Chapter 1: Getting Started with CSS

External Stylesheet

An external stylesheet is a separate CSS file linked to your HTML file using the `<link>` tag in the HTML
`<head>` section.

Example:

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
```

In `styles.css`:

```css
h1 {
color: blue;
}
```

Internal Styles

Internal styles are added directly inside the HTML file using the `<style>` tag in the `<head>` section.

Example:

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
h1 {
color: green;
}
</style>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
```

CSS @import Rule

The `@import` rule lets you include other CSS files within your CSS file. Place it at the top of your CSS
file.

KARAN NATH - E-BOOK 7


Example:

```css
@import url('reset.css');
@import url('typography.css');

body {
font-family: Arial, sans-serif;
}
```

Inline Styles

Inline styles are added directly to an HTML element using the `style` attribute.

Example:

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1 style="color: red;">Hello World</h1>
</body>
</html>
```

Changing CSS with JavaScript

You can use JavaScript to change CSS styles by modifying the `style` property of an HTML element.

Example:

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1 id="myHeading">Hello World</h1>
<button onclick="changeStyle()">Change Style</button>

<script>
function changeStyle() {
document.getElementById('myHeading').style.color = 'purple';
}
</script>
</body>
</html>
```

Styling Lists with CSS

You can change the appearance of lists using the `list-style` property in CSS.

KARAN NATH - E-BOOK 8


Example:

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
ul {
list-style-type: square;
}

ol {
list-style-type: upper-roman;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>

<ol>
<li>First</li>
<li>Second</li>
</ol>
</body>
</html>
```

KARAN NATH - E-BOOK 9


Chapter 2: Structure and Formatting of a CSS Rule

Property Lists

A CSS rule is made up of a selector and a declaration block. The declaration block contains one or more
property-value pairs. Each property-value pair is written in the format `property: value;` and is separated
by a semicolon.

Example:

```css
selector {
property1: value1;
property2: value2;
}
```

Here’s an example of a CSS rule:

```css
h1 {
color: blue;
font-size: 24px;
}
```

Multiple Selectors

You can apply the same styles to multiple elements by grouping selectors. Separate each selector with a
comma.

Example:

```css
h1, h2, h3 {
color: navy;
font-family: Arial, sans-serif;
}
```

In this example, the styles will be applied to all `<h1>`, `<h2>`, and `<h3>` elements.

Rules, Selectors, and Declaration Blocks

A CSS rule consists of a selector and a declaration block. The selector targets the HTML element(s) to
style, and the declaration block contains the styles.

Example:

```css
/* Selector */
p{
/* Declaration Block */
color: green;
font-size: 16px;
}
```

In this example, the `p` selector targets all `<p>` elements, and the declaration block specifies that the
text color should be green and the font size should be 16px.

KARAN NATH - E-BOOK 10


Chapter 3: Comments

Single Line

Single-line comments in CSS start with `/*` and end with `*/`. They are used to add notes or explanations
in the CSS code and do not affect the rendering of the page.

Example:

```css
/* This is a single-line comment */
p{
color: red; /* This is another comment */
}
```

Multiple Line

Multiple-line comments, also known as block comments, are used to add comments that span more than
one line. They also start with `/*` and end with `*/`.

Example:

```css
/*
This is a multiple-line comment.
It can span several lines.
*/
h1 {
color: blue;
}
```

These comments help in documenting the CSS code and can be useful for clarifying complex styles or
sections of the stylesheet.

KARAN NATH - E-BOOK 11


Conclusion

This chapter explains the use of the `<p>` element in HTML to create and format paragraphs. Proper use
of paragraphs enhances the structure and readability of web content, contributing to a better user
experience.

---

This explanation provides a clear and detailed overview of Chapter 4: Paragraphs, including code
examples and best practices.

KARAN NATH - E-BOOK 12


Chapter 4: Selectors

Basic Selectors

Basic selectors are used to select HTML elements based on their name, class, or ID.

Example:

```css
/* Selects all <p> elements */
p{
color: blue;
}

/* Selects all elements with class "example" */


.example {
font-size: 20px;
}

/* Selects the element with ID "unique" */


#unique {
margin: 10px;
}
```

Attribute Selectors

Attribute selectors target elements based on their attributes and attribute values.

Example:

```css
/* Selects input elements with a type attribute of "text" */
input[type="text"] {
border: 1px solid black;
}

/* Selects anchor elements with a href attribute that starts with "https" */
a[href^="https"] {
color: green;
}
```

Combinators

Combinators define the relationships between selectors to target elements based on their relationship to
other elements.

Example:

```css
/* Selects <p> elements that are direct children of <div> */
div > p {
color: red;
}

KARAN NATH - E-BOOK 13


/* Selects all <p> elements that are descendants of <div> */
div p {
font-style: italic;
}

/* Selects all <p> elements that are siblings of <h1> */


h1 + p {
margin-top: 0;
}

/* Selects all <p> elements that follow <h1> */


h1 ~ p {
color: blue;
}
```

Pseudo-classes

Pseudo-classes apply styles to elements based on their state or position in the document.

Example:

```css
/* Selects the first <p> element */
p:first-of-type {
font-weight: bold;
}

/* Selects <a> elements when they are hovered over */


a:hover {
color: red;
}

/* Selects <input> elements that are checked */


input:checked {
background-color: yellow;
}
```

Child Pseudo Class

The child pseudo-class selects elements that are direct children of a specified element.

Example:

```css
/* Selects <li> elements that are direct children of <ul> */
ul > li {
list-style-type: none;
}
```

Class Name Selectors

Class name selectors target elements with a specific class attribute.

KARAN NATH - E-BOOK 14


Example:

```css
/* Selects all elements with class "highlight" */
.highlight {
background-color: yellow;
}
```

Select Element Using Its ID Without the High Specificity of the ID Selector

You can use attribute selectors or class selectors to achieve similar styling without the high specificity of
ID selectors.

Example:

```css
/* Selects elements with an ID of "item" */
[id="item"] {
font-size: 18px;
}

/* Selects elements with the class "item" */


.item {
font-size: 18px;
}
```

The Selector

The `:not` pseudo-class excludes elements that match a specified selector.

Example:

```css
/* Selects all <p> elements except those with class "exclude" */
p:not(.exclude) {
color: blue;
}
```

CSS3 Selector Example

CSS3 introduced new selectors to target elements more precisely.

Example:

```css
/* Selects the last child of its parent */
p:last-child {
margin-bottom: 0;
}

/* Selects the nth child of its parent */


li:nth-child(2) {
color: green;
}
```

KARAN NATH - E-BOOK 15


The Pseudo-class Example and CSS Pseudo-class

Pseudo-classes are used to style elements based on their state or position.

Example:

```css
/* Selects the first link that is visited */
a:visited {
color: purple;
}

/* Selects the last link that is hovered over */


a:hover:last-of-type {
color: orange;
}
```

Global Boolean with Checkbox and ~ (General Sibling Combinator)

The general sibling combinator (`~`) selects elements that are siblings following a specified element.

Example:

```css
/* Selects all <p> elements that follow a <h1> element */
h1 ~ p {
color: gray;
}
```

ID Selectors

ID selectors target elements with a specific ID. IDs should be unique within a page.

Example:

```css
/* Selects the element with ID "header" */
#header {
background-color: lightgray;
}
```

How to Style a Range Input

Styling range inputs involves customizing the appearance of sliders.

Example:

```css
/* Styles the range input track */
input[type="range"]::-webkit-slider-runnable-track {
background: #ddd;
height: 8px;
}

```

KARAN NATH - E-BOOK 16


/* Styles the range input thumb */
input[type="range"]::-webkit-slider-thumb {
background: #4CAF50;
height: 20px;
width: 20px;
cursor: pointer;
}
```

The Pseudo-class Selector Example

Pseudo-classes can also be used for more specific element targeting.

Example:

```css
/* Selects the first child of its parent */
:first-child {
color: blue;
}

/* Selects elements when they are being dragged */


:active {
background-color: lightblue;
}

KARAN NATH - E-BOOK 17


Chapter 5: Backgrounds

Background Color

The `background-color` property sets the background color of an element.

Example:

```css
/* Sets a background color for all <div> elements */
div {
background-color: lightblue;
}
```

Background Gradients

Background gradients are used to create smooth transitions between colors.

Example:

```css
/* Creates a linear gradient from blue to green */
div {
background: linear-gradient(to right, blue, green);
}

/* Creates a radial gradient from red to yellow */


div {
background: radial-gradient(circle, red, yellow);
}
```

Background Image

The `background-image` property sets an image as the background of an element.

Example:

```css
/* Sets a background image for all <section> elements */
section {
background-image: url('background.jpg');
}
```

Background Shorthand

The `background` shorthand property allows you to set multiple background properties in one line.

Example:

```css
/* Sets background color, image, and position */
div {
background: lightgray url('image.jpg') no-repeat center center;
}
```

KARAN NATH - E-BOOK 18


Background Size

The `background-size` property controls the size of the background image.

Example:

```css
/* Scales the background image to cover the entire element */
div {
background-size: cover;
}

/* Sets the background image to a specific size */


div {
background-size: 100px 100px;
}
```

Background Position

The `background-position` property sets the position of the background image.

Example:

```css
/* Positions the background image at the top-right corner */
div {
background-position: top right;
}

/* Positions the background image at specific coordinates */


div {
background-position: 10px 20px;
}
```

The `background-origin` Property

The `background-origin` property defines the positioning area for background images.

Example:

```css
/* Sets the background positioning area to the content box */
div {
background-origin: content-box;
}

/* Sets the background positioning area to the padding box */


div {
background-origin: padding-box;
}
```

Multiple Background Image

You can use multiple background images for a single element.

KARAN NATH - E-BOOK 19


Example:

```css
/* Sets multiple background images */
div {
background-image: url('image1.jpg'), url('image2.jpg');
background-position: left top, right bottom;
}
```

Background Attachment

The `background-attachment` property specifies whether the background image is fixed or scrolls with
the content.

Example:

```css
/* Fixes the background image in place */
div {
background-attachment: fixed;
}

/* Scrolls the background image with the content */


div {
background-attachment: scroll;
}
```

Background Clip

The `background-clip` property controls the area within which the background is painted.

Example:

```css
/* Clips the background to the border box */
div {
background-clip: border-box;
}

/* Clips the background to the padding box */


div {
background-clip: padding-box;
}
```

Background Repeat

The `background-repeat` property controls whether and how the background image repeats.

Example:

```css
/* Prevents the background image from repeating */
div {
background-repeat: no-repeat;
}

KARAN NATH - E-BOOK 20


/* Repeats the background image both horizontally and vertically */
div {
background-repeat: repeat;
}
```

background-blend-mode Property

The `background-blend-mode` property specifies how background images and colors blend with each
other.

Example:

```css
/* Blends background images and colors using the multiply mode */
div {
background: url('image.jpg');
background-color: rgba(255, 0, 0, 0.5);
background-blend-mode: multiply;
}
```

Background Color with Opacity

To set a background color with opacity, you can use RGBA color values.

Example:

```css
/* Sets a background color with 50% opacity */
div {
background-color: rgba(0, 0, 255, 0.5);
}
```

KARAN NATH - E-BOOK 21


Chapter 6: Centering

Using Flexbox

Flexbox is a layout model that makes it easy to center elements both horizontally and vertically.

Example:

```css
/* Container with flexbox */
.container {
display: flex;
justify-content: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
height: 100vh; /* Full viewport height */
}

/* Centered item */
.item {
width: 200px;
height: 100px;
}
```

Using CSS Transform

The `transform` property can be used to center elements by translating them to the center of their
container.

Example:

```css
/* Container */
.container {
position: relative;
height: 100vh; /* Full viewport height */
}

/* Centered item */
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 100px;
}
```

Using `margin: 0 auto;`

To center block-level elements horizontally, you can use `margin: 0 auto;` if the element has a fixed
width.

Example:

```css
/* Centered block element */
.item {

KARAN NATH - E-BOOK 22


width: 200px;
margin: 0 auto;
}
```

Using `text-align`

To center inline or inline-block elements within a block-level container, use `text-align: center;` on the
container.

Example:

```css
/* Container with centered text */
.container {
text-align: center;
}

/* Centered inline-block element */


.item {
display: inline-block;
width: 200px;
height: 100px;
}
```

Using `position: absolute`

Absolute positioning can center an element by using `top` and `left` properties along with `transform`.

Example:

```css
/* Container */
.container {
position: relative;
height: 100vh; /* Full viewport height */
}

/* Centered item */
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 100px;
}
```

Using `calc()`

The `calc()` function allows you to perform calculations to position elements.

Example:

```css
/* Container */
.container {

KARAN NATH - E-BOOK 23


position: relative;
height: 100vh; /* Full viewport height */
}

/* Centered item */
.item {
position: absolute;
top: calc(50% - 50px); /* 50% of container height minus half of item's height */
left: calc(50% - 100px); /* 50% of container width minus half of item's width */
width: 200px;
height: 100px;
}
```

Using `line-height`

For vertically centering single-line text, you can match the `line-height` to the height of the container.

Example:

```css
/* Container */
.container {
height: 100px;
line-height: 100px; /* Same as container height */
text-align: center;
}

/* Centered text */
.item {
display: inline-block;
vertical-align: middle;
line-height: normal; /* Reset line-height for text element */
}
```

Vertical Align Anything with 3 Lines of Code

The `vertical-align` property can be used with inline or inline-block elements to center them vertically
relative to their container.

Example:

```css
/* Container */
.container {
height: 100px;
line-height: 100px; /* Same as container height */
text-align: center;
}

/* Centered text or inline element */


.item {
display: inline-block;
vertical-align: middle;
line-height: normal; /* Reset line-height for text element */
}
```

KARAN NATH - E-BOOK 24


Centering in Relation to Another Item

To center an element in relation to another element, position the child element absolutely within the
parent element.

Example:

```css
/* Parent container */
.parent {
position: relative;
height: 300px;
width: 300px;
background-color: lightgray;
}

/* Centered child element */


.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
background-color: blue;
}
```

Ghost Element Technique (Michał Czernow's Hack)


The ghost element technique involves creating an empty pseudo-element to help with centering.

Example:

```css
/* Parent container */
.parent {
position: relative;
height: 300px;
width: 300px;
background-color: lightgray;
}
/* Ghost element */
.parent::before {
content: "";
display: block;
height: 100%;
width: 100%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

/* Centered child element */


.child {
position: relative;
width: 100px;
height: 100px;
background-color: blue;
}
```
KARAN NATH - E-BOOK 25
Centering Vertically and Horizontally Without Worrying About Height or Width

Using Flexbox is an effective way to center elements without needing to specify their height or width.

Example:

```css
/* Parent container */
.container {
display: flex;
justify-content: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
height: 100vh; /* Full viewport height */
background-color: lightgray;
}

/* Centered item */
.item {
background-color: blue;
}
```

Vertically Align an Image Inside div

To center an image vertically inside a container, you can use Flexbox or the `vertical-align` property with
a flex container.

Example using Flexbox:

```css
/* Container */
.container {
display: flex;
align-items: center; /* Vertical centering */
height: 300px;
background-color: lightgray;
}

/* Image */
.container img {
max-width: 100%;
}
```

Example using vertical-align:

```css
/* Container */
.container {
height: 300px;
line-height: 300px; /* Same as container height */
text-align: center;
}

/* Image */
.container img {
vertical-align: middle;
max-width: 100%;
}
```

KARAN NATH - E-BOOK 26


Centering with Fixed Size

For elements with fixed sizes, you can use `margin: auto;` to center them horizontally within a container.

Example:

```css
/* Container */
.container {
width: 500px;
height: 300px;
background-color: lightgray;
position: relative;
}

/* Fixed size centered item */


.item {
width: 200px;
height: 100px;
margin: auto;
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
background-color: blue;
}
```

Vertically Align Dynamic Height Elements

To center elements with dynamic height, you can use Flexbox or grid layout.

Example using Flexbox:

```css
/* Parent container */
.container {
display: flex;
justify-content: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
height: 100vh; /* Full viewport height */
background-color: lightgray;
}

/* Centered item */
.item {
background-color: blue;
padding: 20px;
}
```

Horizontal and Vertical Centering Using Table Layout

The table layout model can be used for centering elements. Set the container to `display: table` and the
item to `display: table-cell`.

Example:

```css
/* Parent container */
.container {
display: table;
width: 100%;

KARAN NATH - E-BOOK 27


height: 100vh; /* Full viewport height */
background-color: lightgray;
}

/* Centered item */
.item {
display: table-cell;
vertical-align: middle; /* Vertical centering */
text-align: center; /* Horizontal centering */
background-color: blue;
width: 200px;
height: 100px;
margin: 0 auto;
}
```

KARAN NATH - E-BOOK 28


Chapter 7: The Box Model

What is the Box Model?

The CSS box model describes the rectangular boxes generated for elements in the document tree. Each
box consists of:

- Content: The actual content of the box, such as text or an image.


- Padding: Space between the content and the border, inside the element.
- Border: The border surrounding the padding (if any).
- Margin: Space outside the border, separating the element from other elements.

Example:

```css
/* Example of the box model */
.box {
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid black;
margin: 30px;
}
```

In this example:
- Content: 200px width and 100px height.
- Padding: 20px on all sides.
- Border: 5px solid black.
- Margin: 30px on all sides.

box-sizing

The `box-sizing` property controls how the total width and height of an element are calculated.

- content-box (default): The width and height apply only to the content area. Padding and border are
added to the total width and height.
- border-box: The width and height include content, padding, and border. Padding and border are
included within the total width and height.

Example:

```css
/* Border-box sizing */
.box {
box-sizing: border-box;
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid black;
}
```

In this example, the total width of the element will be 200px, including padding and border, instead of
adding them to the width.

KARAN NATH - E-BOOK 29


Chapter 8: Margins

Margin Collapsing

Margins between adjacent block-level elements can collapse into a single margin. The larger of the two
margins is used, and the smaller margin is ignored.

Example:

```css
/* Collapsing margins example */
.box1 {
margin-bottom: 20px;
}

.box2 {
margin-top: 30px;
}
```

In this example, the space between `.box1` and `.box2` will be 30px, not 50px.

Apply Margin on a Given Side

You can apply margins to specific sides of an element.

Example:
```css
/* Applying margin to specific sides */
.box {
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 40px;
}
```

Margin Property Simplification

The `margin` shorthand property allows you to set all four margins in one line.

Example:

```css
/* Shorthand margin property */
.box {
margin: 10px 20px 30px 40px; /* top right bottom left */
}
```

Horizontally Center Elements on a Page Using Margin

To center a block-level element horizontally, set its margins to `auto` and give it a fixed width.

Example:
```css
/* Centering a block-level element horizontally */
.box {
width: 300px;
margin: 0 auto;
}
```

KARAN NATH - E-BOOK 30


Negative Margins

Negative margins can pull elements closer together or overlap them.

Example:

```css
/* Using negative margin */
.box {
margin-left: -20px;
}
```

In this example, the element will be pulled 20px to the left of its normal position.

KARAN NATH - E-BOOK 31


Chapter 9: Padding

Padding Shorthand

The `padding` shorthand property sets padding for all four sides of an element.

Example:

```css
/* Padding shorthand property */
.box {
padding: 10px 20px 30px 40px; /* top right bottom left */
}
```

Padding on a Given Side

You can set padding for specific sides of an element.

Example:

```css
/* Padding on specific sides */
.box {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
}
```

Padding on a given side can also be set individually:

```css
/* Individual padding properties */
.box {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
}
```

KARAN NATH - E-BOOK 32


Chapter 10: Border

border-radius

The `border-radius` property creates rounded corners for an element's border.

Example:

```css
/* Rounded corners */
.box {
border-radius: 10px;
}
```

border-style

The `border-style` property sets the style of the border (e.g., solid, dashed, dotted).

Example:

```css
/* Border style */
.box {
border-style: solid;
}
```

Multiple Borders

You can set different styles, widths, and colors for each border side.

Example:

```css
/* Different styles for each border */
.box {
border-top: 5px solid black;
border-right: 5px dashed red;
border-bottom: 5px dotted blue;
border-left: 5px double green;
}
```

border (Shorthands)

The `border` shorthand property sets width, style, and color for all borders.

Example:

```css
/* Border shorthand property */
.box {
border: 2px solid black;
}
```

border-collapse

The `border-collapse` property sets whether table borders are collapsed into a single border or
separated.

KARAN NATH - E-BOOK 33


Example:

```css
/* Collapsed table borders */
table {
border-collapse: collapse;
}
```

border-image

The `border-image` property allows you to use an image as a border.

Example:

```css
/* Using an image as a border */
.box {
border-image: url('border-image.png') 30 round;
}
```

Creating a Multi-colored Border Using border-image

You can create a multi-colored border by using a gradient image.

Example:

```css
/* Multi-colored border using gradient */
.box {
border: 10px solid transparent;
border-image: linear-gradient(to right, red, yellow, green) 1;
}
```

border-[left|right|top|bottom]

You can set border styles for specific sides of an element.

Example:

```css
/* Border for specific sides */
.box {
border-top: 2px solid black;
border-bottom: 2px dashed gray;
}
```

KARAN NATH - E-BOOK 34


Chapter 11: Outlines

Overview

The `outline` property is used to draw a line around elements outside the border.

Example:

```css
/* Outline property */
.box {
outline: 2px solid red;
}
```

outline-style

The `outline-style` property sets the style of the outline (e.g., solid, dotted).

Example:

```css
/* Outline style */
.box {
outline-style: dotted;
}
```

KARAN NATH - E-BOOK 35


Chapter 12: Overflow

overflow-wrap
The `overflow-wrap` property controls how text should be wrapped when it exceeds the width of its
container.
Example:
```css
/* Text wrapping */
.box {
overflow-wrap: break-word;
}
```
overflow-x and overflow-y

The `overflow-x` and `overflow-y` properties control how content overflows horizontally and vertically.

Example:

```css
/* Overflow properties */
.box {
overflow-x: auto; /* Horizontal scrolling */
overflow-y: hidden; /* No vertical scrolling */
}
```
overflow: scroll

The `overflow` property set to `scroll` adds scrollbars to an element if its content overflows.
Example:

```css
/* Scrollbars for overflow */
.box {
overflow: scroll;
}
```
overflow: visible

The `overflow` property set to `visible` makes the content overflow the container without clipping it.

Example:

```css
/* Visible overflow */
.box {
overflow: visible;
}
```

Block Formatting Context Created with Overflow

Setting the `overflow` property to any value other than `visible` creates a new block formatting context,
which can help contain floats.

Example:

```css
/* Creating a block formatting context */
.container {
overflow: hidden; /* or overflow: auto; */
}
```

KARAN NATH - E-BOOK 36


Chapter 13: Media Queries

Terminology and Structure

Media queries are used to apply CSS rules based on the characteristics of the device, such as its width,
height, or screen resolution.

Basic Example

```css
/* Media query example */
@media (max-width: 600px) {
.box {
background-color: lightblue;
}
}
```

mediatype

Media types define the category of devices the styles are intended for, such as `screen`, `print`, or `all`.

```css
/* Media type example */
@media screen {
.box {
background-color: lightgreen;
}
}
```

Media Queries for Retina and Non-Retina Screens

Media queries can target devices with different pixel densities.

```css
/* Retina display query */
@media only screen and (min-device-pixel-ratio: 2) {
.box {
background-color: lightcoral;
}
}
```

Width vs Viewport

Media queries can target specific widths and viewports for more precise control.

```css
/* Targeting width and viewport */
@media (min-width: 600px) and (max-width: 1200px) {
.box {
background-color: lightyellow;
}
}
```

Using Media Queries to Target Different Screen Sizes

Media queries help create responsive designs by applying different styles at various screen sizes.

KARAN NATH - E-BOOK 37


```css
/* Different screen sizes */
@media (max-width: 480px) {
.box {
background-color: pink;
}
}

@media (min-width: 481px) and (max-width: 768px) {


.box {
background-color: orange;
}
}

@media (min-width: 769px) {


.box {
background-color: lightgreen;
}
}
```

Use on Link Tag

Media queries can be used directly in HTML to apply different stylesheets.

```html
<!-- Link tag with media query -->
<link rel="stylesheet" media="screen and (max-width: 600px)" href="small-screen.css">
```

Media Queries and IE8

For compatibility with IE8 and earlier, use a JavaScript polyfill like Respond.js.

```html
<!-- Respond.js for IE8 support -->
<!--[if lt IE 9]>
<script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
```

KARAN NATH - E-BOOK 38


Chapter 14: Floats

Float an Image Within Text

The `float` property is used to position an element to the left or right of its container, allowing text to wrap
around it.

Example:

```css
/* Floating an image */
img {
float: left;
margin-right: 10px;
}
```

clear Property

The `clear` property is used to control the behavior of floating elements, preventing them from wrapping
around other floated elements.

Example:

```css
/* Clear property */
.clearfix {
clear: both;
}
```
Clearfix

The clearfix hack is used to clear floats, ensuring that a container fully encloses its floated children.

Example:

```css
/* Clearfix example */
.clearfix::after {
content: "";
display: table;
clear: both;
}
```
In-line div Using Float

Floating a `div` element allows it to be placed next to other elements.


Example:

```css
/* Floating div elements */
.div1 {
float: left;
width: 50%;
}

.div2 {
float: right;
width: 50%;
}
```
KARAN NATH - HTML E-BOOK 39
Chapter 15: Typography

The Font Shorthand

The `font` shorthand property sets font-style, font-variant, font-weight, font-size, line-height, and font-
family.

Example:

```css
/* Font shorthand */
.text {
font: italic small-caps bold 16px/1.5 Arial, sans-serif;
}
```

Quotes

The `quotes` property sets quotation marks for quotes in text.

Example:

```css
/* Custom quotes */
q{
quotes: "“" "”" "‘" "’";
}
```

Font Size

The `font-size` property sets the size of the font.

Example:

```css
/* Font size */
.text {
font-size: 18px;
}
```

Text Direction

The `direction` property sets the text direction to left-to-right or right-to-left.

Example:

```css
/* Right-to-left text direction */
.text {
direction: rtl;
}
```

Font Stacks

Font stacks provide fallback options if the preferred font is unavailable.

KARAN NATH - E-BOOK 40


Example:

```css
/* Font stack */
.text {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
```

Text Overflow

The `text-overflow` property specifies how overflowed content that is not displayed should be signaled.

Example:

```css
/* Text overflow */
.text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
```

Text Shadow

The `text-shadow` property adds shadow to text.

Example:

```css
/* Text shadow */
.text {
text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5);
}
```

Text Transform

The `text-transform` property controls the capitalization of text.

Example:

```css
/* Text transform */
.text {
text-transform: uppercase;
}
```

Letter Spacing

The `letter-spacing` property controls the space between characters.

Example:
```css
/* Letter spacing */
.text {
letter-spacing: 2px;
}
```
KARAN NATH - E-BOOK 41
Text Indent

The `text-indent` property sets the indentation of the first line of text.

Example:

```css
/* Text indent */
.text {
text-indent: 30px;
}
```

Text Decoration

The `text-decoration` property sets the decoration of text, such as underline, overline, or line-through.

Example:

```css
/* Text decoration */
.text {
text-decoration: underline;
}
```

Word Spacing

The `word-spacing` property sets the space between words.

Example:

```css
/* Word spacing */
.text {
word-spacing: 10px;
}
```

Font Variant

The `font-variant` property controls the usage of alternate glyphs.

Example:

```css
/* Font variant */
.text {
font-variant: small-caps;
}
```

KARAN NATH - E-BOOK 42


Chapter 16: Flexible Box Layout (Flexbox)

Dynamic Vertical and Horizontal Centering (align-items, justify-content)

Flexbox makes it easy to center elements both vertically and horizontally.

Example:

```css
/* Centering elements */
.container {
display: flex;
align-items: center; /* Vertical centering */
justify-content: center; /* Horizontal centering */
height: 100vh;
}
```

Sticky Variable-Height Footer

Flexbox can be used to create a sticky footer that stays at the bottom of the page, regardless of the
content height.

Example:

```css
/* Sticky footer layout */
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
}

.content {
flex: 1;
}

.footer {
background: lightgray;
padding: 10px;
}
```

Optimally Fit Elements to Their Container

Flexbox can automatically adjust the size of elements to optimally fit their container.

Example:

```css
/* Flex items fit to container */
.container {
display: flex;
}

.item {
flex: 1; /* All items will have equal width */
}
```

KARAN NATH - E-BOOK 43


Holy Grail Layout Using Flexbox

The Holy Grail layout consists of a header, footer, and three columns (left sidebar, main content, right
sidebar). Flexbox makes this layout simple to achieve.

Example:
```css
/* Holy Grail layout */
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
}

.header, .footer {
background: lightgray;
padding: 10px;
}

.main-content {
display: flex;
flex: 1;
}

.sidebar {
width: 200px;
background: lightblue;
padding: 10px;
}

.main {
flex: 1;
background: lightyellow;
padding: 10px;
}
```

Perfectly Aligned Buttons Inside Cards with Flexbox

Flexbox helps align buttons within cards or containers.

Example:

```css
/* Aligned buttons */
.card {
display: flex;
flex-direction: column;
border: 1px solid #ccc;
padding: 10px;
}

.card-content {
flex: 1;
}

.card-actions {
display: flex;
justify-content: flex-end;
}
```
KARAN NATH - E-BOOK 44
Same Height on Nested Containers

Flexbox ensures that nested containers or items have the same height.

Example:

```css
/* Equal height containers */
.container {
display: flex;
}

.item {
flex: 1;
margin: 10px;
background: lightgray;
padding: 10px;
}
```

KARAN NATH - E-BOOK 45


Chapter 17: Cascading and Specificity

Calculating Selector Specificity

Selector specificity determines which CSS rule is applied by the browser. It’s calculated based on the
types of selectors used.

Example:
```css
/* Specificity example */
#id {
/* ID selectors have high specificity */
color: blue;
}

.class {
/* Class selectors have medium specificity */
color: green;
}

element {
/* Element selectors have low specificity */
color: red;
}
```

The `#id` selector has the highest specificity, followed by the `.class` selector, and then the `element`
selector.

The !important Declaration

Using `!important` can override all other specificity rules.

Example:

```css
/* !important declaration */
p{
color: red !important;
}
```

In this example, all `p` elements will be red, even if other rules have higher specificity.

Cascading

Cascading determines how conflicting styles are resolved. It considers specificity, importance (such as
`!important`), and the order of appearance in the CSS.

Example:

```css
/* Cascading example */
p{
color: red;
}

p{
color: blue; /* This will be applied because it comes later */
}
```
KARAN NATH - E-BOOK 46
More Complex Specificity Example

Combining different types of selectors to understand how specificity is calculated.

Example:

```css
/* Complex specificity */
div p {
color: green; /* Specificity 0-0-1-1 */
}

#main .content p {
color: orange; /* Specificity 0-1-1-1 */
}

p{
color: purple !important; /* This will override all */
}
```

In this example, the `p` elements within `#main .content` will be orange due to higher specificity, but any
`p` element with `!important` will be purple, regardless of other rules.

KARAN NATH - E-BOOK 47


Chapter 18: Colors

currentColor

The `currentColor` keyword uses the current color value of an element for properties like `border-color`
or `text-shadow`.

Example:

```css
/* Using currentColor */
.box {
color: red;
border: 2px solid currentColor; /* Border will also be red */
}
```

Color Keywords

Color keywords are predefined color names, like `red`, `blue`, `green`, etc.

Example:

```css
/* Color keywords */
.box {
color: blue;
}
```

Hexadecimal Value

Hexadecimal color values are used to define colors in hexadecimal format (e.g., `#RRGGBB`).

Example:

```css
/* Hexadecimal color */
.box {
color: #ff5733; /* A shade of orange */
}
```

rgb() Notation

The `rgb()` function defines colors using red, green, and blue values.

Example:

```css
/* RGB color */
.box {
color: rgb(255, 87, 51); /* A shade of orange */
}
```

rgba() Notation

The `rgba()` function defines colors with an additional alpha channel for opacity.

KARAN NATH - E-BOOK 48


Example:

```css
/* RGBA color with opacity */
.box {
color: rgba(255, 87, 51, 0.5); /* Semi-transparent orange */
}
```

hsl() Notation

The `hsl()` function defines colors using hue, saturation, and lightness values.

Example:

```css
/* HSL color */
.box {
color: hsl(15, 100%, 60%); /* A shade of orange */
}
```

hsla() Notation

The `hsla()` function defines colors with an additional alpha channel for opacity.

Example:

```css
/* HSLA color with opacity */
.box {
color: hsla(15, 100%, 60%, 0.5); /* Semi-transparent orange */
}
```

KARAN NATH - E-BOOK 49


Chapter 19: Opacity

Opacity Property

The `opacity` property sets the transparency level of an element. It ranges from `0` (fully transparent) to
`1` (fully opaque).

Example:

```css
/* Opacity property */
.box {
opacity: 0.5; /* 50% transparent */
}
```

IE Compatibility for opacity

For Internet Explorer versions prior to IE9, use the `filter` property to achieve similar opacity effects.

Example:

```css
/* IE compatibility for opacity */
.box {
opacity: 0.5; /* Modern browsers */
filter: alpha(opacity=50); /* IE8 and earlier */
}
```

KARAN NATH - E-BOOK 50


Chapter 20: Length Units

Creating Scalable Elements Using rems and ems

The `rem` and `em` units are relative to font size and allow for scalable elements.

- `rem` (root em) is relative to the root element's font size (`html`).
- `em` is relative to the font size of the element itself or its parent.

Example:

```css
/* Using rem and em for scalable elements */
html {
font-size: 16px; /* Base font size */
}

.box {
font-size: 1.5rem; /* 24px (16px * 1.5) */
margin: 2em; /* Margin is relative to the element's font size */
}
```

Font Size with rem

Setting font size with `rem` ensures consistency across elements because it's based on the root
element's font size.

Example:

```css
/* Font size with rem */
.box {
font-size: 1.2rem; /* Font size relative to the root element */
}
```

vmin and vmax

- `vmin` is a percentage of the smaller dimension of the viewport (width or height).


- `vmax` is a percentage of the larger dimension of the viewport.

Example:

```css
/* Using vmin and vmax */
.box {
width: 50vmin; /* 50% of the smaller viewport dimension */
height: 50vmax; /* 50% of the larger viewport dimension */
}
```

vh and vw

- `vh` (viewport height) is a percentage of the viewport's height.


- `vw` (viewport width) is a percentage of the viewport's width.

KARAN NATH - E-BOOK 51


Example:

```css
/* Using vh and vw */
.box {
width: 50vw; /* 50% of the viewport's width */
height: 50vh; /* 50% of the viewport's height */
}
```

Using Percent %

The `%` unit is relative to the parent element’s dimensions.

Example:

```css
/* Using percentage */
.box {
width: 50%; /* 50% of the parent element's width */
}
```

KARAN NATH - E-BOOK 52


Chapter 21: Pseudo-Elements

Pseudo-Elements

Pseudo-elements are used to style specific parts of an element. Common pseudo-elements include
`::before` and `::after`, which insert content before or after an element’s content.

Example:

```css
/* Pseudo-elements example */
.box::before {
content: "★"; /* Adds a star before the content */
color: gold;
}

.box::after {
content: "★"; /* Adds a star after the content */
color: gold;
}
```

Pseudo-Elements in Lists

Pseudo-elements can be used to style list items or add decorative content.

Example:

```css
/* Pseudo-elements in lists */
ul li::marker {
color: red; /* Changes the color of the list item marker */
}

ul li::before {
content: "• "; /* Adds a bullet before list items */
color: blue;
}
```

KARAN NATH - E-BOOK 53


Chapter 22: Positioning

Overlapping Elements with z-index

The `z-index` property controls the stacking order of positioned elements. Higher values are placed in
front of lower values.

Example:

```css
/* Overlapping elements */
.box1 {
position: absolute;
z-index: 1; /* Positioned behind .box2 */
background-color: lightblue;
}

.box2 {
position: absolute;
z-index: 2; /* Positioned in front of .box1 */
background-color: lightcoral;
}
```

Absolute Position

The `position: absolute` property positions an element relative to its nearest positioned ancestor (or the
initial containing block if none exists).

Example:

```css
/* Absolute positioning */
.container {
position: relative; /* Container as the reference point */
}

.box {
position: absolute;
top: 10px;
left: 20px;
background-color: lightgreen;
}
```

Fixed Position

The `position: fixed` property positions an element relative to the viewport, staying in place as the page is
scrolled.

Example:

```css
/* Fixed positioning */
.box {
position: fixed;
bottom: 10px;
right: 10px;
background-color: lightyellow;
}
```
KARAN NATH - E-BOOK 54
Relative Position

The `position: relative` property positions an element relative to its normal position. It does not affect the
layout of surrounding elements.

Example:

```css
/* Relative positioning */
.box {
position: relative;
top: 10px;
left: 20px;
background-color: lightpink;
}
```

Static Positioning

The default positioning value is `static`, which places elements in the normal document flow.

Example:

```css
/* Static positioning (default) */
.box {
position: static;
background-color: lightgray;
}
```

KARAN NATH - E-BOOK 55


Chapter 23: Layout Control

The Display Property

The `display` property specifies how an element is displayed in the document layout. Common values
include `block`, `inline`, `flex`, `grid`, and `none`.

Example:

```css
/* Display property examples */
.block-element {
display: block; /* Takes up full width, with a new line before and after */
}

.inline-element {
display: inline; /* Takes up only as much width as needed, no new lines */
}

.flex-container {
display: flex; /* Enables flexbox layout */
}

.grid-container {
display: grid; /* Enables grid layout */
}

.hidden-element {
display: none; /* Hides the element */
}
```

To Get Old Table Structure Using div

Using `div` elements to create a table-like structure without using actual `<table>` elements.

Example:

```css
/* Table-like layout using divs */
.table {
display: table;
width: 100%;
}

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

.table-cell {
display: table-cell;
padding: 10px;
border: 1px solid #ddd;
}
```

KARAN NATH - E-BOOK 56


```html
<!-- HTML structure -->
<div class="table">
<div class="table-row">
<div class="table-cell">Cell 1</div>
<div class="table-cell">Cell 2</div>
</div>
<div class="table-row">
<div class="table-cell">Cell 3</div>
<div class="table-cell">Cell 4</div>
</div>
</div>
```

KARAN NATH - HTML E-BOOK 57


Chapter 24: Grid

Basic Example

CSS Grid Layout provides a two-dimensional grid-based layout system, allowing for more complex and
responsive designs. Here’s a basic example of creating a simple grid.

Example:

```css
/* Basic grid layout */
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Creates three equal columns */
gap: 10px; /* Space between grid items */
}

.item {
background-color: lightblue;
padding: 20px;
border: 1px solid #ddd;
}
```

```html
<!-- HTML structure -->
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
</div>
```

In this example:

- The `.container` element is defined as a grid container with three equal-width columns.
- The `gap` property defines the spacing between the grid items.
- Each `.item` is styled with padding, border, and background color.

KARAN NATH - E-BOOK 58


Chapter 25: Tables

Table Layout

CSS can be used to style HTML tables, including their layout and appearance.

Example:

```css
/* Basic table layout */
.table {
width: 100%;
border-collapse: collapse; /* Collapses table borders into a single border */
}

.table th, .table td {


border: 1px solid #ddd;
padding: 8px;
text-align: left;
}

.table th {
background-color: #f4f4f4;
}
```

```html
<!-- HTML table structure -->
<table class="table">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
<td>Row 1, Cell 3</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
<td>Row 2, Cell 3</td>
</tr>
</tbody>
</table>
```

Empty Cells

You can control the appearance of empty cells in a table with the `empty-cells` property.

Example:

KARAN NATH - E-BOOK 59


```css
/* Handling empty cells */
.table {
empty-cells: hide; /* Hides borders of empty cells */
}
```

Border Collapse and Border Spacing

- `border-collapse` controls whether table borders are collapsed into a single border or separated.
- `border-spacing` sets the distance between the borders of adjacent cells.

Example:

```css
/* Border collapse and spacing */
.table {
border-collapse: separate; /* Borders are separated */
border-spacing: 10px; /* Space between cells */
}
```

```html
<table class="table">
<!-- Table content here -->
</table>
```

KARAN NATH - E-BOOK 60


Chapter 26: Transitions

Transition Shorthand
The `transition` shorthand property allows you to specify multiple transition properties in one
declaration. It includes properties for duration, timing function, delay, and which properties to transition.
Example:

```css
/* Transition shorthand example */
.box {
transition: background-color 0.5s ease-in-out, transform 0.3s ease;
}
.box:hover {
background-color: lightcoral;
transform: scale(1.1);
}
```
In this example, `background-color` will transition over `0.5s` with an `ease-in-out` timing function, and
`transform` will transition over `0.3s` with an `ease` timing function.

Cubic-bezier

The `cubic-bezier` function allows you to define a custom timing function for transitions, giving you
control over the acceleration curve.

Example:
```css
/* Custom cubic-bezier timing function */
.box {
transition: transform 0.5s cubic-bezier(0.25, 0.1, 0.25, 1);
}

.box:hover {
transform: rotate(45deg);
}
```

In this example, `cubic-bezier(0.25, 0.1, 0.25, 1)` creates a custom easing effect for the transition.
Transition (Longhand)

The longhand properties for `transition` can be set individually: `transition-property`, `transition-
duration`, `transition-timing-function`, and `transition-delay`.

Example:

```css
/* Transition longhand properties */
.box {
transition-property: background-color, transform;
transition-duration: 0.5s, 0.3s;
transition-timing-function: ease-in-out, ease;
transition-delay: 0s, 0s;
}
.box:hover {
background-color: lightcoral;
transform: scale(1.1);
}
```
This longhand approach is equivalent to the shorthand example but allows you to specify each transition
property separately.

KARAN NATH - E-BOOK 61


Chapter 27: Animations

Animations with Keyframes

CSS animations are created using the `@keyframes` rule to define the stages of the animation. The
`animation` property applies the animation to an element.

Example:

```css
/* Defining keyframes */
@keyframes slideIn {
from {
transform: translateX(-100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}

/* Applying the animation */


.box {
animation: slideIn 1s ease-out;
}
```

In this example, the `.box` element will slide in from the left and fade in over `1s`.

Animations with the Transition Property

While `transition` handles simple state changes, `animation` provides more control with multiple stages
and complex effects.

Example:

```css
/* Transition-based animation example */
.box {
transition: transform 0.5s ease;
}

.box:hover {
transform: scale(1.1);
}
```

In this example, hovering over `.box` will scale it up with a smooth transition effect.

Syntax Examples

CSS animations include properties such as `animation-name`, `animation-duration`, `animation-timing-


function`, `animation-delay`, and `animation-iteration-count`.

Example:

KARAN NATH - E-BOOK 62


```css
/* Animation syntax example */
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

.box {
animation-name: rotate;
animation-duration: 2s;
animation-timing-function: linear;
animation-delay: 0s;
animation-iteration-count: infinite;
}
```

In this example, `.box` rotates continuously with a duration of `2s`, a linear timing function, and no delay.

Increasing Animation Performance Using the `will-change` Attribute

The `will-change` property informs the browser about upcoming changes, allowing it to optimize
performance.

Example:

```css
/* Optimizing animation performance */
.box {
will-change: transform; /* Optimizes for transformations */
animation: rotate 2s linear infinite;
}
```

By using `will-change`, the browser can optimize rendering for the `transform` property, potentially
improving animation performance.

KARAN NATH - HTML E-BOOK 63


Chapter 28: 2D Transforms

Rotate

The `rotate` function allows you to rotate an element around a specified point.

Example:

```css
/* Rotate transform */
.box {
transform: rotate(45deg); /* Rotates the element 45 degrees clockwise */
}
```

Scale

The `scale` function resizes an element. You can specify different scaling factors for width and height.

Example:

```css
/* Scale transform */
.box {
transform: scale(1.5); /* Scales the element to 150% of its original size */
}
```

```css
/* Scale with different factors */
.box {
transform: scale(2, 0.5); /* Scales width by 200% and height by 50% */
}
```

Skew

The `skew` function tilts an element along the X and Y axes.

Example:

```css
/* Skew transform */
.box {
transform: skew(20deg, 10deg); /* Skews the element 20 degrees on the X-axis and 10 degrees on the
Y-axis */
}
```

Multiple Transforms

You can apply multiple transform functions to an element, separating them with spaces.

Example:
```css
/* Multiple transforms */
.box {
transform: rotate(45deg) scale(1.2) translateX(50px); /* Rotates, scales, and translates the element */
}
```

KARAN NATH - E-BOOK 64


Transform Origin

The `transform-origin` property sets the point around which an element rotates or scales.

Example:

```css
/* Transform origin */
.box {
transform: rotate(45deg);
transform-origin: top left; /* Rotation occurs around the top-left corner */
}
```

```css
/* Custom transform origin */
.box {
transform: rotate(45deg);
transform-origin: 50% 50%; /* Rotation occurs around the center of the element */
}
```

KARAN NATH - E-BOOK 65


Chapter 29: 3D Transforms

Compass Pointer or Needle Shape Using 3D Transforms

You can create a 3D compass pointer or needle shape using `rotate` and `perspective` properties.

Example:

```css
/* Compass pointer example */
.compass {
width: 100px;
height: 100px;
background: red;
transform-style: preserve-3d;
transform: rotateX(30deg) rotateY(45deg);
}
```

In this example, `rotateX` and `rotateY` are used to tilt the element in 3D space.

3D Text Effect with Shadow

Adding 3D text effects involves using `text-shadow` combined with `transform` for depth.

Example:

```css
/* 3D text effect */
.text {
font-size: 40px;
color: navy;
text-shadow: 1px 1px 0 rgba(0,0,0,0.1),
2px 2px 0 rgba(0,0,0,0.2),
3px 3px 0 rgba(0,0,0,0.3),
4px 4px 0 rgba(0,0,0,0.4),
5px 5px 0 rgba(0,0,0,0.5);
}
```

This creates a layered shadow effect to give the text a 3D appearance.

Backface Visibility

The `backface-visibility` property determines whether the back face of a transformed element is visible
when turned away from the viewer.

Example:

```css
/* Backface visibility */
.box {
width: 100px;
height: 100px;
background: lightblue;
transform: rotateY(180deg);
backface-visibility: hidden; /* Hides the back face */
}
```

KARAN NATH - E-BOOK 66


In this example, the back face of `.box` will be hidden when rotated.

3D Cube

Creating a 3D cube involves multiple faces positioned and rotated in 3D space.

Example:

```css
/* 3D cube example */
.cube {
width: 100px;
height: 100px;
position: relative;
transform-style: preserve-3d;
transform: rotateX(30deg) rotateY(45deg);
}

.cube div {
position: absolute;
width: 100%;
height: 100%;
background: rgba(255, 255, 255, 0.8);
border: 1px solid #ddd;
}

.cube .front { transform: translateZ(50px); }


.cube .back { transform: rotateY(180deg) translateZ(50px); }
.cube .left { transform: rotateY(-90deg) translateZ(50px); }
.cube .right { transform: rotateY(90deg) translateZ(50px); }
.cube .top { transform: rotateX(90deg) translateZ(50px); }
.cube .bottom { transform: rotateX(-90deg) translateZ(50px); }
```

This example positions each face of the cube to create a 3D effect.

KARAN NATH - E-BOOK 67


Chapter 30: Filter Property

Blur

The `blur` function applies a Gaussian blur to an element, making it appear out of focus.

Example:

```css
/* Blur filter */
.image {
filter: blur(5px); /* Applies a blur with a 5px radius */
}
```

Drop Shadow (Use box-shadow Instead if Possible)

The `drop-shadow` function adds a shadow effect to an element, similar to `box-shadow`, but it works
with the transparency of the element’s content.

Example:

```css
/* Drop shadow filter */
.image {
filter: drop-shadow(10px 10px 5px rgba(0, 0, 0, 0.5)); /* Adds a shadow with offset and blur */
}
```

In many cases, `box-shadow` is preferred for non-transparent elements.

Invert Color

The `invert` function inverts the colors of an element, creating a negative effect.

Example:

```css
/* Invert color filter */
.image {
filter: invert(100%); /* Inverts all colors */
}
```

Multiple Filter Values

You can apply multiple filters by separating them with spaces.

Example:

```css
/* Multiple filters */
.image {
filter: brightness(0.8) contrast(1.2) sepia(0.3); /* Applies brightness, contrast, and sepia effects */
}
```

Each filter function is applied in sequence, allowing for complex visual effects.

KARAN NATH - E-BOOK 68


Chapter 31: Cursor Styling

Changing Cursor Type


The `cursor` property changes the type of cursor displayed when the mouse pointer is over an element.

Example:
```css
/* Changing cursor type */
.pointer {
cursor: pointer; /* Changes the cursor to a hand icon */
}

.text {
cursor: text; /* Changes the cursor to an I-beam */
}

.wait {
cursor: wait; /* Changes the cursor to a waiting icon */
}

.crosshair {
cursor: crosshair; /* Changes the cursor to a crosshair */
}
```
Pointer-events

The `pointer-events` property specifies under what circumstances (if any) a particular graphic element
can be the target of mouse events.

Example:
```css
/* Pointer events */
.no-click {
pointer-events: none; /* Disables mouse events on the element */
}

.allow-click {
pointer-events: auto; /* Enables mouse events on the element */
}
```

Caret-color

The `caret-color` property sets the color of the insertion caret (the blinking cursor) in an element that
accepts user input.

Example:

```css
/* Caret color */
.input {
caret-color: red; /* Changes the caret color to red */
}

.input-blue {
caret-color: blue; /* Changes the caret color to blue */
}
```
These properties allow for customized and interactive user experiences by controlling how cursors and
pointer events are handled.

KARAN NATH - E-BOOK 69


Chapter 32: Box-shadow

Bottom-only Drop Shadow Using a Pseudo-element


To create a shadow effect on only the bottom of an element, you can use a pseudo-element.

Example:
```css
/* Bottom-only drop shadow */
.box {
position: relative;
}
.box::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 10px;
box-shadow: 0 10px 10px -10px rgba(0, 0, 0, 0.5); /* Creates a bottom-only shadow */
}
```
Drop Shadow

The `box-shadow` property adds shadow effects around an element's frame. You can specify horizontal
and vertical offsets, blur radius, spread radius, and color.

Example:
```css
/* Drop shadow */
.box {
box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5); /* Adds a shadow with offset, blur, and color */
}
```

Inner Drop Shadow

To create a shadow that appears inside the element, use the `inset` keyword.
Example:

```css
/* Inner drop shadow */
.box {
box-shadow: inset 5px 5px 10px rgba(0, 0, 0, 0.5); /* Creates an inner shadow */
}
```
Multiple Shadows

You can apply multiple shadows to an element by separating them with commas.

Example:

```css
/* Multiple shadows */
.box {
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3), -2px -2px 5px rgba(0, 0, 0, 0.3); /* Adds multiple shadow
effects */
}
```

This allows for creating complex shadow effects on elements.

KARAN NATH - E-BOOK 70


Chapter 33: Shapes for Floats

Shape Outside with Basic Shape – circle()

The `shape-outside` property allows you to wrap text around a shape. Using the `circle()` function, you
can create a circular text wrap.

Example:

```css
/* Circle shape outside */
.image {
float: left;
shape-outside: circle(50%);
width: 100px;
height: 100px;
clip-path: circle(50%);
}

.text {
width: 70%;
}
```

Shape Margin

The `shape-margin` property adds space between the shape and the text.

Example:

```css
/* Shape margin */
.image {
float: left;
shape-outside: circle(50%);
width: 100px;
height: 100px;
clip-path: circle(50%);
shape-margin: 10px; /* Adds a 10px margin around the shape */
}
```

By adding `shape-margin`, you ensure that the text does not touch the shape directly, creating a better
visual separation.

KARAN NATH - E-BOOK 71


Chapter 34: List Styles

Bullet Position

The `list-style-position` property sets whether the list marker should appear inside or outside the content
flow.

Example:

```css
/* Bullet position */
ul {
list-style-position: inside; /* Bullets appear inside the list item */
}

ol {
list-style-position: outside; /* Bullets appear outside the list item */
}
```

Removing Bullets / Numbers

The `list-style-type` property changes the marker type for a list. You can use `none` to remove bullets or
numbers.

Example:

```css
/* Removing bullets or numbers */
ul {
list-style-type: none; /* Removes bullets */
}

ol {
list-style-type: none; /* Removes numbers */
}
```

Type of Bullet or Numbering

You can change the type of bullets or numbering for lists using the `list-style-type` property.

Example:

```css
/* Custom bullets and numbering */
ul {
list-style-type: square; /* Changes bullets to squares */
}

ol {
list-style-type: upper-roman; /* Changes numbers to upper Roman numerals */
}
```

This allows for customization of list markers to fit the design and styling needs of your content.

KARAN NATH - E-BOOK 72


Chapter 35: Counters

Applying Roman Numerals Styling to the Counter Output

You can use CSS counters to create custom numbering systems, such as Roman numerals.

Example:

```css
/* Applying Roman numerals */
ol {
counter-reset: section; /* Resets the counter */
}

li {
counter-increment: section; /* Increments the counter */
}

li::before {
content: counter(section, upper-roman) ". "; /* Adds Roman numerals before each list item */
}
```

Number Each Item Using CSS Counter

CSS counters allow you to number elements dynamically.

Example:

```css
/* Numbering each item */
ol {
counter-reset: item; /* Resets the counter */
}

li {
counter-increment: item; /* Increments the counter */
}

li::before {
content: counter(item) ". "; /* Adds the counter value before each list item */
}
```

Implementing Multi-level Numbering Using CSS Counters

You can create multi-level numbering by nesting counters.

Example:

```css
/* Multi-level numbering */
ol {
counter-reset: section; /* Resets the section counter */
}

li {
counter-increment: section; /* Increments the section counter */
}

KARAN NATH - E-BOOK 73


li::before {
content: counters(section, ".") " "; /* Adds multi-level numbering */
}

ol ol {
counter-reset: subsection; /* Resets the subsection counter */
}

ol ol li {
counter-increment: subsection; /* Increments the subsection counter */
}

ol ol li::before {
content: counters(section, ".") "." counter(subsection) " "; /* Adds subsection numbering */
}
```

This example shows how to create hierarchical numbering, useful for documents or outlines with
multiple levels.

KARAN NATH - E-BOOK 74


Chapter 36: Functions

calc() Function

The `calc()` function allows you to perform calculations to determine CSS property values.

Example:

```css
/* Using calc() */
.container {
width: calc(100% - 50px); /* Subtracts 50px from 100% of the container's width */
margin-top: calc(10px + 2%); /* Adds 10px and 2% of the container's height */
}
```

attr() Function

The `attr()` function retrieves the value of an attribute of the selected element and uses it in the
stylesheet.

Example:

```css
/* Using attr() */
.tooltip::after {
content: attr(data-tooltip); /* Uses the data-tooltip attribute as the content */
}
```

var() Function

The `var()` function retrieves the value of a custom property (CSS variable).

Example:

```css
/* Using var() */
:root {
--main-color: #3498db;
--padding: 10px;
}

.element {
color: var(--main-color); /* Uses the custom property value */
padding: var(--padding); /* Uses the custom property value */
}
```

radial-gradient() Function

The `radial-gradient()` function creates a radial gradient (a gradient that radiates from an origin).

Example:

```css
/* Using radial-gradient() */
.background {
background: radial-gradient(circle, red, yellow, green); /* Creates a circular radial gradient */
}
```
KARAN NATH - E-BOOK 75
linear-gradient() Function

The `linear-gradient()` function creates a linear gradient.

Example:

```css
/* Using linear-gradient() */
.background {
background: linear-gradient(to right, red, yellow, green); /* Creates a linear gradient from left to right */
}
```

These functions allow for more dynamic and flexible CSS, making it easier to create responsive and
adaptable designs.

KARAN NATH - E-BOOK 76


Chapter 37: Custom Properties (Variables)

Variable Color

CSS custom properties, also known as variables, allow you to store values that can be reused throughout
your stylesheet.

Example:

```css
/* Defining and using a variable for color */
:root {
--main-color: #3498db; /* Defining a variable */
}

.element {
color: var(--main-color); /* Using the variable */
background-color: var(--main-color);
}
```

Variable Dimensions

You can use custom properties for dimensions as well.

Example:

```css
/* Defining and using a variable for dimensions */
:root {
--main-padding: 10px;
--main-margin: 20px;
}

.container {
padding: var(--main-padding);
margin: var(--main-margin);
}
```

Variable Cascading

Variables can inherit and cascade just like other CSS properties.

Example:

```css
/* Cascading variables */
:root {
--main-color: #3498db;
}

.section {
--main-color: #e74c3c; /* Overriding the variable within this section */
}

.element {
color: var(--main-color); /* Will be #e74c3c if inside .section, otherwise #3498db */
}
```

KARAN NATH -E-BOOK 77


Valid/Invalids

CSS variables are flexible and can be used in various contexts. However, they need to be defined before
use.

Example:

```css
/* Using variables correctly */
:root {
--main-color: #3498db;
}

.element {
color: var(--main-color); /* Valid */
}

.invalid {
color: var(--undefined-variable, red); /* Fallback to red if the variable is not defined */
}
```

With Media Queries

You can use CSS variables within media queries to adapt styles based on different conditions.

Example:

```css
/* Using variables with media queries */
:root {
--main-padding: 10px;
}

@media (min-width: 600px) {


:root {
--main-padding: 20px; /* Change the variable value based on screen width */
}
}

.container {
padding: var(--main-padding); /* The padding will change based on the screen width */
}
```

This allows for more dynamic and responsive design adjustments based on various conditions.

KARAN NATH - E-BOOK 78


Chapter 38: Single Element Shapes

Trapezoid

A trapezoid shape can be created using CSS by manipulating the borders of an element.

Example:

```css
/* Trapezoid */
.trapezoid {
width: 100px;
border-bottom: 50px solid blue;
border-left: 25px solid transparent;
border-right: 25px solid transparent;
height: 0;
}
```

Triangles

Triangles can be created by setting only one border side with a color and the other sides as transparent.

Example:

```css
/* Triangle pointing up */
.triangle-up {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}

/* Triangle pointing down */


.triangle-down {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-top: 100px solid red;
}

/* Triangle pointing left */


.triangle-left {
width: 0;
height: 0;
border-top: 50px solid transparent;
border-bottom: 50px solid transparent;
border-right: 100px solid red;
}
/* Triangle pointing right */
.triangle-right {
width: 0;
height: 0;
border-top: 50px solid transparent;
border-bottom: 50px solid transparent;
border-left: 100px solid red;
}
```
KARAN NATH -E-BOOK 79
Circles and Ellipses

Circles and ellipses can be created using the `border-radius` property.

Example:

```css
/* Circle */
.circle {
width: 100px;
height: 100px;
background-color: green;
border-radius: 50%;
}

/* Ellipse */
.ellipse {
width: 150px;
height: 100px;
background-color: green;
border-radius: 50%;
}
```

Bursts

Burst shapes can be created by using `clip-path`.

Example:

```css
/* Burst */
.burst {
width: 100px;
height: 100px;
background-color: yellow;
clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2%
35%, 39% 35%);
}
```

Square

Creating a square is straightforward, just use equal width and height.

Example:

```css
/* Square */
.square {
width: 100px;
height: 100px;
background-color: purple;
}
```

KARAN NATH - E-BOOK 80


cube

A 3D cube can be created using CSS transforms.

Example:

```css
/* Cube */
.cube {
width: 100px;
height: 100px;
background-color: lightblue;
transform: rotateX(45deg) rotateY(45deg);
transform-style: preserve-3d;
position: relative;
}

.cube::before,
.cube::after {
content: '';
position: absolute;
width: 100px;
height: 100px;
background-color: lightblue;
}

.cube::before {
transform: rotateY(90deg) translateX(50%);
}

.cube::after {
transform: rotateX(90deg) translateY(50%);
}
```

Pyramid

A pyramid shape can be created using multiple triangles positioned in 3D space.

Example:

```css
/* Pyramid */
.pyramid {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
transform: rotateX(-30deg) rotateY(45deg);
transform-style: preserve-3d;
}
```

These examples show how to create various shapes using only CSS, without relying on images or
additional HTML elements.

KARAN NATH - E-BOOK 81


### Benefits of Using HOCs

1. **Code Reusability**: HOCs help avoid duplication by encapsulating common functionality in a


reusable function.
2. **Separation of Concerns**: They allow you to separate logic (e.g., authentication, data fetching) from
presentation components, leading to cleaner and more maintainable code.
3. **Composability**: Multiple HOCs can be composed together to add various pieces of functionality to a
single component.

### Considerations

1. **Avoid Overusing HOCs**: While powerful, excessive use of HOCs can lead to complex and hard-to-
maintain component trees. Use them judiciously and consider alternatives like React hooks for simpler
use cases.
2. **Naming Conventions**: Clearly name your HOCs to reflect their purpose (e.g., `withAuth`,
`withLogging`) to make your codebase easier to understand.

Higher-Order Components are a flexible and powerful way to enhance your React components with
additional functionality while keeping your code modular and reusable.

KARAN NATH - E-BOOK 82


Chapter 39: Columns

Simple Example (column-count)

The `column-count` property divides an element's content into a specified number of columns.

Example:

```css
/* Simple column count */
.container {
column-count: 3; /* Divides the content into 3 columns */
}
```

Column Width

The `column-width` property sets the ideal width of columns. The browser will determine how many
columns will fit based on this width.

Example:

```css
/* Column width */
.container {
column-width: 200px; /* Sets the column width to 200px */
}
```

By using `column-count` and `column-width`, you can easily create multi-column layouts that adapt to
different screen sizes and content lengths.

KARAN NATH - E-BOOK 83


Chapter 40: Multiple Columns

Create Multiple Columns

The `columns` shorthand property can be used to set both `column-count` and `column-width` at the
same time.

Example:

```css
/* Create multiple columns */
.container {
columns: 3 200px; /* Creates 3 columns with a minimum width of 200px each */
}
```

Basic Example

Using the `column-count` and `column-width` properties, you can create a flexible, multi-column layout.

Example:

```css
/* Basic example */
.container {
column-count: 3; /* Divides the content into 3 columns */
column-gap: 20px; /* Adds a 20px gap between columns */
}

.container-wide {
column-width: 200px; /* Sets the column width to 200px */
column-gap: 20px; /* Adds a 20px gap between columns */
}
```

The `column-gap` property allows you to set the space between columns, creating a clear separation and
improving readability.

KARAN NATH - E-BOOK 84


Chapter 41: Inline-Block Layout

Justified Navigation Bar

Using the `display: inline-block` property can help in creating a horizontal navigation bar where items are
justified and aligned.

Example:

```css
/* Justified navigation bar */
.navbar {
text-align: center; /* Centers the navigation bar items */
}

.navbar a {
display: inline-block; /* Aligns links horizontally */
padding: 10px 20px; /* Adds space around the links */
text-decoration: none; /* Removes underline from links */
color: black; /* Sets text color */
}

.navbar a:hover {
background-color: #f0f0f0; /* Changes background on hover */
}
```

In this example, `display: inline-block` ensures that the navigation items line up horizontally and are
responsive to padding and margins. Adjustments to `text-align` and `padding` help to center and space
out the navigation items.

KARAN NATH - E-BOOK 85


Chapter 42: Inheritance

Automatic Inheritance

CSS properties are inherited by default unless explicitly overridden. For example, text-related properties
such as `color`, `font-family`, and `font-size` are inherited by child elements.

Example:

```css
/* Automatic inheritance */
.parent {
color: blue; /* Sets text color */
font-family: Arial, sans-serif; /* Sets font family */
}

.child {
/* Inherits color and font-family from .parent */
}
```

In this example, the text color and font family of `.child` will automatically inherit those of `.parent` unless
specified otherwise.

Enforced Inheritance

To enforce inheritance for a property, use the `inherit` keyword.

Example:

```css
/* Enforced inheritance */
.parent {
color: blue;
}

.child {
color: inherit; /* Explicitly inherits color from .parent */
}
```

This ensures that `.child` will always use the `color` property value of its parent element, regardless of
any other styling rules.

KARAN NATH - E-BOOK 86


Chapter 43: CSS Image Sprites

A Basic Implementation

CSS image sprites combine multiple images into a single file, which can reduce the number of HTTP
requests for a web page. To use a sprite, you set the background image of an element and position it
using `background-position`.

Example:

```css
/* Basic sprite implementation */
.sprite {
background-image: url('sprites.png'); /* The image containing all the sprites */
width: 50px; /* Width of the sprite */
height: 50px; /* Height of the sprite */
background-repeat: no-repeat; /* Prevents repeating the background image */
}

.icon-home {
background-position: 0 0; /* Position of the home icon within the sprite */
}

.icon-settings {
background-position: -50px 0; /* Position of the settings icon within the sprite */
}
```

In this example, the `background-position` property is used to display the correct portion of the sprite
image for each icon. Adjust the `background-position` values to align the sprite correctly within the
element.

KARAN NATH - E-BOOK 87


Chapter 44: Clipping and Masking

Clipping and Masking: Overview and Difference

Clipping and masking are techniques used to control the visibility of an element, but they operate
differently:

- **Clipping** restricts the visibility of an element to a specific shape or path. It hides the parts of the
element that fall outside this shape.
- **Masking** allows for more complex shapes and gradients to be used, where the visibility of the
element can be controlled by a mask image or gradient.

Simple Mask That Fades an Image from Solid to Transparent

A simple mask can be created using the `mask-image` property with a linear gradient.

Example:

```css
/* Mask that fades an image */
.image {
width: 300px;
height: 200px;
background-image: url('image.jpg');
mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));
}
```
This CSS applies a gradient mask to an image, creating a fade effect from solid to transparent.

Clipping (Circle)

The `clip-path` property can create a circular clipping effect.

Example:

```css
/* Clipping with a circle */
.image {
width: 200px;
height: 200px;
background-image: url('image.jpg');
clip-path: circle(50%);
}
```

This example clips the image to a circular shape.

Clipping (Polygon)

The `clip-path` property can also use polygons to define complex clipping paths.

Example:

```css
/* Clipping with a polygon */
.image {
width: 300px;
height: 200px;
background-image: url('image.jpg');
clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
}
```

KARAN NATH - E-BOOK 88


This example clips the image into a diamond shape.

Using Masks to Cut a Hole in the Middle of an Image

Masks can be used to create a hole in the middle of an image.

Example:

```css
/* Mask with a hole in the middle */
.image {
width: 300px;
height: 200px;
background-image: url('image.jpg');
-webkit-mask-image: radial-gradient(circle, transparent 50px, black 51px);
mask-image: radial-gradient(circle, transparent 50px, black 51px);
}
```

This mask creates a circular hole in the middle of the image.

Using Masks to Create Images with Irregular Shapes

Complex shapes can be created using SVG masks or image masks.

Example:

```css
/* Using an SVG mask for irregular shapes */
.image {
width: 300px;
height: 200px;
background-image: url('image.jpg');
mask-image: url('mask.svg'); /* SVG mask file */
}
```

This example uses an SVG file to define a mask that applies an irregular shape to the image.

KARAN NATH - E-BOOK 89


Chapter 45: Fragmentation

Media Print Page-break

Fragmentation in CSS is used to control the way content is divided across different pages when printing.
The `page-break` properties are used to manage how content breaks between pages.

Example:

```css
/* Page break for printing */
@media print {
.page-break {
page-break-before: always; /* Inserts a page break before the element */
}

.no-break {
page-break-inside: avoid; /* Prevents a page break inside the element */
}

.avoid {
page-break-after: avoid; /* Prevents a page break after the element */
}
}
```

In this example:
- `page-break-before: always` ensures that a page break occurs before the element with the class `page-
break`.
- `page-break-inside: avoid` prevents a page break from occurring inside the element with the class `no-
break`.
- `page-break-after: avoid` prevents a page break from occurring immediately after the element with the
class `avoid`.

These properties help control the layout of printed documents by specifying where content should break
or avoid breaking between pages.

KARAN NATH - E-BOOK 90


Chapter 46: CSS Object Model (CSSOM)

Adding a Background-image Rule via the CSSOM

The CSS Object Model (CSSOM) allows for dynamic manipulation of CSS styles using JavaScript. You
can modify existing styles or add new ones to the stylesheet using the CSSOM.

Example:

```javascript
// Adding a background-image rule via CSSOM

// Select the stylesheet


let stylesheet = document.styleSheets[0];

// Create a new rule


let rule = 'background-image: url("image.jpg");';

// Add the rule to the stylesheet


stylesheet.insertRule(`.dynamic-background { ${rule} }`, stylesheet.cssRules.length);

// Apply the class to an element


document.querySelector('.element').classList.add('dynamic-background');
```

In this example:
- `document.styleSheets[0]` selects the first stylesheet on the page.
- `insertRule` adds a new CSS rule to the end of the stylesheet. The rule sets a background image for
elements with the class `dynamic-background`.
- The class is then applied to an element to show the background image.

This method allows for real-time changes to CSS properties, making it possible to update styles
dynamically based on user interactions or other conditions.

KARAN NATH - E-BOOK 91


Chapter 47: Feature Queries

Basic @supports Usage

Feature queries, using the `@supports` rule, enable you to apply CSS rules conditionally based on
whether the browser supports specific CSS features. This allows you to use advanced CSS properties
while maintaining compatibility with older browsers.

Example:

```css
/* Basic @supports usage */
@supports (display: grid) {
.container {
display: grid; /* Apply grid layout if supported */
grid-template-columns: repeat(3, 1fr); /* Define a 3-column grid */
}
}

@supports not (display: grid) {


.container {
display: flex; /* Fallback to flex layout if grid is not supported */
flex-direction: row;
}
}
```

In this example:
- The `@supports (display: grid)` rule applies the grid layout to `.container` only if the browser supports
CSS Grid.
- The `@supports not (display: grid)` rule provides a fallback using Flexbox if the browser does not
support Grid.

Chaining Feature Detections

You can chain multiple feature queries to check for a combination of features.

Example:
```css
/* Chaining feature detections */
@supports (display: grid) and (grid-template-columns: repeat(3, 1fr)) {
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Advanced grid layout */
}
}

@supports (display: grid) and not (grid-template-columns: repeat(3, 1fr)) {


.container {
display: grid;
grid-template-columns: 1fr 1fr; /* Fallback grid layout */
}
}
```

In this example:
- The first rule applies a more complex grid layout if the browser supports both CSS Grid and the specific
grid template.
- The second rule provides a simpler grid layout if the browser supports Grid but not the specified
template.

KARAN NATH - E-BOOK 92


Chapter 48: Stacking Context

Stacking Context

A stacking context is a three-dimensional concept in CSS that controls the layering of elements.
Elements in a stacking context are stacked according to their `z-index` values, relative to their parent
stacking context.

The `z-index` property determines the stacking order of positioned elements (those with `position` set to
`relative`, `absolute`, `fixed`, or `sticky`) within the same stacking context. Elements with a higher `z-
index` value appear in front of those with a lower value.

Example:

```css
/* Creating a stacking context */
.container {
position: relative;
z-index: 1; /* Creates a stacking context with z-index 1 */
}

.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 10; /* Stacks above other elements with lower z-index */
}

.content {
position: relative;
z-index: 5; /* Stacks above the container but below the overlay */
}
```

In this example:
- `.container` creates a stacking context with `z-index: 1`.
- `.overlay` is positioned absolutely and has a `z-index` of 10, so it appears on top of the `.container` and
`.content`.
- `.content` has a `z-index` of 5, so it appears above `.container` but below `.overlay`.

Understanding stacking contexts is crucial for managing complex layouts where elements overlap and
ensuring the correct layering order.

KARAN NATH - E-BOOK 93


Chapter 49: Block Formatting Contexts

Using the Overflow Property with a Value Different to visible

A Block Formatting Context (BFC) is an isolated rendering area where block-level elements are formatted.
It affects how elements are laid out and how their margins are handled, particularly in relation to floating
elements and margin collapsing.

Creating a new BFC can be useful for managing layout issues. One common way to create a BFC is by
setting the `overflow` property to a value other than `visible`.

Example:

```css
/* Creating a BFC */
.container {
overflow: hidden; /* Creates a new block formatting context */
background-color: #f0f0f0;
padding: 20px;
}

.child {
float: left; /* Floated element inside the BFC */
width: 200px;
height: 100px;
background-color: #c0c0c0;
}
```

In this example:
- The `.container` element creates a new BFC with `overflow: hidden`.
- The `.child` element is floated, but since it is inside a BFC, its margins will not collapse with other
elements outside of the `.container`.

Using `overflow: hidden`, `overflow: auto`, or `overflow: scroll` on an element will establish a new BFC,
helping to contain floats and manage layout issues effectively.

KARAN NATH - E-BOOK 94


Chapter 50: Vertical Centering

Centering with `display: table`

Using `display: table` and `display: table-cell` can help with vertical centering of content.

Example:

```css
/* Centering with display: table */
.container {
display: table; /* Creates a table context */
width: 100%;
height: 100vh; /* Full viewport height */
}

.centered {
display: table-cell; /* Acts like a table cell */
vertical-align: middle; /* Vertically centers content */
text-align: center; /* Horizontally centers text */
}
```

In this example:
- The `.container` acts as a table.
- The `.centered` element acts as a table cell, allowing its content to be centered both vertically and
horizontally.

Centering with Flexbox

Flexbox provides an easy way to center content both horizontally and vertically.

Example:

```css
/* Centering with flexbox */
.container {
display: flex;
justify-content: center; /* Horizontally centers content */
align-items: center; /* Vertically centers content */
height: 100vh; /* Full viewport height */
}

.centered {
width: 50%; /* Example width */
height: 50%; /* Example height */
background-color: #c0c0c0;
}
```

In this example:
- The `.container` uses Flexbox to center `.centered` both horizontally and vertically.

Centering with `transform`

Using CSS transforms to center an element involves setting its position to `absolute` or `fixed` and using
`transform` to adjust its position.

KARAN NATH - E-BOOK 95


Example:

```css
/* Centering with transform */
.container {
position: relative;
height: 100vh; /* Full viewport height */
}

.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* Moves the element back to center */
}
```

In this example:
- The `.centered` element is moved to the center of the `.container` using `transform: translate(-50%,
-50%)`.

Centering Text with Line Height

For single-line text, centering can be achieved by matching the `line-height` to the element's height.

Example:

```css
/* Centering text with line height */
.container {
height: 100px; /* Set height */
line-height: 100px; /* Match line-height to height */
text-align: center; /* Horizontally centers text */
}

.centered {
vertical-align: middle; /* Vertically aligns text */
}
```

In this example:
- The `.container`'s `line-height` matches its height, centering the text vertically.

Centering with `position: absolute`

Centering an element using `position: absolute` involves positioning it relative to its nearest positioned
ancestor.

Example:

```css
/* Centering with position: absolute */
.container {
position: relative;
height: 100vh; /* Full viewport height */
}

KARAN NATH - E-BOOK 96


.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* Moves the element back to center */
}
```

In this example:
- The `.centered` element is positioned in the center of the `.container` using `position: absolute` and
`transform`.

Centering with Pseudo Element

You can use pseudo-elements to center content, particularly for decorative purposes.

Example:

```css
/* Centering with pseudo-element */
.container {
position: relative;
height: 100vh; /* Full viewport height */
}

.container::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 100px; /* Example width */
height: 100px; /* Example height */
background-color: #c0c0c0;
transform: translate(-50%, -50%); /* Moves the pseudo-element back to center */
}
```

In this example:
- The `::before` pseudo-element is used to create a centered box inside the `.container`.

KARAN NATH - E-BOOK 97

You might also like