0% found this document useful (0 votes)
10 views

CSS Notes

CSS (Cascading Style Sheets) is a stylesheet language that controls the presentation and layout of HTML documents, promoting separation of concerns, reusability, consistency, and flexibility. It includes various types of CSS (inline, internal, external), selectors, properties, and methods for styling elements, backgrounds, borders, and dimensions. The document also covers CSS comments, color specifications, and the box model, providing a comprehensive overview of CSS fundamentals.

Uploaded by

toneh64272
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

CSS Notes

CSS (Cascading Style Sheets) is a stylesheet language that controls the presentation and layout of HTML documents, promoting separation of concerns, reusability, consistency, and flexibility. It includes various types of CSS (inline, internal, external), selectors, properties, and methods for styling elements, backgrounds, borders, and dimensions. The document also covers CSS comments, color specifications, and the box model, providing a comprehensive overview of CSS fundamentals.

Uploaded by

toneh64272
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 192

CSS Notes

CSS Notes
CSS (Cascading Style Sheets) -
Introduction
CSS (Cascading Style Sheets) -
Introduction
What is CSS?
CSS (Cascading Style Sheets) is a stylesheet language used to control the presentation and
layout of HTML documents.

Why Use CSS?

●​ Separation of Concerns: Keeps content (HTML) separate from presentation (CSS).


●​ Reusability: A single CSS file can style multiple pages.
●​ Consistency: Ensures uniform styling across a website.
●​ Flexibility: Allows easy changes in design without modifying HTML.

Types of CSS
1.​ Inline CSS (applies styles directly within an element)​

<p style="color: blue; font-size: 20px;">This is inline
CSS</p>

2.​ Internal CSS (written inside a <style> tag in the HTML <head>)​

<style>
p {
color: blue;
font-size: 20px;
}
</style>

3.​ External CSS (linked using a separate .css file)​


html​
<link rel="stylesheet" href="styles.css">

css​

​ p {
​ color: blue;
​ font-size: 20px;
}

CSS Selectors
●​ Element Selector: p { color: red; }
●​ Class Selector: .title { font-weight: bold; }
●​ ID Selector: #main { background-color: yellow; }
●​ Universal Selector: * { margin: 0; }
●​ Group Selector: h1, h2, p { font-family: Arial; }
●​ Attribute Selector: input[type="text"] { border: 1px solid gray; }

CSS Properties
●​ Text & Font Styling​
color, font-size, font-family, font-weight, text-align,
text-decoration
●​ Box Model​
margin, padding, border, width, height
●​ Backgrounds​
background-color, background-image, background-size
●​ Positioning​
position, display, float, flexbox, grid

CSS Box Model


Each element is treated as a rectangular box with:

1.​ Content: Actual text or image inside the element.


2.​ Padding: Space inside the border.
3.​ Border: The edge around the element.
4.​ Margin: Space outside the border.
CSS Selectors
CSS Selectors
CSS selectors are used to target HTML elements and apply styles to them.

1. Basic Selectors

(a) Universal Selector (*)

●​ Selects all elements on a page.

css

* {
margin: 0;
padding: 0;
}

(b) Element Selector

●​ Targets all instances of a specific HTML element.

css
p {
color: blue;
}

Applies to all <p> elements.

(c) Class Selector (.)

●​ Selects elements with a specific class.

css

.title {
font-size: 20px;
color: red;
}
Usage in HTML:

html

<p class="title">This is a styled paragraph.</p>

(d) ID Selector (#)

●​ Targets a specific element by its id.

css
#main {
background-color: yellow;
}

Usage in HTML:

html
<div id="main">Main Content</div>

2. Grouping and Combinators

(a) Group Selector (,)

●​ Applies the same style to multiple elements.

css

h1, h2, p {
font-family: Arial, sans-serif;
}

(b) Descendant Selector ( )

●​ Targets elements inside a specific parent.

css

div p {
color: green;
}
Applies to <p> inside <div>.

(c) Child Selector (>)

●​ Targets direct children only.

css

div > p {
font-weight: bold;
}

(d) Adjacent Sibling Selector (+)

●​ Selects the immediate next sibling.

css

h1 + p {
color: blue;
}

(e) General Sibling Selector (~)

●​ Selects all siblings after a specified element.

css

h1 ~ p {
font-style: italic;
}

3. Attribute Selectors
(a) Elements with a Specific Attribute
css

input[type="text"] {
border: 1px solid gray;
}
(b) Attribute Contains (*=)

●​ Selects elements with an attribute containing a specific value.

css

a[href*="example"] {
color: red;
}

(c) Attribute Starts With (^=)

●​ Selects elements whose attribute starts with a certain value.

css

a[href^="https"] {
color: green;
}

(d) Attribute Ends With ($=)

●​ Selects elements whose attribute ends with a certain value.

css

img[src$=".png"] {
border-radius: 10px;
}
CSS Comments
CSS Comments
What are CSS Comments?
CSS comments are used to add explanations or notes within the stylesheet. They help
developers understand the code better and make it easier to maintain.

Syntax of CSS Comments


●​ CSS comments start with /* and end with */.
●​ They can be placed anywhere in the stylesheet.
●​ Comments are ignored by the browser and do not affect the styling.

Example:
css

/* This is a single-line comment */


p {
color: blue; /* This comment is inside a rule */
}

/*
This is a multi-line comment
It can span multiple lines
*/
h1 {
font-size: 24px;
}

Why Use CSS Comments?


1.​ Improve Readability – Helps explain styles and why they are used.
2.​ Debugging – Temporarily disable styles by commenting them out.
3.​ Collaboration – Makes it easier for teams to understand the CSS.

Example: Commenting Out a Rule


css

/*
h2 {
color: red;
}
*/

This h2 rule will not be applied.


CSS Colors 🎨
CSS Colors 🎨
CSS provides various ways to specify colors for text, backgrounds, borders, and other
elements.

1. Ways to Define Colors in CSS


(a) Named Colors

CSS supports 140+ predefined colors, such as:

css

p {
color: red;
}

✅ Example colors: red, blue, green, yellow, black, white, purple,


orange

(b) HEX Color Codes

A hexadecimal value represents a color in RGB format.

css

p {
color: #ff5733; /* Red-Orange */
}

✅ Format: #RRGGBB (Each pair represents Red, Green, Blue).​


✅ Short HEX codes are also valid:
css

h1 {
color: #f06; /* Equivalent to #ff0066 */
}
(c) RGB Colors

RGB defines a color using Red, Green, and Blue values (0-255).

css

p {
color: rgb(255, 87, 51); /* Red-Orange */
}

(d) RGBA (RGB with Transparency)

A (Alpha) defines opacity (0 = fully transparent, 1 = fully opaque).

css

p {
color: rgba(255, 87, 51, 0.5); /* 50% transparent */
}

(e) HSL (Hue, Saturation, Lightness)

HSL defines colors using hue (0-360°), saturation (%), and lightness (%).

css

p {
color: hsl(15, 100%, 50%); /* Red-Orange */
}

(f) HSLA (HSL with Transparency)


css

p {
color: hsla(15, 100%, 50%, 0.5); /* 50% transparent */
}

2. Background Colors
You can apply colors to the background of elements.
css

body {
background-color: lightgray;
}

3. Border Colors
css

div {
border: 2px solid rgb(0, 128, 255); /* Blue border */
}

4. Opacity Property
●​ The opacity property makes an element semi-transparent.

css

div {
background-color: blue;
opacity: 0.5; /* 50% transparent */
}

5. Gradient Colors
(a) Linear Gradient
css

div {
background: linear-gradient(to right, red, yellow);
}

(b) Radial Gradient


css
div {
background: radial-gradient(circle, red, yellow);
}
CSS Backgrounds 🎨
CSS Backgrounds 🎨
CSS allows you to style the background of elements using various properties.

1. Background Color (background-color)


Defines the background color of an element.

css

body {
background-color: lightblue;
}

2. Background Image (background-image)


Sets an image as the background.

css

body {
background-image: url("background.jpg");
}

✅ Tips:
●​ Use an absolute URL (https://example.com/image.jpg) or relative URL
(images/bg.jpg).
●​ If the image does not load, the background-color (if defined) will be visible.

3. Background Repeat (background-repeat)


Controls how the background image repeats.

css
body {
background-image: url("pattern.png");
background-repeat: repeat; /* Default (Repeats both X &
Y) */
background-repeat: repeat-x; /* Repeats horizontally */
background-repeat: repeat-y; /* Repeats vertically */
background-repeat: no-repeat; /* No repeating */
}

4. Background Size (background-size)


Defines the size of the background image.

css

body {
background-image: url("image.jpg");
background-size: cover; /* Covers entire area */
background-size: contain; /* Fits inside the container */
background-size: 100px 50px; /* Custom width & height */
}

5. Background Position (background-position)


Controls the starting position of the background image.

css

body {
background-image: url("image.jpg");
background-position: top left;
background-position: center center;
background-position: 50% 50%;
}
6. Background Attachment (background-attachment)
Defines whether the background image scrolls with the page or stays fixed.

css

body {
background-image: url("image.jpg");
background-attachment: fixed; /* Background stays fixed */
background-attachment: scroll; /* Background moves with
the page */
}

7. Background Gradient (background:


linear-gradient())

(a) Linear Gradient


css

div {
background: linear-gradient(to right, red, yellow);
}

(b) Radial Gradient


css

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

8. Background Shorthand Property


You can define multiple background properties in a single line.

css

body {
background: url("image.jpg") no-repeat center center /
cover fixed;
}

📌 Format:​
background: [image] [repeat] [position] / [size] [attachment];
CSS Borders 🖼️
CSS Borders 🖼️
CSS borders allow you to define a frame around an element.

1. Border Syntax
The border property is a shorthand for:

●​ border-width (Thickness of the border)


●​ border-style (Type of border)
●​ border-color (Color of the border)

Example:
css

div {
border: 2px solid red;
}

✅ Equivalent to:
css

div {
border-width: 2px;
border-style: solid;
border-color: red;
}

2. Border Styles (border-style)


The border-style property defines the appearance of the border.

Style Example
Name
solid border: 3px solid
black;

dashed border: 3px dashed


blue;

dotted border: 3px dotted


red;

double border: 4px double


green;

groove border: 4px groove


purple;

ridge border: 4px ridge


orange;

inset border: 4px inset


gray;

outset border: 4px outset


brown;

none border: none;

hidden border: hidden;

Example:
css

p {
border: 4px dotted blue;
}

3. Border Width (border-width)


Specifies the thickness of the border in px, em, rem, etc.

css

div {
border-width: 5px;
border-style: solid;
}

✅ Different width for each side:


css

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

4. Border Color (border-color)


Specifies the color of the border.

css

h1 {
border: 3px solid rgb(0, 128, 255);
}

✅ Different colors for each side:


css

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

5. Border Radius (border-radius)


The border-radius property creates rounded corners.
Example:
css

div {
border: 3px solid black;
border-radius: 10px;
}

✅ Perfect Circle:
css

div {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: lightblue;
}

✅ Different Radius for Each Corner:


css

div {
border-radius: 10px 20px 30px 40px; /* top-left,
top-right, bottom-right, bottom-left */
}

6. Individual Borders
You can set different styles, colors, and widths for each side.

css

div {
border-top: 5px solid red;
border-right: 3px dashed blue;
border-bottom: 4px double green;
border-left: 2px dotted orange;
}
7. Border Shorthand
You can define all properties in one line.

css

div {
border: 3px solid red;
}

✅ Using Multiple Values


css

div {
border: 5px dashed blue;
border-radius: 15px;
}
CSS Height & Width 📏
CSS Height & Width 📏
CSS provides properties to control the height and width of elements.

1. Width (width)
The width property sets the horizontal size of an element.

Example:
css

div {
width: 200px;
background-color: lightblue;
}

✅ Common Units for Width:


●​ Pixels (px) → width: 300px;
●​ Percentage (%) → width: 50%; (Relative to the parent element)
●​ View Width (vw) → width: 50vw; (50% of the viewport width)
●​ Auto (auto) → Adjusts based on content

Min & Max Width → Prevents extreme sizing​


css​

div {
min-width: 100px;
max-width: 500px;
}

●​

2. Height (height)
The height property sets the vertical size of an element.
Example:
css

div {
height: 100px;
background-color: lightgreen;
}

✅ Common Units for Height:


●​ Pixels (px) → height: 150px;
●​ Percentage (%) → height: 80%; (Relative to the parent element)
●​ View Height (vh) → height: 50vh; (50% of the viewport height)
●​ Auto (auto) → Adjusts based on content

Min & Max Height → Restricts size​


css​

div {
min-height: 50px;
max-height: 400px;
}

●​

3. Full-Screen Element
You can make an element cover the full screen:

css

div {
width: 100vw; /* Full viewport width */
height: 100vh; /* Full viewport height */
background-color: gray;
}

4. Overflow (overflow)
Controls content that exceeds the height/width.

Property Description

visible Default; content overflows

hidden Hides overflow content

scroll Adds scrollbars

auto Adds scrollbars if needed


css

div {
width: 200px;
height: 100px;
overflow: auto;
}

5. Box Sizing (box-sizing)


Defines how width & height are calculated.

Property Description

content-box Default; width/height excludes padding &


border

border-box Width/height includes padding & border


css

div {
width: 300px;
height: 150px;
padding: 20px;
box-sizing: border-box;
}
CSS Margin & Padding 📏
CSS Margin & Padding 📏
Margins and padding are used for spacing in CSS.

1. Margin (margin)
The margin property controls the space outside an element.

Example:
css

div {
margin: 20px;
background-color: lightblue;
}

✅ Different Ways to Set Margin:


●​ Single Value → margin: 20px; (All sides equal)
●​ Two Values → margin: 10px 20px; (Top/Bottom, Left/Right)
●​ Three Values → margin: 10px 20px 30px; (Top, Left/Right, Bottom)
●​ Four Values → margin: 10px 15px 20px 25px; (Top, Right, Bottom, Left)

✅ Individual Margin Sides:


css

margin-top: 10px;
margin-right: 15px;
margin-bottom: 20px;
margin-left: 25px;

✅ Auto Centering:
css

div {
width: 50%;
margin: auto;
}

📌 margin: auto; centers the element horizontally if it has a fixed width.

2. Padding (padding)
The padding property controls the space inside an element, between content and border.

Example:
css

div {
padding: 20px;
background-color: lightgreen;
}

✅ Different Ways to Set Padding:


●​ Single Value → padding: 20px; (All sides equal)
●​ Two Values → padding: 10px 20px; (Top/Bottom, Left/Right)
●​ Three Values → padding: 10px 20px 30px; (Top, Left/Right, Bottom)
●​ Four Values → padding: 10px 15px 20px 25px; (Top, Right, Bottom, Left)

✅ Individual Padding Sides:


css

padding-top: 10px;
padding-right: 15px;
padding-bottom: 20px;
padding-left: 25px;

3. Difference Between Margin & Padding


Property What It Does

Margin Creates space outside the element (pushes away from


neighbors)
Padding Creates space inside the element (pushes content inward)

Example with Both:

css

div {
margin: 20px;
padding: 15px;
background-color: lightgray;
}

4. Box Sizing & Padding


By default, padding increases the total width/height of an element.

🔹 Default (content-box)
css

div {
width: 200px;
padding: 20px; /* Total width = 200px + 20px + 20px =
240px */
}

🔹 Fix It with border-box


css

div {
width: 200px;
padding: 20px;
box-sizing: border-box; /* Keeps width = 200px */
}
CSS Box Model Components
CSS Box Model Components

Every HTML element is a rectangular box, and the box model consists of four main parts:

1.​ Content
○​ The actual text, image, or other elements inside the box.
○​ width and height define the size of the content area.
2.​ Padding
○​ The space between the content and the border.
○​ padding: 10px; adds 10px of space on all sides.
○​ Can have different values for top, right, bottom, and left.
3.​ Border
○​ A line around the padding (if any) and content.
○​ border: 2px solid black; creates a solid black border of 2px.
○​ Can be styled (solid, dashed, double, etc.).
4.​ Margin
○​ The space outside the border, separating it from other elements.
○​ margin: 20px; adds 20px of space around the element.
○​ Can also be set individually for top, right, bottom, and left.

Box Sizing

●​ By default, width and height apply only to the content area.


●​ Use box-sizing: border-box; to include padding and border in the total
width/height.

Example Code
css
.box {
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid blue;
margin: 15px;
box-sizing: border-box;
}
CSS Text Properties
CSS Text Properties

1. Text Color & Alignment

●​ color: red; → Sets text color.


●​ text-align: center; → Aligns text (left, right, center, justify).

2. Text Decoration & Transform

●​ text-decoration: underline; → Adds an underline (also none, overline,


line-through).
●​ text-transform: uppercase; → Changes text case (lowercase,
capitalize).

3. Text Spacing

●​ letter-spacing: 2px; → Controls space between letters.


●​ word-spacing: 5px; → Controls space between words.
●​ line-height: 1.5; → Adjusts spacing between lines.

4. Text Shadow

●​ text-shadow: 2px 2px 5px gray; → Adds shadow (x-offset, y-offset,


blur-radius, color).

5. Font Styling

●​ font-family: Arial, sans-serif; → Sets font.


●​ font-size: 16px; → Defines text size (use px, em, %, rem).
●​ font-weight: bold; → Controls boldness (normal, bold, lighter, bolder,
or values like 400, 700).
●​ font-style: italic; → Changes style (normal, italic, oblique).

Example Code
css

p {
color: #333;
text-align: justify;
font-family: 'Verdana', sans-serif;
font-size: 18px;
line-height: 1.6;
text-shadow: 1px 1px 3px gray;
}
CSS Links Styling - Quick Notes
CSS Links Styling - Quick Notes

Links (<a> tags) have different states that can be styled using CSS:

1. Link States
css
a:link { color: blue; } /* Unvisited link */
a:visited { color: purple; } /* Visited link */
a:hover { color: red; } /* When the mouse hovers over */
a:active { color: green; } /* When clicked */

2. Removing Underline
css
a {
text-decoration: none; /* Removes underline */
}

3. Adding Hover Effects


css
a:hover {
color: orange;
text-decoration: underline;
font-weight: bold;
}

4. Styling Buttons as Links


css
a {
display: inline-block;
padding: 10px 20px;
background: blue;
color: white;
text-decoration: none;
border-radius: 5px;
}

a:hover {
background: darkblue;
}
CSS Fonts - Quick Notes
CSS Fonts - Quick Notes

Fonts in CSS control how text appears on a webpage.

1. Font Family

Defines the typeface used for text.

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

Use fallback fonts in case the preferred one isn’t available:​


css​
CopyEdit​
font-family: "Times New Roman", Times, serif;

2. Font Size

Controls the size of the text.

p {
font-size: 16px; /* Fixed size */
font-size: 1.2em; /* Relative size */
font-size: 120%; /* Percentage */
}

●​ Recommended Units:
○​ px (pixels) → Fixed size
○​ em / rem → Relative to parent/root element
○​ % → Percentage of parent

3. Font Weight

Controls boldness.
p {
font-weight: normal; /* Default */
font-weight: bold; /* Bold */
font-weight: 300; /* Thin */
font-weight: 700; /* Extra Bold */
}

4. Font Style

Changes text appearance.

css
p {
font-style: normal; /* Default */
font-style: italic; /* Italic text */
font-style: oblique; /* Slanted text */
}

5. Font Variant

Used for small caps.

css
p {
font-variant: small-caps;
}

6. Google Fonts (Custom Fonts)

To use custom fonts from Google Fonts:

1.​ Add this inside <head>:​


html​
<link
href="https://fonts.googleapis.com/css2?family=Poppins:wght@30
0;600&display=swap" rel="stylesheet">
2.​ Use in CSS:​
css​
CopyEdit​
p {
font-family: 'Poppins', sans-serif;
}

7. Shorthand Property (font)

You can set multiple properties in one line:

p {
font: italic bold 20px/1.5 "Arial", sans-serif;
}
/* font-style | font-weight | font-size/line-height |
font-family */
CSS Units - Quick Notes
CSS Units - Quick Notes

CSS units define measurements like width, height, font size, margins, etc. They are
categorized into absolute and relative units.

1. Absolute Units (Fixed Size)


These units have a fixed size and do not change based on screen size.

Unit Description

px Pixels (Most commonly used)

cm Centimeters

mm Millimeters

in Inches (1in = 96px)

pt Points (1pt = 1/72 inch)

pc Picas (1pc = 12pt)

🔹 Example:
div {
width: 200px;
height: 100px;
}

2. Relative Units (Flexible & Responsive)


These units adjust based on parent elements or viewport size.

Unit Description

% Percentage of parent element

em Relative to parent’s font size (1em = parent’s


font-size)
rem Relative to root (html) font size (default 16px)

vw Viewport width (1vw = 1% of screen width)

vh Viewport height (1vh = 1% of screen height)

vmi Smaller of vw or vh
n

vma Larger of vw or vh
x

🔹 Example:
p {
font-size: 1.5em; /* 1.5 times parent font size */
}

.container {
width: 50%; /* Half of the parent element */
}

.hero {
width: 100vw; /* Full viewport width */
height: 100vh; /* Full viewport height */
}

3. CSS Grid & Flexbox Units


●​ fr → Fraction of available space (used in CSS Grid)
●​ auto → Automatically adjusts based on content

🔹 Example:
.grid {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* 3 columns, middle one
is twice as big */
}
Best Practices for Choosing Units

✔ Use px for precise control (e.g., borders, images).​


✔ Use rem for consistent font sizes.​
✔ Use % for fluid layouts.​
✔ Use vw/vh for full-screen sections.​
✔ Use fr for grid-based layouts.
CSS Cursor Property - Quick Notes
CSS Cursor Property - Quick Notes

The cursor property changes the appearance of the mouse pointer when hovering over an
element.

1. Default Cursors
Cursor Description Example

default The system default cursor 🔹


pointer A hand icon (for links, buttons) 👉
text A text selection cursor (I-beam) 📝
crosshair A crosshair cursor ➕
move A move cursor (for drag-and-drop) ⬍

not-allow A blocked cursor 🚫


ed

🔹 Example:
button {
cursor: pointer; /* Changes to a hand icon */
}

2. Resize Cursors
Cursor Description Example

ew-resize Left-right arrow ↔

ns-resize Up-down arrow ↕

nesw-resi Diagonal arrow (↘↖) ↘


ze

nwse-resi Diagonal arrow (↙↗) ↙


ze
🔹 Example:
.resizable {
cursor: ew-resize; /* Left-right resize */
}

3. Drag & Drop Cursors


Cursor Description Example

grab Open hand ✋


grabbi Closed hand ✊
ng

copy Shows copy cursor 📋


alias Shows an alias 🔗
(shortcut)

🔹 Example:
.draggable {
cursor: grab;
}
.draggable:active {
cursor: grabbing;
}

4. Custom Cursor (Using Images)

You can set a custom image as a cursor:

.custom-cursor {
cursor: url('cursor.png'), auto;
}

●​ The second value (auto) is a fallback in case the image fails to load.
Best Practices

✔ Use pointer for buttons and links.​


✔ Use not-allowed for disabled elements.​
✔ Use move for draggable elements.​
✔ Keep custom cursors lightweight for better performance.
CSS !important
CSS !important - Quick Notes

The !important rule overrides all other CSS rules, including inline styles and styles with
higher specificity.

1. How to Use !important

p {
color: red !important; /* This will override all other
color rules */
}

Even if another rule has higher specificity, !important will take precedence:

p {
color: blue; /* This will be ignored */
}

2. Overriding Inline Styles

Normally, inline styles (style="") have the highest priority:

html
CopyEdit
<p style="color: green;">Hello</p>

But using !important in CSS:

p {
color: red !important; /* Will override inline color */
}

3. When to Use !important


✔ To force a style when working with third-party stylesheets.​
✔ To override inline styles in dynamically generated content.​
✔ To debug CSS issues quickly.

4. When NOT to Use !important

❌ Overusing !important makes styles hard to maintain.​


❌ It breaks the natural CSS hierarchy (specificity).​
❌ Makes debugging difficult when multiple !important rules exist.

5. How to Override !important

If two rules have !important, the one with higher specificity wins:

p { color: blue !important; } /* Lower specificity */


#special { color: green !important; } /* Higher specificity -
this wins */

🔹 Best Fix: Instead of !important, increase specificity or adjust styles properly.

Best Practice

🚀 Use !important only as a last resort. Try restructuring your CSS before using it.
CSS box-shadow - Quick Notes
CSS box-shadow - Quick Notes

The box-shadow property adds a shadow effect around an element.

1. Basic Syntax

box-shadow: offset-x offset-y blur-radius spread-radius color;

●​ offset-x → Horizontal shadow position (+right, -left)


●​ offset-y → Vertical shadow position (+down, -up)
●​ blur-radius → How soft the shadow is (higher = softer)
●​ spread-radius → Expands or contracts the shadow
●​ color → Shadow color

2. Basic Example

.box {
width: 200px;
height: 100px;
background: lightblue;
box-shadow: 5px 5px 10px gray;
}

🔹 This adds a gray shadow that is 5px right, 5px down, with a 10px blur.

3. Adding a Spread Effect

box-shadow: 5px 5px 10px 5px rgba(0, 0, 0, 0.5);

●​ The last 5px spreads the shadow outward.


●​ rgba(0,0,0,0.5) makes the shadow semi-transparent.

4. Inner Shadow (inset)


box-shadow: inset 3px 3px 10px rgba(0, 0, 0, 0.5);

●​ Adds a shadow inside the element.


●​ Gives a pressed or embossed effect.

5. Multiple Shadows

box-shadow: 3px 3px 5px red, -3px -3px 5px blue;

●​ Creates two shadows (one red, one blue).

6. Removing the Shadow on Hover

.box:hover {
box-shadow: none;
}

Best Practices

✔ Use subtle shadows (rgba for transparency).​


✔ Avoid overusing large shadows (can look unnatural).​
✔ Use inset shadows for 3D button effects.
CSS opacity - Quick Notes
CSS opacity - Quick Notes

The opacity property controls the transparency of an element.

1. Basic Syntax

element {
opacity: value;
}

●​ 0 → Fully transparent (invisible)


●​ 1 → Fully visible (default)
●​ Values between 0 and 1 create semi-transparent effects

2. Example: Transparent Box

.box {
width: 200px;
height: 100px;
background: blue;
opacity: 0.5; /* 50% transparent */
}

3. Hover Effect

Make an element fade in/out on hover:

button {
background: green;
opacity: 0.7;
transition: opacity 0.3s;
}

button:hover {
opacity: 1; /* Fully visible on hover */
}

4. Opacity & Child Elements

🔹 opacity affects the entire element, including text and child elements.
.parent {
background: red;
opacity: 0.5;
}

💡 Fix: Use rgba() for background transparency instead:


.parent {
background: rgba(255, 0, 0, 0.5); /* Red with 50%
transparency */
}

This keeps child elements fully visible.

5. Fading Effect with Keyframes

Create a fade-in animation:

@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}

.box {
animation: fadeIn 2s ease-in-out;
}

Best Practices
✔ Use opacity for smooth transitions & overlays.​
✔ Use rgba() for transparent backgrounds (without affecting children).​
✔ Combine with transition for smooth hover effects.
CSS filter Property - Quick Notes
CSS filter Property - Quick Notes

The filter property applies visual effects like blur, brightness, contrast, grayscale, etc.,
to an element (commonly used for images).

1. Basic Syntax

element {
filter: effect(value);
}

●​ You can apply multiple filters by separating them with spaces.

2. Common Filter Functions


Filter Description Example

blur(px) Blurs the element blur(5px)

brightness(% Adjusts brightness brightness(15


) 0%)

contrast(%) Adjusts contrast contrast(200%


)

grayscale(%) Converts to grayscale grayscale(100


%)

invert(%) Inverts colors invert(100%)

opacity(%) Adjusts transparency opacity(50%)

saturate(%) Adjusts color intensity saturate(300%


)

sepia(%) Adds a sepia tone sepia(80%)

hue-rotate(d Rotates colors hue-rotate(90


eg) deg)
3. Example Usage

img {
filter: grayscale(100%) brightness(120%);
}

🔹 This makes the image grayscale and increases brightness by 20%.

4. Hover Effect

Apply a filter on hover:

img {
filter: grayscale(100%);
transition: filter 0.5s;
}

img:hover {
filter: none; /* Removes filter on hover */
}

🔹 The image starts in grayscale and returns to normal on hover.

5. Applying Filters to Backgrounds

.bg {
background: url('image.jpg');
filter: blur(10px);
}

⚠ Note: filter only works on elements, not background images directly. A workaround is
using pseudo-elements (::before).

6. Using backdrop-filter (For Background Blur)


To blur the background while keeping the element sharp:

.blur-box {
background: rgba(255, 255, 255, 0.3);
backdrop-filter: blur(10px);
}

🔹 This creates a frosted glass effect.

Best Practices

✔ Use filter for cool effects on images, videos, and text.​


✔ Use backdrop-filter for modern UI designs (like glassmorphism).​
✔ Combine with transition for smooth effects.
CSS Gradients - Quick Notes
CSS Gradients - Quick Notes

Gradients in CSS allow you to create smooth transitions between multiple colors. There are
three main types:

1.​ Linear Gradient (Straight-line transition)


2.​ Radial Gradient (Circular transition)
3.​ Conic Gradient (Rotational transition)

1. Linear Gradient
A linear gradient transitions between colors along a straight line.

Basic Syntax:

background: linear-gradient(direction, color1, color2, ...);

Example: Top to Bottom (Default)

div {
background: linear-gradient(red, blue);
}

🔹 Default direction is top to bottom.


Example: Left to Right

div {
background: linear-gradient(to right, red, blue);
}

Example: Diagonal Gradient

div {
background: linear-gradient(to bottom right, red, yellow,
blue);
}
Using Angles

You can define an angle instead of using to keywords:

background: linear-gradient(45deg, red, yellow);

🔹 0deg is top to bottom, 90deg is left to right.

2. Radial Gradient
A radial gradient spreads outward from a central point.

Basic Syntax:

background: radial-gradient(shape size at position, color1,


color2, ...);

Example: Default Circle Gradient

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

🔹 Defaults to a circle centered in the element.


Example: Ellipse Shape

background: radial-gradient(ellipse, red, yellow, blue);

Example: Gradient Starting at a Specific Position


Best Practices

✔ Use linear-gradient for backgrounds & overlays.​


✔ Use radial-gradient for spotlight effects.

CopyEdit
background: radial-gradient(circle at top left, red, blue);

🔹 Moves the center of the gradient to the top-left.


CSS overflow Property - Quick Notes
CSS overflow Property - Quick Notes

The overflow property controls what happens when content exceeds the size of its
container.

1. Basic Syntax

element {
overflow: value;
}

2. Overflow Values & Examples

🔹 overflow: visible (Default)


Content overflows the container (no clipping).

.box {
width: 200px;
height: 100px;
overflow: visible;
}

🔹 Not recommended for controlled layouts.

🔹 overflow: hidden
Hides content that overflows the container.

.box {
width: 200px;
height: 100px;
overflow: hidden;
}
🔹 Useful for clipping content (e.g., images, animations).

🔹 overflow: scroll
Always adds a scrollbar, even if not needed.

.box {
width: 200px;
height: 100px;
overflow: scroll;
}

🔹 Not recommended unless you always want scrollbars.

🔹 overflow: auto
Adds a scrollbar only when needed.

.box {
width: 200px;
height: 100px;
overflow: auto;
}

🔹 Best choice for dynamic content.

3. Overflow in One Direction


You can control overflow separately for X and Y axes.css

Property Description
CopyEdit
overflow Controls horizontal overflow
.box {
-x
width: 200px;
overflow Controls vertical overflow height: 100px;
-y overflow-x: scroll;
overflow-y: hidden;
}

🔹 This allows horizontal scrolling but hides vertical overflow.

4. overflow: clip (New in CSS)


Clips content without scrolling (similar to hidden but stricter).

.box {
overflow: clip;
}

🔹 More efficient than hidden, as it prevents scrolling entirely.

5. Overflow & text-overflow


If text overflows, use text-overflow to show ellipsis (...).

.text-box {
width: 150px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

🔹 Ensures text doesn’t break onto multiple lines.


Best Practices
✔ Use overflow: auto for dynamic content.​
✔ Use overflow: hidden to hide extra content cleanly.​
✔ Use text-overflow: ellipsis for truncated text.
CSS Resizable Property ✨
CSS Resizable Property ✨
The resize property allows users to resize an element (like a <div> or <textarea>) by
dragging its edges.

1. Basic Syntax

element {
resize: value;
overflow: auto; /* Required for resizing to work */
}

✅ Example:
.resizable-box {
width: 200px;
height: 100px;
border: 2px solid black;
resize: both;
overflow: auto;
}

<div class="resizable-box">
Resize me!
</div>

2. Resize Property Values


Value Description

none Default; cannot be resized.

both Resizable in both horizontal and vertical directions.


horizont Resizable only left or right.
al

vertical Resizable only up or down.

block Resizable vertically in block-level elements.

inline Resizable horizontally in inline elements.

✅ Example: Horizontal & Vertical Resize


.horizontal {
resize: horizontal;
overflow: auto;
}

.vertical {
resize: vertical;
overflow: auto;
}

3. Resizable Textarea

textarea {
width: 300px;
height: 100px;
resize: both; /* Can resize in any direction */
}

<textarea>Try resizing me!</textarea>

📌 Disable Resizing
textarea {
resize: none;
}
4. Controlling Maximum & Minimum Resize
You can set min-width, max-width, min-height, and max-height to control the
resizing limits.

✅ Example:
.resizable-box {
width: 200px;
height: 100px;
resize: both;
overflow: auto;
min-width: 150px;
max-width: 400px;
min-height: 80px;
max-height: 250px;
}
CSS Lists 📝
CSS Lists 📝
CSS provides various styling options for lists, including bullets, numbering, spacing, and
custom designs.

1. Types of Lists in HTML


●​ Ordered List (<ol>) → Numbered list (1, 2, 3, …)
●​ Unordered List (<ul>) → Bulleted list (●, ○, ■, …)
●​ Description List (<dl>) → Term-definition list

2. Styling List Items (list-style-type)


The list-style-type property controls the bullet or numbering style.

🔹 Unordered List (<ul>) Styles


ul {
list-style-type: disc; /* Default */
}

Value Description

disc ● Filled circle (default)

circl ○ Hollow circle


e

squar ■ Filled square


e

none ❌ No bullets
✅ Example
ul {
list-style-type: square;
}

🔹 Ordered List (<ol>) Styles


ol {
list-style-type: decimal; /* Default */
}

Value Description

decimal 1, 2, 3, … (default)

decimal-leading- 01, 02, 03, …


zero

lower-roman i, ii, iii, iv, …

upper-roman I, II, III, IV, …

lower-alpha a, b, c, d, …

upper-alpha A, B, C, D, …

✅ Example
ol {
list-style-type: upper-roman;
}

3. Removing Default List Styling

ul, ol {
list-style: none;
}

4. Custom Bullet Images (list-style-image)


You can use an image instead of bullets.

✅ Example
ul {
list-style-image: url('bullet.png');
}

5. Positioning Bullets (list-style-position)


Determines whether bullets appear inside or outside the list item.

Value Description

insid Bullets align with text


e

outsi Bullets stay outside


de (default)

✅ Example
ul {
list-style-position: inside;
}

6. Shorthand Property (list-style)

ul {
list-style: square inside;
}

🔹 Equivalent to:
ul {
list-style-type: square;
list-style-position: inside;
}
CSS Tables 📊
CSS Tables 📊
CSS provides various ways to style HTML tables for better readability and appearance.

1. Basic Table Styling

table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 10px;
text-align: left;
}

✅ Explanation:
●​ width: 100%; → Makes the table take full width.
●​ border-collapse: collapse; → Merges borders for a clean look.
●​ padding: 10px; → Adds space inside cells.
●​ text-align: left; → Aligns text in cells.

✅ Example Table:
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Alice</td>
<td>25</td>
</tr>
</table>
2. Table Borders (border)
You can customize border style, width, and color.

✅ Example:
table, th, td {
border: 2px solid blue;
}

🔹 Different Border Styles:


table {
border: 2px dashed red; /* dashed, dotted, double, solid */
}

3. Adding Space (border-spacing)


Controls spacing between table cells when border-collapse: separate; is used.

✅ Example:
table {
border-collapse: separate;
border-spacing: 10px;
}

4. Table Header Styling

th {
background-color: #4CAF50;
color: white;
padding: 15px;
}
5. Striped Rows (nth-child)
Alternating row colors improve readability.

✅ Example:
tr:nth-child(even) {
background-color: #f2f2f2;
}

6. Hover Effect on Rows

tr:hover {
background-color: yellow;
}

7. Fixing Table Header (position: sticky)


Keeps the header visible while scrolling.

✅ Example:
th {
position: sticky;
top: 0;
background-color: #333;
color: white;
}

8. Full-Width Responsive Table


Make tables responsive by adding overflow: auto;.

✅ Example:
.table-container {
overflow-x: auto;
}

<div class="table-container">
<table>
<!-- Table content here -->
</table>
</div>
CSS Functions 🎨
CSS Functions 🎨
CSS functions help perform calculations, manipulate colors, and dynamically adjust styles.

1. calc() – Perform Calculations 🧮


Used to calculate dynamic values like width, height, margins, etc.

✅ Example:
div {
width: calc(100% - 50px); /* Subtracts 50px from full width */
height: calc(50vh + 20px); /* Half the viewport height plus 20px
*/
}

🔹 Operations Allowed: +, -, *, /

2. var() – CSS Variables 🌿


Stores reusable values.

✅ Example:
:root {
--primary-color: blue;
--padding-size: 10px;
}

div {
background-color: var(--primary-color);
padding: var(--padding-size);
}
3.url() – Load External Resources 🌐
Loads images and other assets.

✅ Example:
div {
background-image: url('image.jpg');
}

4. min() & max() – Flexible Sizing 📏


Sets values based on the smallest/largest possible size.

✅ Example:
div {
width: min(50vw, 500px); /* Takes the smaller value */
height: max(200px, 10vh); /* Takes the larger value */
}
CSS Box Sizing 📦
CSS Box Sizing 📦
The box-sizing property controls how the width and height of an element are calculated. It
helps prevent unexpected layout shifts due to padding and borders.

1. Default Behavior (content-box)


By default, CSS calculates width & height based only on content size, ignoring padding
and borders.

✅ Example:
.box {
width: 200px;
padding: 20px;
border: 5px solid black;
}

💡 Actual size = 200px (content) + 40px (padding) + 10px (border) = 250px total width

2. border-box – More Predictable Layout 📏


With box-sizing: border-box;, the width includes padding and border.

✅ Example:
.box {
width: 200px;
padding: 20px;
border: 5px solid black;
box-sizing: border-box;
}

💡 Total width remains 200px (content + padding + border).


✔️ No unexpected size increase!

3. Applying to All Elements (*)


It's common to apply border-box globally for a consistent layout.

✅ Best Practice:
* {
box-sizing: border-box;
}

4. Comparison: content-box vs border-box


Property content-box border-box
(Default)

Width Calculation Content only Content + Padding + Border

Requires Manual Fix? ✅ Yes ❌ No


Prevents Overflow? ❌ No ✅ Yes

5. When to Use box-sizing: border-box;?


✅ When working with fixed layouts​
✅ When dealing with responsive designs​
✅ When using padding and borders extensively
CSS initial vs inherit 🎨
CSS initial vs inherit 🎨
CSS provides initial and inherit values to control how properties are applied to
elements.

1. initial – Resets to Default Value 🔄


The initial keyword resets a property to its default browser value (not inherited from
the parent).

✅ Example:
p {
color: red;
}

span {
color: initial; /* Resets to browser's default (usually black)
*/
}

💡 Result:
●​ <p> text = Red
●​ <span> text = Default black (not inherited)

✅ Use initial when:


●​ You want to reset a property to its browser default.
●​ You don’t want the inherited value.

2. inherit – Takes Parent’s Value 📌


The inherit keyword forces an element to take the same property value as its parent.

✅ Example:
div {
color: blue;
}

p {
color: inherit; /* Takes color from <div> */
}

💡 Result:
●​ <p> inside <div> will be blue.

✅ Use inherit when:


●​ You want child elements to follow the parent’s style.
●​ You override non-inherited properties like border, padding, etc.

3. initial vs inherit – Quick Comparison 📊


Feature initial inherit

Effect Resets to browser Takes parent's value


default

Common Use Reset styles Maintain consistency

Works on Inherited Properties? ✅ Yes ✅ Yes


Works on Non-Inherited ✅ Yes ❌ No (unless explicitly
Properties? set)

4. unset – A Combination of Both 🌀


●​ Acts like inherit for inherited properties (e.g., color, font).
●​ Acts like initial for non-inherited properties (e.g., margin, border).

✅ Example:
p {
color: unset; /* Will inherit from parent */
border: unset; /* Will reset to default (no border) */
}
CSS object-fit Property 🖼️
CSS object-fit Property 🖼️
The object-fit property controls how an <img> or <video> fits inside its container,
maintaining aspect ratio without distortion.

1. Syntax 📌
img {
object-fit: value;
}

2. Values of object-fit 🎨
🔹 fill (Default) – Stretches to Fit
✅ The image stretches to fill the container (can distort).
img {
object-fit: fill;
}

💡 Use when exact dimensions are required, but distortion is acceptable.

🔹 contain – Fits Without Cropping


✅ The image resizes to fit inside the container while maintaining aspect ratio.​
✅ No cropping, but may leave empty space.
img {
object-fit: contain;
}
💡 Use when you need the full image visible inside the container.

🔹 cover – Fills Container Without Distortion


✅ The image scales and crops to fill the container while maintaining aspect ratio.​
✅ No stretching, but parts of the image may be cropped.
img {
object-fit: cover;
}

💡 Best for backgrounds, profile pictures, or full-width images.

🔹 none – Original Size, No Resizing


✅ The image doesn’t scale or crop and may overflow the container.
img {
object-fit: none;
}

💡 Use when exact image dimensions matter.

🔹 scale-down – Chooses the Smallest Size


✅ Behaves like none or contain, whichever makes the image smaller.
img {
object-fit: scale-down;
}

💡 Useful when you want to shrink images but not enlarge them.
3. Example – object-fit in Action 🎬
<img src="image.jpg" style="width: 200px; height: 200px; object-fit:
cover;">

4. Bonus: object-position
Used with object-fit to adjust the image’s alignment inside the container.

✅ Example:
img {
object-fit: cover;
object-position: top; /* Aligns image to the top */
}
CSS Pseudo-classes 🎭
CSS Pseudo-classes 🎭
A pseudo-class is a keyword added to a selector that defines a special state of an
element.

1. Syntax 📌
selector:pseudo-class {
property: value;
}

✅ Example:
button:hover {
background-color: blue;
}

💡 Changes the button color when hovered.

2. Common Pseudo-classes 🎨
🔹 User Interaction Pseudo-classes 🖱️
Pseudo-clas Description
s

:hover When a user hovers over an element.

:focus When an element is focused (e.g., input


fields).

:active When an element is clicked.

:visited Styles a visited link.

:link Styles an unvisited link.


✅ Example:
a:visited {
color: purple;
}

button:active {
transform: scale(0.95);
}

🔹 Structural Pseudo-classes 📏
Pseudo-class Description

:first-chil Selects the first child of a parent.


d

:last-child Selects the last child of a parent.

:nth-child( Selects the nth child (e.g., nth-child(2)).


n)

:nth-of-typ Selects the nth element of a specific type.


e(n)

:only-child Selects an element if it’s the only child of its parent.

✅ Example:
p:first-child {
font-weight: bold;
}

div:nth-child(2) {
background-color: yellow;
}

🔹 Form Pseudo-classes 📝
Pseudo-class Description
:checked Selects checked checkboxes or radio
buttons.

:disabled Selects disabled form elements.

:enabled Selects enabled form elements.

:required Selects required input fields.

:valid / Selects valid/invalid input fields.


:invalid

✅ Example:
input:focus {
border: 2px solid blue;
}

input:required {
border: 2px solid red;
}

🔹 :not() – Exclude Elements ❌


✅ Example:
p:not(.special) {
color: gray;
}

💡 All <p> elements except those with class special will turn gray.

3. Combining Pseudo-classes 🔗
✅ Example:
button:hover:active {
background-color: red;
}

💡 Changes the button color only when hovered and clicked.

4. Pseudo-class vs Pseudo-element 🚀
Feature Pseudo-class Pseudo-element
(:) (::)

Applies to Existing elements Part of an element

Example :hover, :focus ::before,


::after
CSS Pseudo-elements 🎨
CSS Pseudo-elements 🎨
A pseudo-element is used to style specific parts of an element, such as the first letter or
inserting content before or after an element.

1. Syntax 📌
selector::pseudo-element {
property: value;
}

✅ Example:
p::first-letter {
font-size: 2em;
color: red;
}

💡 Styles the first letter of every <p>.

2. Common Pseudo-elements 🎭
🔹 ::before – Insert Content Before an Element
✅ Adds content before an element (useful for icons, decorations, etc.).
h1::before {
content: " 🔥 ";
}

💡 Adds a fire emoji before every <h1>.


🔹 ::after – Insert Content After an Element
✅ Adds content after an element.
h1::after {
content: " 🎉";
}

💡 Adds a celebration emoji after every <h1>.

🔹 ::first-letter – Style First Letter


✅ Targets the first letter of an element.
p::first-letter {
font-size: 2em;
font-weight: bold;
}

💡 Makes the first letter bigger & bold.

🔹 ::first-line – Style First Line


✅ Targets the first line of an element.
p::first-line {
color: blue;
font-weight: bold;
}

💡 Changes the first line’s color to blue.

🔹 ::selection – Style Highlighted Text


✅ Changes the background and text color of selected text.
::selection {
background-color: yellow;
color: black;
}

💡 Text selection will have a yellow background.

🔹 ::marker – Style List Markers


✅ Styles the bullet points or numbers in lists.
li::marker {
color: red;
font-size: 1.5em;
}

💡 List markers turn red & larger.

3. Pseudo-element vs Pseudo-class 🚀
Feature Pseudo-element Pseudo-class
(::) (:)

Applies to Part of an element Whole element

Example ::before, :hover,


::after :focus

Content Modification ✅ Yes ❌ No

4. Bonus: ::before and ::after with content


✅ Best used with content to add icons, symbols, or decorative elements.
button::before {
content: " 👉 ";
}

button::after {
content: " ✅";
}

💡 Adds an arrow before & a checkmark after the button text.


CSS display vs visibility 🚀
CSS display vs visibility 🚀
The display and visibility properties control how elements appear or disappear on a
webpage, but they behave differently.

1. display Property 🖥️
The display property determines how an element is rendered in the layout.

🔹 Common display Values


Value Description

block Elements take up full width (e.g., <div>, <p>).

inline Elements stay in a line (e.g., <span>, <a>).

inline-bl Like inline, but allows height & width.


ock

none Completely removes the element from the


layout.

flex Makes an element a flex container.

grid Makes an element a grid container.

✅ Example:
p {
display: none; /* Hides the paragraph completely */
}

💡 The paragraph won’t take space on the page.

2. visibility Property 👀
The visibility property controls whether an element is visible but still takes up space.
🔹 visibility Values
Value Description

visible The element is fully visible (default).

hidden The element is invisible, but space is


reserved.

✅ Example:
p {
visibility: hidden;
}

💡 The paragraph won’t be visible, but the space it occupies remains.

3. display: none vs visibility: hidden 🔍


Feature display: visibility: hidden
none

Element ✅ Yes ❌ No
removed?

Space occupied? ❌ No ✅ Yes


Clickable? ❌ No ✅ No (but still occupies space)
✅ Example:
.box1 {
display: none;
}

.box2 {
visibility: hidden;
}

💡 box1 is completely removed, while box2 is invisible but still takes up space.
4. Bonus: opacity: 0 vs visibility: hidden 🎭
●​ opacity: 0; hides the element but keeps it interactive.
●​ visibility: hidden; makes the element invisible and non-interactive.

✅ Example:
.hidden {
opacity: 0;
}

💡 The element remains clickable even though it’s invisible.


CSS position Property 📍
CSS position Property 📍
The position property in CSS is used to define how an element is positioned in a
document.

1. position Values & Behavior


Value Description

static Default positioning (normal document flow).

relative Position relative to its normal position.

absolute Position relative to its nearest positioned ancestor (or


body if none).

fixed Position relative to the viewport (doesn’t scroll).

sticky Switches between relative and fixed depending on


scroll.

2. static (Default Position)


✅ The element follows the normal document flow.
div {
position: static;
}

💡 The element stays where it normally appears.

3. relative (Relative to Itself)


✅ Moves the element relative to its original position.
div {
position: relative;
top: 20px; /* Moves 20px down */
left: 10px; /* Moves 10px right */
}

💡 The space it originally occupied remains empty.

4. absolute (Relative to Nearest Positioned Ancestor)


✅ Moves the element relative to its nearest positioned ancestor (or body if none).
div {
position: absolute;
top: 50px;
left: 30px;
}

💡 The element is removed from the normal flow.

5. fixed (Fixed to Viewport)


✅ Stays fixed in place even when scrolling.
header {
position: fixed;
top: 0;
width: 100%;
background-color: black;
color: white;
}

💡 Great for sticky headers.


6. sticky (Hybrid of Relative & Fixed)
✅ Acts as relative until scrolled, then becomes fixed.
div {
position: sticky;
top: 10px;
}

💡 Sticks to the top when scrolling down.

7. z-index (Stack Order)


✅ Controls which element appears on top.
div {
position: absolute;
z-index: 10; /* Higher values appear on top */
}

💡 Higher z-index = Higher stacking order.

8. Positioning Example 🚀
.container {
position: relative;
width: 300px;
height: 300px;
}

.box {
position: absolute;
top: 50px;
left: 50px;
background: red;
width: 100px;
height: 100px;
}

💡 The .box is positioned inside .container.


CSS float & clear 🎈
CSS float & clear 🎈
The float property is used for positioning elements side by side, while clear helps
prevent layout issues caused by floating elements.

1. float Property 📌
The float property moves an element to the left or right, allowing text or other elements to
wrap around it.

🔹 float Values
Value Description

left Floats the element to the left.

right Floats the element to the right.

none Default; no floating.

inher Inherits float value from parent.


it

✅ Example (Image Floated Left)


img {
float: left;
margin-right: 10px;
}

💡 Text wraps around the image on the right.

2. clear Property 🚫
The clear property is used to stop elements from wrapping around floated elements.

🔹 clear Values
Value Description

left Clears floating elements on the


left.

right Clears floating elements on the


right.

both Clears both left and right floats.

none Default; allows floating.

✅ Example (Clearing Float)


.clearfix {
clear: both;
}

💡 Prevents content from wrapping around floated elements.

3. Common float Issues & Solutions

🔹 Issue: Parent Collapsing Due to Float


✅ Fix: Use .clearfix (Adding overflow: hidden or display: flow-root)
.container::after {
content: "";
display: table;
clear: both;
}

💡 Ensures the container wraps around floated elements.

4. Float Layout Example 📌


.container {
width: 500px;
border: 2px solid black;
}

.box {
width: 100px;
height: 100px;
margin: 10px;
}

.left {
float: left;
background-color: lightblue;
}

.right {
float: right;
background-color: lightcoral;
}

✅ HTML
<div class="container">
<div class="box left">Left Box</div>
<div class="box right">Right Box</div>
</div>

💡 One box floats left, the other floats right.

5. Alternative: Flexbox vs Float 🚀


Feature Float Flexbox

Layout Old method for layouts Modern method

Responsiv ❌ Needs workarounds ✅ Easier


e

Alignment Hard to center Easy with


elements justify-content
💡 Use flexbox for modern layouts instead of float.
CSS 2D Transforms 🎭
CSS 2D Transforms 🎭
The 2D Transform property in CSS allows you to rotate, scale, skew, and translate elements
in a two-dimensional space.

1. transform Property 🚀
The transform property is used to apply 2D transformations to elements.

✅ Syntax:
selector {
transform: function(value);
}

2. Types of 2D Transforms 🛠️
🔹 1. translate(x, y) (Move)
Moves an element horizontally (x) and vertically (y).

✅ Example:
.box {
transform: translate(50px, 20px); /* Moves right 50px, down 20px
*/
}

💡 Shortcut:
●​ translateX(50px); → Moves right 50px
●​ translateY(-20px); → Moves up 20px

🔹 2. rotate(angle) (Rotate)
Rotates an element clockwise or counterclockwise.

✅ Example:
.box {
transform: rotate(45deg); /* Rotates 45 degrees clockwise */
}

💡 Use Negative Values (-45deg) for Counterclockwise Rotation.

🔹 3. scale(x, y) (Resize)
Resizes an element by scaling width (x) and height (y).

✅ Example:
.box {
transform: scale(1.5, 2); /* 1.5x width, 2x height */
}

💡 Shortcut:
●​ scaleX(2); → Doubles the width
●​ scaleY(0.5); → Shrinks height to 50%

🔹 4. skew(x, y) (Slant)
Tilts an element along the X or Y axis.

✅ Example:
.box {
transform: skew(20deg, 10deg); /* Skews 20° on X, 10° on Y */
}

💡 Shortcut:
●​ skewX(30deg); → Skews only along the X-axis
●​ skewY(15deg); → Skews only along the Y-axis

3. Combining Multiple Transforms 🔄


You can combine multiple transformations by separating them with a space.

✅ Example:
.box {
transform: translate(50px, 20px) rotate(45deg) scale(1.2);
}

💡 Order Matters! It first moves, then rotates, then scales.

4. Setting the transform-origin 🎯


By default, transformations happen from the center of an element.​
The transform-origin property changes the reference point.

✅ Example:
.box {
transform-origin: top left; /* Rotates from the top-left corner
*/
transform: rotate(45deg);
}

5. Full Example with Hover Effect 🖱️


.box {
width: 100px;
height: 100px;
background: coral;
transition: transform 0.5s;
}
.box:hover {
transform: rotate(20deg) scale(1.2);
}

✅ HTML
<div class="box"></div>

💡 Hover over the box to see it transform!

6. transform vs position vs margin 🤔


Feature transfo positi margi
rm on n

Moves element? ✅ Yes ✅ Yes ✅ Yes


Affects other ❌ No ✅ Yes ✅ Yes
elements?

Animatable? ✅ Yes ❌ No ✅ Yes


💡 Use transform for smoother animations & effects!
CSS 3D Transforms 🎭
CSS 3D Transforms 🎭
CSS 3D Transforms allow elements to be rotated, scaled, moved, and skewed in a
three-dimensional space using the transform property.

1. Enabling 3D with perspective 🏞️


The perspective property adds depth to the scene.​
It defines how far the viewer is from the Z-axis.

✅ Example:
.container {
perspective: 600px; /* Adjusts depth effect */
}

💡 Higher perspective = Less depth​


💡 Lower perspective = More dramatic 3D effect

2. 3D Transform Functions 🛠️
🔹 1. translate3d(x, y, z) (Move in 3D Space)
Moves an element along the X, Y, and Z axes.

✅ Example:
.box {
transform: translate3d(50px, 20px, 100px);
}

💡 Shortcuts:
●​ translateX(50px); → Moves right 50px
●​ translateY(-20px); → Moves up 20px
●​ translateZ(100px); → Moves closer (toward the viewer)

🔹 2. rotate3d(x, y, z, angle) (Rotate in 3D)


Rotates the element in 3D space.

✅ Example:
.box {
transform: rotate3d(1, 1, 0, 45deg); /* Rotates diagonally */
}

💡 Shortcuts:
●​ rotateX(45deg); → Rotates around the X-axis
●​ rotateY(60deg); → Rotates around the Y-axis
●​ rotateZ(90deg); → Rotates around the Z-axis

🔹 3. scale3d(x, y, z) (Resize in 3D)


Resizes an element along all three axes.

✅ Example:
.box {
transform: scale3d(1.5, 1.2, 1);
}

💡 Shortcuts:
●​ scaleX(2); → Doubles the width
●​ scaleY(1.5); → Increases height by 50%
●​ scaleZ(0.8); → Reduces depth

🔹 4. skew() (Skewing is Only 2D)


Skew transformations do not support 3D but can still be used.
✅ Example:
.box {
transform: skew(20deg, 10deg);
}

3. transform-style: preserve-3d 🎭
By default, child elements flatten into 2D.​
To keep 3D depth, use preserve-3d.

✅ Example:
.parent {
transform-style: preserve-3d;
}

💡 Use preserve-3d for nested elements in 3D scenes.

4. backface-visibility (Hiding the Back of an


Element) 👀
Controls whether the back of a rotated element is visible.

✅ Example:
.box {
backface-visibility: hidden;
}

💡 Useful for flip animations!

5. Full 3D Flip Animation 🃏


✅ CSS
.container {
perspective: 1000px;
}

.card {
width: 200px;
height: 200px;
position: relative;
transform-style: preserve-3d;
transition: transform 0.6s;
}

.card:hover {
transform: rotateY(180deg);
}

.front, .back {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
}

.back {
background: coral;
transform: rotateY(180deg);
}

✅ HTML
<div class="container">
<div class="card">
<div class="front">Front</div>
<div class="back">Back</div>
</div>
</div>
💡 Hover to flip the card!

6. When to Use 3D Transforms? 🤔


✅ For creating 3D effects, such as:
●​ Flip cards
●​ Rotating cubes
●​ Depth effects in UI

💡 Avoid overuse, as excessive 3D transforms can affect performance.


CSS Transitions 🎨✨
CSS Transitions 🎨✨
CSS Transitions allow you to create smooth animations between different states of an
element.

1. The transition Property 🚀


The transition property lets elements change from one style to another gradually,
instead of instantly.

✅ Syntax:
selector {
transition: property duration timing-function delay;
}

🔹 Parameters:
Property Description

property The CSS property to animate (e.g., width, background-color). Use


all for multiple properties.

duration The time (in seconds or milliseconds) the transition takes (e.g., 2s,
500ms).

timing-fun Defines the speed of the transition (e.g., ease, linear).


ction

delay Delay before the transition starts (optional).

2. Basic Transition Example 🎭


✅ CSS
.box {
width: 100px;
height: 100px;
background: coral;
transition: background 0.5s ease, transform 0.5s;
}

.box:hover {
background: blue;
transform: scale(1.2);
}

✅ HTML
<div class="box"></div>

💡 Hover over the box to see the transition!

3. Transition Timing Functions ⏳


The timing-function defines how the speed of the transition changes.

Timing Function Description

ease Default. Starts slow, speeds up, then slows


down.

linear Constant speed.

ease-in Starts slow, then speeds up.

ease-out Starts fast, then slows down.

ease-in-out Starts and ends slow.

cubic-bezier(n,n, Custom speed curve.


n,n)

✅ Example:
.box {
transition: width 2s ease-in-out;
}

4. Delaying Transitions ⏱️
Use transition-delay to start the animation after a delay.

✅ Example:
.box {
transition: background 1s ease-in 0.5s;
}

💡 The background color change will start after 0.5s delay.

5. Applying Transitions to Multiple Properties 🎨


✅ Example:
.box {
transition: background 1s, transform 1s;
}

💡 You can animate multiple properties at the same time!

6. Full Example with Hover Animation 🖱️


.box {
width: 100px;
height: 100px;
background: coral;
transition: all 0.5s ease-in-out;
}

.box:hover {
background: green;
transform: rotate(20deg) scale(1.2);
}

✅ HTML
<div class="box"></div>

💡 Smooth hover effect! 🚀

7. When to Use CSS Transitions? 🤔


✅ Best for:
●​ Button hover effects
●​ Smooth color & size changes
●​ Menu animations
●​ Loading effects

💡 For complex animations, consider @keyframes and animation.


CSS Animations 🎬✨
CSS Animations 🎬✨
CSS Animations allow elements to change styles dynamically over time, making
webpages more interactive and engaging.

1. The @keyframes Rule 🎨


CSS animations use @keyframes to define step-by-step style changes.

✅ Syntax:
@keyframes animationName {
from {
/* Initial state */
}
to {
/* Final state */
}
}

💡 OR using percentages:
@keyframes animationName {
0% { /* Start state */ }
50% { /* Mid state */ }
100% { /* End state */ }
}

2. Applying the Animation 🚀


Use the animation property to apply the @keyframes animation.

✅ Syntax:
selector {
animation: name duration timing-function delay iteration-count
direction;
}

🔹 Parameters:
Property Description

name Name of the @keyframes animation.

duration Time taken to complete one cycle (e.g., 2s, 500ms).

timing-funct Speed curve (ease, linear, etc.).


ion

delay Time before the animation starts (optional).

iteration-co Number of times the animation repeats (infinite for


unt continuous).

direction Animation flow (normal, reverse, alternate,


alternate-reverse).

3. Basic Animation Example 🎭


✅ CSS
@keyframes moveBox {
from {
transform: translateX(0);
}
to {
transform: translateX(200px);
}
}

.box {
width: 100px;
height: 100px;
background: coral;
animation: moveBox 2s ease-in-out infinite alternate;
}

✅ HTML
<div class="box"></div>

💡 The box moves back and forth!

4. Multiple Keyframes (Smooth Animations) 🔥


✅ Example:
@keyframes colorChange {
0% { background: red; }
50% { background: yellow; }
100% { background: green; }
}

.box {
animation: colorChange 3s linear infinite;
}

💡 The box smoothly changes colors! 🎨

5. animation-fill-mode (Retaining Styles) 🎯


Controls whether the animation's final style stays applied.

Value Effect

none Default, element returns to original style.

forward Keeps the final keyframe style after animation


s ends.
backwar Applies the first keyframe before animation starts.
ds

both Applies forwards and backwards.

✅ Example:
.box {
animation: moveBox 2s forwards;
}

💡 The box stays at the final position!

6. animation-delay (Adding Delay) ⏳


Use animation-delay to delay the start.

✅ Example:
.box {
animation: moveBox 2s ease-in-out 1s;
}

💡 The animation starts after 1s.

7. animation-direction (Reversing Animation) 🔄


Value Description

normal Default, plays forward.

reverse Plays backwards.

alternate Plays forward, then


backward.

alternate-rev Plays backward, then


erse forward.
✅ Example:
.box {
animation: moveBox 2s infinite alternate;
}

💡 Moves back and forth automatically!

8. Full Animation Example 🎬


@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-50px); }
}

.bouncing-box {
width: 100px;
height: 100px;
background: blue;
animation: bounce 1s infinite;
}

✅ HTML
<div class="bouncing-box"></div>

💡 A bouncing box effect! 🏀

9. When to Use CSS Animations? 🤔


✅ Best for:
●​ Hover & Click effects
●​ Loading animations
●​ Banner text effects
●​ Smooth UI transitions
Print Style in CSS 🖨️
Print Style in CSS 🖨️
Print styles allow you to create a custom layout for documents when they are printed,
improving the user experience and making printed content more readable.

1. Using @media print 🖨️


The @media print rule is used to define print-specific styles. You can place CSS rules
inside this block that only apply when the page is being printed.

✅ Syntax:
@media print {
/* Print-specific styles here */
}

2. Example: Basic Print Styles


You can hide certain elements like navigation menus or background images for a cleaner
print version.

✅ CSS:
@media print {
body {
font-family: Arial, sans-serif; /* Set a readable font */
font-size: 12pt; /* Adjust font size */
}

header, footer {
display: none; /* Hide header and footer */
}

.no-print {
display: none; /* Hide elements with class 'no-print' */
}
}

💡 The content will only be visible when printed if it is not within the .no-print class.

3. Page Breaks (page-break-before,


page-break-after, page-break-inside) 📄
In print layouts, you can control where the page breaks to improve the printed document's
structure.

Properties:

●​ page-break-before - Adds a page break before the element.


●​ page-break-after - Adds a page break after the element.
●​ page-break-inside - Prevents or allows page breaks inside an element.

✅ Example:
@media print {
h2 {
page-break-before: always; /* Force a page break before each
heading */
}

.section {
page-break-inside: avoid; /* Prevent page break inside a
section */
}

footer {
page-break-after: always; /* Add a page break after the
footer */
}
}

4. Hiding Non-Essential Elements 🛑


You can hide elements like sidebars or advertisements when printing to avoid wasting paper.

✅ Example:
@media print {
.sidebar, .ads {
display: none; /* Hide elements not needed for print */
}
}

5. Styling Links and URLs 📎


You can format links to be more print-friendly by removing underlines or changing their color.

✅ Example:
@media print {
a {
color: black; /* Change links to black */
text-decoration: none; /* Remove underlines */
}
}

6. Adjusting Layout for Print 📏


You may want to adjust the layout, such as switching from a multi-column format to a
single-column for better readability on paper.

✅ Example:
@media print {
.container {
width: 100%; /* Set full width for better use of space */
margin: 0;
}

.two-column-layout {
display: block; /* Convert multi-column layout to single
column */
}
}

7. Adding a Custom Page Size 🎚️


You can also define a custom page size for printing using the @page rule. This helps in
setting the margins and size of printed pages.

✅ Example:
@page {
size: A4; /* Set page size to A4 */
margin: 20mm; /* Set page margins */
}

@media print {
body {
margin: 0; /* Remove extra margin when printed */
}
}

8. Example: Complete Print Styles 🎨


@media print {
/* Set font and layout for printing */
body {
font-family: 'Times New Roman', serif;
font-size: 11pt;
color: black;
}

/* Hide navigation and footer */


nav, footer {
display: none;
}
/* Remove background colors and images */
body {
background-color: white;
}

/* Adjust images for print */


img {
max-width: 100%;
height: auto;
}

/* Force page breaks */


.chapter {
page-break-before: always;
}

/* Customize links */
a {
text-decoration: none;
color: black;
}
}

9. Previewing Print Styles 🖨️


You can preview how the page will look when printed using the browser's print preview
feature. In most browsers, this can be accessed by pressing Ctrl + P or Cmd + P (Mac).

10. When to Use Print Styles 🤔


✅ Best for:
●​ Printing reports
●​ Creating printable forms
●​ Generating user-friendly invoices

💡 Always make sure your printed pages are easy to read and look professional.
Responsive Web Design (RWD) 🌐📱
Responsive Web Design (RWD) 🌐📱
Responsive Web Design (RWD) is the approach of creating web pages that adapt to various
screen sizes and devices. This ensures that the user experience remains consistent and
optimal on mobile, tablet, and desktop screens.

1. Key Concepts of RWD 🧠


Responsive web design uses a combination of flexible grids, media queries, and fluid
images to create layouts that adjust to the user's screen size.

Key Principles:

1.​ Fluid Grid Layouts - Use percentages instead of fixed pixel values for layout widths,
so the design adapts to the viewport.
2.​ Media Queries - Apply CSS styles based on the characteristics of the device (e.g.,
screen width).
3.​ Flexible Images - Images should resize within their containers using max-width:
100%.

2. Fluid Grid Layouts 🌊


Fluid grids rely on relative units like percentages (%) rather than fixed units like pixels (px),
which allows the layout to resize based on the viewport.

Example:

.container {
width: 80%; /* Width adjusts to 80% of the viewport */
margin: 0 auto;
}

💡 The container adjusts its width as the screen size changes!

3. Media Queries 📱🖥️


Media queries allow you to apply CSS rules based on different screen conditions, like width,
height, or orientation.

Syntax:

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


/* Styles for devices with a max width of 768px (like tablets)
*/
}

Common Media Query Breakpoints:

@media screen and (max-width: 1200px) { /* Desktops */ }


@media screen and (max-width: 992px) { /* Tablets in landscape */ }
@media screen and (max-width: 768px) { /* Tablets in portrait */ }
@media screen and (max-width: 576px) { /* Mobile devices */ }

4. Fluid Images 🖼️
To make images responsive, you can set max-width: 100% to ensure images never
exceed their container's width.

Example:

img {
max-width: 100%;
height: auto; /* Maintain aspect ratio */
}

💡 The image will resize based on its container's width!

5. Viewport Meta Tag 🖥️📱


The viewport meta tag controls the page's dimensions and scaling on mobile devices.

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

💡 width=device-width makes the page width match the device's screen width.

6. Flexbox for Layouts 🧩


Flexbox is a powerful layout tool that allows for flexible, responsive designs without the
need for complex calculations.

Example:

.container {
display: flex;
flex-wrap: wrap; /* Allow items to wrap */
}

.item {
flex: 1 1 200px; /* Flex items grow, shrink, and have a base
width */
}

💡 Items inside .container will adjust based on available space!

7. CSS Grid for Advanced Layouts 🧭


CSS Grid provides a two-dimensional layout system that makes it easy to create complex
responsive designs.

Example:

.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); /*
Auto-fill with minimum width */
gap: 20px;
}
💡 The grid adapts automatically based on the available space and screen size.

8. Mobile First Design 📱


Start designing for small screens first and then progressively add styles for larger screens
using media queries. This is the most common approach to responsive design.

Example:

/* Mobile-first styles */
.container {
width: 100%;
padding: 10px;
}

/* Styles for larger screens */


@media screen and (min-width: 768px) {
.container {
width: 80%;
padding: 20px;
}
}

💡 Mobile-first ensures good performance and usability on mobile devices.

9. Responsive Typography 📏
Responsive typography adjusts text sizes based on the screen width. You can use vw
(viewport width) for scalable typography.

Example:

h1 {
font-size: 5vw; /* Font size adjusts based on viewport width */
}
💡 The font size scales dynamically with the screen size!

10. Testing Responsiveness 🧪


Test your website on different devices and screen sizes. Modern browsers have built-in tools
to simulate mobile devices (e.g., Chrome DevTools, Firefox Developer Tools).

11. Best Practices for Responsive Web Design 🏆


●​ Keep images optimized for fast loading.
●​ Use flexible and scalable layouts.
●​ Avoid fixed-width elements that don’t adjust well on smaller screens.
●​ Design for touch-friendly navigation on mobile devices.
●​ Minimize content on smaller screens and prioritize essential information.

12. Example: Full Responsive Web Design

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Responsive Web Design</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}

.header {
background-color: #333;
color: white;
padding: 10px;
text-align: center;
}
.container {
display: flex;
flex-wrap: wrap;
padding: 20px;
}

.item {
flex: 1 1 200px;
margin: 10px;
background-color: lightgray;
padding: 20px;
text-align: center;
}

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


.container {
flex-direction: column;
}
}
</style>
</head>
<body>
<header class="header">
<h1>Responsive Web Design Example</h1>
</header>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
</body>
</html>

💡 This page will stack the items vertically on screens smaller than 768px wide!
Viewport Meta Tag 🌐📱
Viewport Meta Tag 🌐📱
The viewport meta tag is a key component in responsive web design, ensuring that a web
page adapts appropriately to different screen sizes, especially on mobile devices. It controls
the layout and scaling of the page in the browser’s viewport.

1. Purpose of the Viewport Meta Tag 🎯


The primary purpose of the viewport meta tag is to allow web pages to adjust to the width
and scale of the device's screen, offering a better user experience on mobile and tablet
devices. Without this tag, pages may appear zoomed out, or the layout may be fixed,
causing content to be cut off.

2. Syntax 📜
The basic syntax for the viewport meta tag is as follows:

<meta name="viewport" content="width=device-width,


initial-scale=1.0">

Attributes:

●​ width=device-width: This sets the width of the page to be equal to the device's
screen width. It ensures that the content fits within the screen's width, regardless of
the device.
●​ initial-scale=1.0: This sets the initial zoom level when the page is first loaded. A
value of 1.0 means the page is not zoomed in or out.
●​ maximum-scale=1.0 (optional): Prevents users from zooming in beyond the set
scale.
●​ minimum-scale=1.0 (optional): Prevents users from zooming out beyond the set
scale.
●​ user-scalable=no (optional): Disables zooming on the page.

3. Example: Basic Viewport Meta Tag


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

💡 This makes the page adjust to the width of the device’s screen and ensures it
loads without any initial zoom.

4. Common Variations 📐
1. Setting the Maximum and Minimum Zoom

To prevent zooming in or out on mobile devices, you can specify the maximum and minimum
zoom levels.

<meta name="viewport" content="width=device-width,


initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

💡 This ensures the page is fixed at its default zoom level and cannot be zoomed in or
out.

2. Preventing User Zooming

If you want to completely disable zooming on your site, you can use user-scalable=no.

<meta name="viewport" content="width=device-width,


initial-scale=1.0, user-scalable=no">

💡 This can improve layout consistency but might affect accessibility for users who
rely on zooming.

5. Responsive Layout with Viewport Meta Tag 🌍


By setting width=device-width, you ensure that the page adapts to any screen size.
Combine it with fluid grids, flexible images, and media queries to make your page fully
responsive.
<meta name="viewport" content="width=device-width,
initial-scale=1.0">

💡 This should always be the first line in the <head> section of your HTML document
to ensure proper scaling on all devices.

6. When to Use the Viewport Meta Tag 🤔


Use the viewport meta tag whenever:

●​ You are building a responsive website.


●​ Your website should provide a great experience on both desktop and mobile
devices.
●​ You want to control zooming behavior on mobile devices.

7. Best Practices for the Viewport Meta Tag 📋


●​ Always include width=device-width to ensure your layout scales to the device’s
width.
●​ Use initial-scale=1.0 to prevent any zooming on page load.
●​ Avoid setting user-scalable=no unless absolutely necessary, as it can hinder
accessibility.
●​ Test your website on various screen sizes to ensure content is visible and easily
readable.

📄
8. Example: Full HTML Example with Viewport Meta Tag

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Responsive Page</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}

h1 {
font-size: 2em;
color: #333;
}

p {
font-size: 1em;
line-height: 1.6;
}
</style>
</head>
<body>
<h1>Responsive Web Design</h1>
<p>This is an example of a responsive web page using the
viewport meta tag. Resize the browser window to see the layout
adjust.</p>
</body>
</html>

💡 This example ensures that the page layout adapts to different screen sizes.
Media Queries 📱💻
Media Queries 📱💻
Media Queries are a critical part of responsive web design. They allow you to apply different
CSS styles depending on the device's screen size, resolution, or other characteristics like
orientation and display type.

1. What Are Media Queries? 🤔


Media queries enable the application of CSS rules based on the characteristics of the device
or viewport. They are used to make websites responsive by altering layouts and styles for
various screen sizes, such as phones, tablets, and desktops.

2. Syntax of Media Queries 📝


A media query consists of the @media rule, followed by one or more conditions. The basic
structure is:

@media [media type] and (condition) {


/* CSS rules */
}

Media Query Structure:

●​ @media: Indicates the start of a media query.


●​ [media type]: Optional; specifies the type of media (like screen, print, etc.). Most
commonly used media type is screen.
●​ (condition): The condition(s) specify when the styles will be applied (such as width,
height, or orientation).

3. Common Media Query Conditions 🔍


1. Screen Width and Height:

You can apply styles depending on the width and height of the viewport.
@media screen and (max-width: 768px) {
/* Styles for devices with screen width 768px or smaller */
}

●​ max-width: Applies styles when the viewport is smaller than the specified width.
●​ min-width: Applies styles when the viewport is larger than the specified width.
●​ max-height / min-height: Similar to width, but for screen height.

2. Orientation:

You can target portrait or landscape modes.

@media screen and (orientation: portrait) {


/* Styles for portrait orientation */
}

@media screen and (orientation: landscape) {


/* Styles for landscape orientation */
}

3. Device Pixel Ratio:

This condition is useful for targeting high-resolution screens like Retina displays.

@media screen and (min-device-pixel-ratio: 2) {


/* Styles for devices with high-resolution screens */
}

4. Device Type (e.g., print):

Media queries can also apply styles for different output devices, such as printing.

@media print {
/* Styles for printing */
}
4. Examples of Common Media Queries 🖥️📱
1. Mobile-First Approach (Max-width Media Queries)

Mobile-first design involves writing the default styles for small screens and adding media
queries to scale for larger screens.

/* Default styles (for mobile-first) */


body {
font-size: 14px;
background-color: lightgray;
}

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


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

@media screen and (min-width: 1024px) {


body {
font-size: 18px;
background-color: lightgreen;
}
}

💡 This approach ensures the design looks good on mobile by default, and only
adjusts for larger screens.

2. Targeting Tablets in Portrait and Landscape

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


/* Styles for tablet portrait mode */
body {
font-size: 16px;
}
}

@media screen and (min-width: 768px) and (max-width: 1024px) and


(orientation: landscape) {
/* Styles for tablet landscape mode */
body {
font-size: 18px;
}
}

💡 This query applies specific styles depending on both the width and orientation of
tablets.

3. Targeting Large Desktops

@media screen and (min-width: 1200px) {


/* Styles for desktops with a minimum width of 1200px */
.container {
width: 1100px;
margin: 0 auto;
}
}

💡 This applies when the screen size is wide enough for large desktops.

5. Combining Multiple Conditions 🤹‍♂️


You can combine multiple conditions using and, or, and not.

Example:

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


/* Styles for devices with widths between 768px and 1024px */
.sidebar {
display: block;
}
}

Example:

@media screen and (max-width: 768px), (orientation: portrait) {


/* Styles for screens smaller than 768px or in portrait
orientation */
}

6. Mobile-First vs. Desktop-First 🔄


●​ Mobile-First Approach: Design for smaller screens first (default styles for mobile),
then use media queries to scale for larger devices.
●​ Desktop-First Approach: Design for larger screens first, then scale down using
media queries for mobile.

Mobile-First (Recommended for RWD)

●​ Write the default styles for small devices.


●​ Use min-width for larger screens.

Desktop-First

●​ Write the default styles for large devices.


●​ Use max-width for smaller devices.

7. Best Practices for Media Queries 🏆


●​ Mobile First: Use mobile-first design principles by setting default styles for small
screens.
●​ Test on Real Devices: Always test your design on multiple screen sizes to ensure
consistency.
●​ Limit Breakpoints: Don't overuse media queries. Aim for a clean, scalable design
without too many breakpoints.
●​ Use Relative Units: Use relative units (em, %, rem) in combination with media
queries to improve flexibility.

8. Full Example with Media Queries 📝


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Responsive Design</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}

h1 {
font-size: 2em;
color: #333;
}

p {
font-size: 1em;
line-height: 1.6;
}

@media screen and (max-width: 600px) {


h1 {
font-size: 1.5em;
}
p {
font-size: 0.9em;
}
}

@media screen and (min-width: 601px) and (max-width: 1200px)


{
h1 {
font-size: 2em;
}
p {
font-size: 1em;
}
}

@media screen and (min-width: 1201px) {


h1 {
font-size: 2.5em;
}
p {
font-size: 1.2em;
}
}
</style>
</head>
<body>
<h1>Responsive Web Design with Media Queries</h1>
<p>This text will adjust depending on the screen size!</p>
</body>
</html>

💡 This layout changes the font sizes for small, medium, and large screens.
CSS Specificity 🎯
CSS Specificity 🎯
CSS specificity is a system used to determine which CSS rules are applied to an element
when multiple rules could apply. The more specific a selector is, the higher its specificity
and the more priority it has in applying styles.

1. What is Specificity? 🤔
Specificity defines the "weight" of a selector. If multiple CSS selectors match the same
element, the one with the highest specificity will take precedence and apply its styles.

2. How Specificity is Calculated 🧮


Specificity is calculated based on the types of selectors used in the rule. It is represented as
a four-part value in the form of:

(a, b, c, d)

Where:

●​ a = the number of inline styles (style attribute within the HTML element).
●​ b = the number of ID selectors (#id).
●​ c = the number of class selectors (.class), attributes selectors ([type="text"]),
and pseudo-classes (:hover).
●​ d = the number of type selectors (element names like div, p, etc.) and
pseudo-elements (::before, ::after).

Specificity Rules:

●​ Inline styles have the highest specificity.


●​ ID selectors are more specific than class, attribute, and pseudo-class selectors.
●​ Class, attribute, and pseudo-class selectors are more specific than type and
pseudo-element selectors.
●​ Type selectors have the lowest specificity.
3. Specificity Examples 📊
1. Inline Style (Highest Specificity)

<p style="color: red;">This text is red.</p>

Specificity: (1, 0, 0, 0) — Inline styles have the highest specificity.

2. ID Selector

#main {
color: blue;
}

Specificity: (0, 1, 0, 0) — The ID selector has high specificity.

3. Class Selector

.content {
color: green;
}

Specificity: (0, 0, 1, 0) — The class selector has medium specificity.

4. Element (Type) Selector

p {
color: yellow;
}

Specificity: (0, 0, 0, 1) — The type selector has the lowest specificity.

4. Specificity Calculation Examples 🧑‍🏫


Let’s look at how specificity works when multiple rules apply to the same element.

1. Multiple Selectors for the Same Element


<p class="text" id="main">This is some text.</p>

CSS:

p {
color: yellow;
}

#main {
color: red;
}

.text {
color: green;
}

Specificity:

●​ p has a specificity of (0, 0, 0, 1).


●​ #main has a specificity of (0, 1, 0, 0).
●​ .text has a specificity of (0, 0, 1, 0).

Result: The #main selector will take precedence and apply color: red because it has the
highest specificity.

2. Conflicting Class and Type Selectors

<p class="content">This is some content.</p>

CSS:

.content {
color: green;
}

p {
color: yellow;
}
Specificity:

●​ .content has a specificity of (0, 0, 1, 0).


●​ p has a specificity of (0, 0, 0, 1).

Result: The .content selector will apply color: green because it has higher specificity
than the p selector.

3. Specificity with Multiple Classes

<p class="text content">This is some content.</p>

CSS:

.text {
color: red;
}

.content {
color: blue;
}

Specificity:

●​ .text has a specificity of (0, 0, 1, 0).


●​ .content has a specificity of (0, 0, 1, 0).

Result: Since both classes have the same specificity, the last declared rule in the CSS file
will apply. In this case, color: blue will be applied because .content comes last.

5. Specificity Hierarchy 🔝
1.​ Inline styles: (1, 0, 0, 0)
2.​ ID selectors: (0, 1, 0, 0)
3.​ Class selectors, attribute selectors, pseudo-classes: (0, 0, 1, 0)
4.​ Element selectors, pseudo-elements: (0, 0, 0, 1)
6. Practical Tip: Avoid Over-Specificity ⚠️
Sometimes, it’s easy to fall into the trap of over-specifying selectors, which can make future
edits more complex. A good practice is to keep selectors as simple as possible to
maintain flexibility and reusability.

7. Overriding Specificity
If two selectors have the same specificity, the one that appears last in the CSS file will be
applied. If you need to override a style, you can:

●​ Use a more specific selector.


●​ Use the !important flag (though it should be avoided when possible as it can
break the cascade).

Example:

#main {
color: blue !important;
}

.text {
color: red;
}

Result: The color: blue will be applied, even though .text has higher specificity,
because the !important rule takes precedence.

8. Summary of Specificity 📚
●​ Inline styles always win.
●​ ID selectors are very specific.
●​ Class, attribute, and pseudo-class selectors have medium specificity.
●​ Element selectors (tags like div, h1, p) are the least specific.
●​ Specificity values are cumulative: for example, #main .content p would have a
higher specificity than #main p due to the combination of ID, class, and element.
CSS Multiple Columns 📑
CSS Multiple Columns 📑
The CSS Multiple Columns feature allows you to split content into multiple columns, similar
to newspaper or magazine layouts. It enhances the readability of text-heavy content by
breaking it into narrower columns.

1. The columns Property


The easiest way to create a multi-column layout is by using the columns shorthand
property.

Syntax:

selector {
columns: <column-count> <column-width>;
}

●​ column-count: Specifies the number of columns.


●​ column-width: Defines the width of each column.

Example:

.container {
columns: 3 200px;
}

This rule creates a layout with 3 columns, each having a width of 200px.

2. The column-count and column-width Properties


Instead of the shorthand columns property, you can define the column-count and
column-width properties separately.

Example:
.container {
column-count: 3; /* Number of columns */
column-width: 200px; /* Width of each column */
}

●​ column-count: Sets the number of columns.


●​ column-width: Sets the width of the columns.

If there is not enough space to fit the specified width, the browser will adjust the number of
columns accordingly.

3. Adding Gaps Between Columns with column-gap


The column-gap property controls the space between the columns.

Syntax:

selector {
column-gap: <value>;
}

●​ <value>: Specifies the gap between the columns (can be in px, em, rem, etc.).

Example:

.container {
column-count: 3;
column-gap: 30px;
}

This adds 30px of space between the columns.

4. The column-rule Property


The column-rule property is a shorthand for setting both the border between columns
and the style of the rule.
Syntax:

selector {
column-rule: <width> <style> <color>;
}

●​ width: Thickness of the rule (e.g., 2px).


●​ style: Style of the rule (e.g., solid, dotted).
●​ color: Color of the rule.

Example:

.container {
column-count: 3;
column-rule: 2px solid #000;
}

This creates a 2px solid black rule between the columns.

5. Handling Content Overflow in Columns


Sometimes, when content overflows from a column, the browser handles it differently based
on the layout settings.

Control the Overflow:

.container {
column-count: 3;
column-gap: 20px;
column-fill: auto; /* Default behavior */
}

●​ column-fill: auto: Allows content to overflow from one column to another if it


doesn't fit (default behavior).
●​ column-fill: balance: Forces the content to be distributed as evenly as
possible across the columns.
6. Example of a Multi-Column Layout

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Multi-Column Layout</title>
<style>
.container {
column-count: 3;
column-gap: 20px;
column-rule: 2px solid #000;
}
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec a orci at nunc tempor tincidunt. Morbi eget bibendum lorem.
Sed tincidunt placerat turpis, in facilisis libero lacinia non.</p>
<p>Nullam ultricies, ligula nec varius lacinia, turpis velit
aliquet felis, vel euismod purus est sed nunc. Donec ac erat sit
amet est feugiat ultricies.</p>
<p>Maecenas vel purus libero. Nulla id orci eget mi
scelerisque vehicula. Donec id orci in enim mollis bibendum ac nec
dui. Proin vel suscipit justo. Integer condimentum nisi eget felis
tristique bibendum.</p>
</div>
</body>
</html>

7. Advanced CSS Multi-Column Techniques 🌟


1. Creating Newspaper Layouts

By combining multiple columns with other layout techniques like flexbox or grid, you can
create more complex and responsive layouts.
2. Responsive Multi-Column Layouts

You can use media queries to adjust the number of columns depending on the screen size.
For instance, on mobile devices, you may want a single column, and on larger screens, you
can have multiple columns.

.container {
column-count: 1;
column-gap: 20px;
}

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


.container {
column-count: 2;
}
}

@media screen and (min-width: 1024px) {


.container {
column-count: 3;
}
}

8. Conclusion 🎯
The CSS Multiple Columns feature is an easy way to create a multi-column layout, perfect
for content like articles, blogs, and news sites. With properties like column-count,
column-gap, and column-rule, you can easily adjust the number of columns, the
spacing between them, and even add rules between the columns.

You might also like