A Beginner's Guide to CSS: Mastering Cascading Style Sheets

Table of contents
- CSS and its Syntax
- Why Use CSS?
- 3 Ways to Add CSS
- CSS Selectors
- CSS Comment
- CSS Colors
- CSS Background
- CSS Units
- CSS Fonts
- CSS Text
- Box Model
- CSS Gradients
- Box Shadow & Drop Shadow
- CSS Filter
- List in CSS
- Anchor Link States (Pseudo-classes)
- Combinators in CSS
- Display in CSS
- Position in CSS
- Overflow in CSS
- Pseudo Elements in CSS
- Pseudo class in CSS
- Column layout in CSS
- Flex Box in CSS

CSS and its Syntax
CSS stands for Cascading Style Sheets.
It controls the visual presentation (style, layout, color, fonts, spacing, etc.) of HTML elements.
Why Use CSS?
Without CSS:
<h1>Hello</h1>
With CSS:
<h1 style="color: blue; font-family: Arial;">Hello</h1>
3 Ways to Add CSS
Method | How to Use | Example |
Inline | Inside the HTML tag | <p style="color:red;">Text</p> |
Internal | Inside a <style> tag in <head> | <style>p { color: red; }</style> |
External β | Linked .css file | <link rel="stylesheet" href="styles.css"> |
CSS Syntax
selector {
property: value;
}
β Example:
h1 {
color: blue;
font-size: 24px;
}
This means: make all <h1>
elements blue and 24px in size.
CSS Selectors
Selectors target which elements to style.
πΉ 1. Universal Selector (*
)
Targets all elements.
* {
margin: 0;
padding: 0;
}
πΉ 2. Element Selector
Targets a specific HTML tag.
p {
color: green;
}
πΉ 3. Class Selector (.
)
Targets elements with a specific class.
<p class="highlight">Hello</p>
.highlight {
background-color: yellow;
}
πΉ 4. ID Selector (#
)
Targets an element with a unique ID.
<h1 id="main-title">Welcome</h1>
#main-title {
font-size: 30px;
}
πΉ 5. Group Selector
Style multiple elements at once.
h1, h2, p {
font-family: Arial;
}
πΉ 6. Descendant Selector
Select elements inside other elements.
article p {
color: gray;
}
Applies to all <p>
inside <article>
.
πΉ 7. Child Selector (>
)
Selects direct children only.
ul > li {
list-style-type: square;
}
πΉ 8. Adjacent Sibling Selector (+
)
Selects the next sibling only.
h2 + p {
color: purple;
}
πΉ 9. Attribute Selector
Targets elements by attributes:
input[type="text"] {
border: 1px solid gray;
}
πΉ 10. Pseudo-class Selectors
Used for states or dynamic interaction.
Selector | Meaning |
:hover | When mouse is over element |
:focus | When an input is focused |
:first-child | First child of a parent |
:last-child | Last child |
button:hover {
background-color: red;
}
πΉ 11. Pseudo-elements
Target parts of an element.
p::first-line {
font-weight: bold;
}
Specificity (Which Style Wins?)
Selector Type | Specificity Score |
Element (p ) | 1 |
Class (.x ) | 10 |
ID (#id ) | 100 |
Inline Style | 1000 |
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: sans-serif;
}
h1 {
color: blue;
}
.highlight {
background-color: yellow;
}
#intro {
font-style: italic;
}
</style>
</head>
<body>
<h1 id="intro">Welcome!</h1>
<p class="highlight">This is a highlighted paragraph.</p>
</body>
</html>
CSS Comment
CSS comments are lines of text that are ignored by the browser. They're used to explain code, leave notes, or temporarily disable CSS rules during development.
β Syntax:
/* This is a CSS comment */
Comments start with
/*
and end with*/
.They can span multiple lines.
π Examples:
/* This sets the background color of the body */
body {
background-color: #f0f0f0;
}
/*
This section styles the navigation bar.
It includes padding and font color.
*/
nav {
padding: 10px;
color: white;
}
CSS Colors
β 1. Color Names
CSS supports 147 predefined color names, like:
color: red;
color: blue;
color: lightgreen;
color: darkslategray;
Easy to use, but limited flexibility.
β 2. HEX (Hexadecimal) Color
HEX is a base-16 value that defines red, green, and blue (RGB) using 2 hex digits each.
color: #RRGGBB;
#FF0000
β red#00FF00
β green#0000FF
β blue#FFFFFF
β white#000000
β black
Short form also works: #FFF
(same as #FFFFFF
)
β 3. RGB (Red, Green, Blue)
Each color is defined using integer values (0β255) for red, green, and blue:
color: rgb(255, 0, 0); /* Red */
color: rgb(0, 255, 0); /* Green */
color: rgb(0, 0, 255); /* Blue */
β 4. RGBA (RGB + Alpha Transparency)
Same as rgb()
, but adds alpha (opacity) as a value from 0
(transparent) to 1
(opaque):
color: rgba(255, 0, 0, 0.5); /* Semi-transparent red */
β 5. HSL (Hue, Saturation, Lightness)
HSL gives more human-readable control over color:
color: hsl(0, 100%, 50%); /* Red */
Hue
: 0β360 degrees on a color wheelSaturation
: 0% (gray) to 100% (full color)Lightness
: 0% (black) to 100% (white)
β 6. HSLA (HSL + Alpha Transparency)
color: hsla(0, 100%, 50%, 0.3); /* Semi-transparent red */
β
7. currentColor
Keyword
Uses the value of the elementβs color
property. Useful for reusing a defined color.
border: 1px solid currentColor;
β
8. transparent
Keyword
Makes the color fully transparent.
background-color: transparent;
β Color Comparison Table:
Format | Example | Notes |
Color name | red | Simple, readable |
HEX | #FF0000 | Compact, web standard |
RGB | rgb(255, 0, 0) | Easy for dynamic values |
RGBA | rgba(255, 0, 0, 0.5) | Supports transparency |
HSL | hsl(0, 100%, 50%) | Great for tweaking colors |
HSLA | hsla(0, 100%, 50%, 0.5) | HSL + transparency |
CSS Background
The background
property in CSS is used to set the background effects for elements. It can control background color, images, repeat behavior, positioning, and more.
β
1. background-color
Sets the background color of an element.
background-color: lightblue;
β
2. background-image
Sets a background image using a URL.
background-image: url("image.jpg");
π Can be used with gradients too:
background-image: linear-gradient(to right, red, yellow);
β
3. background-repeat
Controls if/how the image repeats.
background-repeat: repeat; /* Default */
background-repeat: no-repeat; /* Show once */
background-repeat: repeat-x; /* Horizontal only */
background-repeat: repeat-y; /* Vertical only */
β
4. background-position
Sets the starting position of the background image.
background-position: center;
background-position: top right;
background-position: 50% 50%;
β
5. background-size
Controls the size of the background image.
background-size: cover; /* Cover entire area */
background-size: contain; /* Contain image without cutting */
background-size: 100px 100px; /* Fixed size */
β
6. background-attachment
Defines whether the background scrolls with the page.
background-attachment: scroll; /* Default */
background-attachment: fixed; /* Stays in place */
β
7. background-clip
Defines how far the background extends inside the element.
background-clip: border-box; /* Default */
background-clip: padding-box;
background-clip: content-box;
β
8. background
(Shorthand)
You can combine all background properties in a single line:
background: url("bg.jpg") no-repeat center/cover fixed;
Format:
background: [color] [image] [repeat] [position]/[size] [attachment];
Example:
body {
background: linear-gradient(to bottom right, #2196f3, #e91e63);
background-repeat: no-repeat;
background-size: cover;
background-attachment: fixed;
}
CSS Units
CSS Units β Absolute & Relative
β Absolute Units
These units are fixed and do not scale with screen size or parent elements. Best for print or very controlled layouts.
Unit | Description | Example |
px | Pixels (screen dots) | width: 100px; |
pt | Points (1pt = 1/72 inch) | font-size: 12pt; |
cm | Centimeters | margin: 2cm; |
mm | Millimeters | padding: 10mm; |
in | Inches (1in = 2.54cm) | width: 1in; |
pc | Picas (1pc = 12pt) | font-size: 1pc; |
Use Case: Print styles, very specific layouts.
β Relative Units
These units scale depending on parent elements or the viewport. Best for responsive web design.
Unit | Relative To | Example |
% | Parent element | width: 50%; |
em | Font size of the parent | padding: 2em; |
rem | Font size of the root (<html> ) | font-size: 1.5rem; |
vw | 1% of the viewport width | width: 80vw; |
vh | 1% of the viewport height | height: 50vh; |
vmin | 1% of the smaller of vw or vh | font-size: 5vmin; |
vmax | 1% of the larger of vw or vh | padding: 3vmax; |
ch | Width of the character "0" | width: 40ch; |
ex | x-height (height of lowercase "x") | line-height: 2ex; |
Use Case: Responsive layouts, scaling text, flexible designs.
β Quick Comparison:
Scenario | Use Unit |
Responsive layout | % , vw , vh , rem |
Font size (scalable) | em , rem |
Fixed-size elements | px |
Print layout | cm , pt , in |
Example:
html {
font-size: 16px; /* 1rem = 16px */
}
.container {
width: 80vw;
padding: 2em;
font-size: 1.2rem;
}
CSS Fonts
The font
properties in CSS let you control the style, size, weight, family, and more for the text on your web page.
β
1. font-family
Specifies the typeface (the font). Always provide fallback fonts.
font-family: 'Roboto', Arial, sans-serif;
Custom font:
'Roboto'
(loaded via @font-face or Google Fonts)Fallback:
Arial
Generic family:
sans-serif
π― Common generic families:
serif
β like Times New Romansans-serif
β like Arialmonospace
β like Couriercursive
,fantasy
,system-ui
β
2. font-size
Defines the size of the text.
font-size: 16px;
font-size: 1.2em;
font-size: 2rem;
Relative units (em
, rem
, %
) make your text responsive.
β
3. font-weight
Controls the boldness of the font.
font-weight: normal; /* 400 */
font-weight: bold; /* 700 */
font-weight: 100β900; /* Numeric scale */
β
4. font-style
Defines the style (italic or normal).
font-style: normal;
font-style: italic;
font-style: oblique;
β
5. font-variant
Used for small caps:
font-variant: small-caps;
β
6. line-height
Sets the space between lines of text:
line-height: 1.5;
β
7. @font-face
(Custom Fonts)
To load fonts locally or from a URL:
@font-face {
font-family: 'MyFont';
src: url('myfont.woff2') format('woff2');
}
body {
font-family: 'MyFont', sans-serif;
}
β 8. Google Fonts (Easy Custom Fonts)
Include in HTML:
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
Then use in CSS:
body {
font-family: 'Poppins', sans-serif;
}
β
9. Shorthand: font
You can combine font properties like this:
font: italic small-caps bold 16px/1.5 'Arial', sans-serif;
Format:
font: [style] [variant] [weight] [size]/[line-height] [family];
π Tips:
Always include fallback fonts.
Use relative units for better scalability (
em
,rem
).Use Google Fonts or
@font-face
for custom typography.
CSS Text
These properties help you control the appearance and layout of text, including alignment, spacing, decoration, and transformation.
β
1. color
Sets the text color.
color: red;
color: #333;
color: rgb(255, 0, 0);
β
2. text-align
Aligns the text horizontally.
text-align: left; /* Default */
text-align: right;
text-align: center;
text-align: justify;
β
3. text-decoration
Adds decorations like underline, line-through, etc.
text-decoration: none;
text-decoration: underline;
text-decoration: line-through;
text-decoration: overline;
Combine with color:
text-decoration: underline red;
β
4. text-transform
Changes the case of the text.
text-transform: none;
text-transform: uppercase;
text-transform: lowercase;
text-transform: capitalize;
β
5. letter-spacing
Adjusts space between characters.
letter-spacing: 2px;
β
6. word-spacing
Adjusts space between words.
word-spacing: 5px;
β
7. line-height
Controls space between lines of text.
line-height: 1.5;
β
8. text-indent
Adds indentation to the first line of a paragraph.
text-indent: 30px;
β
9. white-space
Controls how white space inside an element is handled.
white-space: normal; /* Default */
white-space: nowrap; /* No line breaks */
white-space: pre; /* Preserve formatting */
β
10. direction
and unicode-bidi
Controls text direction (like for Arabic or Hebrew).
direction: rtl; /* Right to left */
direction: ltr; /* Left to right (default) */
β 11. Text Shadow
Adds shadow to text.
text-shadow: 2px 2px 5px gray;
Example:
h1{
color: #333;
text-align: center;
text-transform: uppercase;
letter-spacing: 2px;
text-shadow: 1px 1px 3px rgba(0,0,0,0.2);
}
Box Model
The CSS box model is essentially a box that wraps around every HTML element. It consists of: content, padding, borders and margins.
In CSS, the term "box model" is used when talking about design and layout.
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent
πΉ 1. Content Area
- Controls the actual content's dimensions.
Property | Description | Example |
width | Sets the width of the content | width: 300px; |
height | Sets the height of the content | height: 150px; |
min-width , max-width | Set limits on width | max-width: 500px; |
min-height , max-height | Set limits on height | min-height: 100px; |
overflow | Controls content overflow | overflow: hidden; |
display | Affects box behavior | display: block; |
πΉ 2. Padding Area
- Space between content and border.
Property | Description | Example |
padding | Shorthand for all sides | padding: 20px; |
padding-top | Top padding | padding-top: 10px; |
padding-right | Right padding | padding-right: 15px; |
padding-bottom | Bottom padding | padding-bottom: 10px; |
padding-left | Left padding | padding-left: 15px; |
πΉ 3. Border Area
- The visible edge surrounding padding and content.
Property | Description | Example |
border | Shorthand for width, style, color | border: 1px solid black; |
border-width | Controls thickness | border-width: 2px; |
border-style | Controls style (solid, dashed, etc.) | border-style: dashed; |
border-color | Sets the border color | border-color: red; |
border-top , border-right , border-bottom , border-left | Individual borders | border-top: 2px dotted blue; |
border-radius | Rounds corners | border-radius: 10px; |
πΉ 4. Margin Area
- Space outside the border, between this element and others.
Property | Description | Example |
margin | Shorthand for all sides | margin: 10px; |
margin-top | Top margin | margin-top: 5px; |
margin-right | Right margin | margin-right: 10px; |
margin-bottom | Bottom margin | margin-bottom: 5px; |
margin-left | Left margin | margin-left: 10px; |
margin: auto | Centers an element (used with width ) | margin: auto; |
πΉ 5. Box Behavior / Control
- Properties that influence how the box behaves.
Property | Description | Example |
box-sizing | Defines how width/height are calculated | box-sizing: border-box; |
display | Block, inline, flex, grid, etc. | display: flex; |
visibility | Show/hide the box | visibility: hidden; |
overflow | What happens if content overflows | overflow: scroll; |
outline | A line outside the border (doesnβt affect box size) | outline: 2px dotted red; |
β Box Model Shorthand Example
.box {
width: 200px;
height: 150px;
padding: 20px;
margin: 10px;
border: 2px solid black;
box-sizing: border-box;
}
π What is box-sizing
in CSS?
The box-sizing
property defines how the total width and height of an element is calculated β whether or not it includes padding and border.
By Default (content-box
):
box-sizing: content-box;
Only the content is counted in the width and height.
Padding and border are added outside the defined width/height.
Example:
width: 300px;
padding: 20px;
border: 10px solid black;
Total width = 300 + 20*2 + 10*2 = 360px
Total height = same calculation
β
box-sizing: border-box;
box-sizing: border-box;
The width and height include content + padding + border.
No need to manually calculate extra space.
Example:
width: 300px;
padding: 20px;
border: 10px solid black;
Here, total width stays 300px.
Content area is automatically shrunk to fit the padding and border.
π Why Use border-box
?
Keeps layout simple and predictable β
Prevents overflow and alignment issues β
Widely used in modern CSS frameworks β
Best Practice (Set Globally):
* {
box-sizing: border-box;
}
This sets all elements (including pseudo-elements) to calculate width and height in a consistent, easier-to-manage way.
CSS Gradients
Gradients let you transition between two or more colors smoothly β and they're generated by the browser, so no image files needed!
β 1. Linear Gradient
Color changes in a straight line (top to bottom by default).
background: linear-gradient(direction, color1, color2, ...);
Examples:
background: linear-gradient(to right, red, blue);
/* From left to right */
background: linear-gradient(to bottom right, #ff7e5f, #feb47b);
/* Diagonal gradient */
background: linear-gradient(45deg, #00c6ff, #0072ff);
/* Using degree */
β 2. Radial Gradient
Color radiates outward from a central point (like a circle or ellipse).
background: radial-gradient(shape size at position, color1, color2, ...);
Examples:
background: radial-gradient(circle, red, yellow, green);
background: radial-gradient(ellipse at center, #ff9a9e, #fad0c4);
β 3. Conic Gradient (Newer)
Color rotates around a center point like a pie chart.
background: conic-gradient(from angle at position, color1, color2, ...);
Example:
background: conic-gradient(from 0deg, red, yellow, green, red);
β Supported in modern browsers.
β 4. Repeating Gradients
Repeats the gradient pattern to fill the element.
background: repeating-linear-gradient(to right, red 0px, red 10px, blue 10px, blue 20px);
background: repeating-radial-gradient(circle, yellow, orange 10px, yellow 20px);
Tips:
You can use transparent in gradients for cool effects!
Combine gradients with
background-size
,background-position
, etc.You can even overlay gradients over images:
background: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), url('image.jpg');
background-size: cover;
Summary Table
Type | Function |
linear-gradient | Transitions in a line |
radial-gradient | Radiates from center |
conic-gradient | Spins around center |
repeating-... | Repeats the gradient pattern |
Box Shadow & Drop Shadow
1. box-shadow
(for elements)
Adds shadow around the border of an element β often used to create depth or elevation.
β Syntax:
box-shadow: offset-x offset-y blur-radius spread-radius color;
offset-x
β Horizontal position (right if positive, left if negative)offset-y
β Vertical position (down if positive, up if negative)blur-radius
(optional) β Soften the edgesspread-radius
(optional) β Expand or shrink the shadowcolor
β Shadow color
Example:
box-shadow: 5px 5px 15px rgba(0, 0, 0, 0.3);
Multiple Shadows:
You can stack shadows with commas:
box-shadow: 2px 2px 4px red, -2px -2px 4px blue;
Inset Shadow:
To apply shadow inside the element:
box-shadow: inset 2px 2px 5px rgba(0,0,0,0.5);
2. filter: drop-shadow()
(for images, SVGs, elements)
drop-shadow()
is part of the filter
property and applies a shadow to the visual content (not the box), useful especially for transparent images, text, or SVGs.
β Syntax:
filter: drop-shadow(offset-x offset-y blur-radius color);
No spread-radius
, but it respects transparent areas of PNGs or SVGs!
Example:
filter: drop-shadow(4px 4px 6px rgba(0,0,0,0.5));
Key Differences
Feature | box-shadow | drop-shadow() |
Used on | Any HTML element | Elements, images, SVGs |
Applies to | The box itself (border area) | The rendered image or content |
Spread control | Yes | No |
Inset option | Yes (inset ) | No |
Transparent images | No proper shadow | β Perfect for transparent PNG/SVG |
Multiple shadows | β With commas | β Only with multiple filters |
Example Comparison:
<!-- Box Shadow -->
<div style="width:100px; height:100px; background:red; box-shadow: 5px 5px 10px gray;"></div>
<!-- Drop Shadow on Image -->
<img src="logo.png" style="filter: drop-shadow(4px 4px 6px black);" />
CSS Filter
The filter
property applies graphic effects like blur, brightness, contrast, grayscale, drop shadow, etc. Itβs great for images, text, or any HTML element.
β Basic Syntax
filter: filter-function(value);
You can chain multiple filters by separating them with spaces:
filter: grayscale(50%) blur(3px);
Common Filter Functions
Filter | What It Does | Example |
blur() | Blurs the element | blur(5px) |
brightness() | Makes the element lighter/darker | brightness(1.2) |
contrast() | Increases or decreases contrast | contrast(150%) |
grayscale() | Converts to black and white | grayscale(100%) |
invert() | Inverts the colors | invert(100%) |
opacity() | Controls transparency | opacity(0.5) |
saturate() | Adjusts color saturation | saturate(200%) |
sepia() | Gives a warm brown (old photo) look | sepia(80%) |
hue-rotate() | Rotates colors (in degrees) | hue-rotate(90deg) |
drop-shadow() | Adds a shadow to the rendered content | drop-shadow(4px 4px 5px black) |
Example on Image
img {
filter: brightness(120%) contrast(110%) blur(2px);
}
π Use Cases
Make images look black & white or vintage
Highlight UI elements on hover
Add soft shadows to icons or PNGs
Enhance text contrast or readability
Create cool hover animations
Add Transition for Smooth Effects
img {
filter: grayscale(100%);
transition: filter 0.3s ease;
}
img:hover {
filter: grayscale(0%);
}
Pro Tip: backdrop-filter
You can use backdrop-filter
to apply effects behind an element (like glassmorphism):
.glass {
backdrop-filter: blur(10px);
background: rgba(255, 255, 255, 0.2);
}
List in CSS
Used to style HTML lists (<ul>
, <ol>
, <li>
).
β
1. list-style-type
Defines the type of marker (bullet or number) for list items.
ul {
list-style-type: circle;
}
Common values:
disc
(default bullet)circle
square
decimal
(numbers for<ol>
)none
(no bullet)
β
2. list-style-position
Sets where the marker appears β inside or outside the list item's content.
ul {
list-style-position: inside;
}
outside
(default) β bullet is outside the content boxinside
β bullet is inside the content box
β
3. list-style-image
Replaces the default marker with a custom image.
ul {
list-style-image: url('bullet.png');
}
β
4. list-style
(shorthand)
Combines all three in one line:
ul {
list-style: square inside url('bullet.png');
}
Anchor Link States (Pseudo-classes)
Anchor tags (<a>
) have 4 main states, often remembered as LVHA (LoVe HAte π):
β
1. :link
- Unvisited link (default state)
a:link {
color: blue;
}
β
2. :visited
- Link that the user has already clicked
a:visited {
color: purple;
}
β
3. :hover
- When the user hovers over the link
a:hover {
text-decoration: underline;
color: red;
}
β
4. :active
- When the link is being clicked (mouse down)
a:active {
color: orange;
}
Order Matters!
Always use this order:
a:link
a:visited
a:hover
a:active
(LVHA β Link, Visited, Hover, Active)
Otherwise, some states might not work as expected.
Combinators in CSS
Combinators define the relationship between selectors.
There are 4 main types:
β
1. Descendant Combinator (space
)
Selects elements that are inside another element, at any level.
div p {
color: red;
}
β
Targets all <p>
elements that are anywhere inside a <div>
, even nested deeply.
β
2. Child Combinator (>
)
Selects elements that are direct children only of a parent.
ul > li {
color: green;
}
β
Targets <li>
items that are immediate children of a <ul>
, not grandchildren.
β
3. Adjacent Sibling Combinator (+
)
Selects an element that is immediately after another element.
h1 + p {
color: blue;
}
β
Targets the first <p>
that comes right after an <h1>
.
β
4. General Sibling Combinator (~
)
Selects all siblings that come after a specific element (not just the first).
h1 ~ p {
color: purple;
}
β
Targets every <p>
after an <h1>
, as long as they share the same parent.
Summary Table
Combinator | Example | Meaning |
(space) | A B | Selects B inside A (any depth) |
> | A > B | Selects B that is a direct child of A |
+ | A + B | Selects B that is the next sibling of A |
~ | A ~ B | Selects B that is any sibling after A |
Display in CSS
The display
property specifies the display behavior (the type of rendering box) of an element.
β
block
Takes up 100% width of the parent (whole line).
Always starts on a new line.
You can set
width
andheight
.
Example elements: <div>
, <p>
, <h1>
p {
display: block;
}
Makes the paragraph take full width and start on a new line.
β
inline
Takes up only as much width as needed.
Sits side by side with other inline elements.
You cannot set
width
orheight
.
Example elements: <span>
, <a>
, <strong>
a {
display: inline;
}
Makes the anchor behave like text β no line break, no width/height control.
β
inline-block
Behaves like
inline
(sits next to others).But you can set
width
andheight
.
Best of both inline
and block
.
button {
display: inline-block;
width: 150px;
height: 40px;
}
Button stays inline with others but can have a set width and height.
Common Use Cases
Task | Use this display |
Stack items vertically | block |
Place items side-by-side | inline or inline-block |
Custom buttons or links with padding & width | inline-block |
Position in CSS
The position
property defines how an element is positioned in the document flow.
1. static
(default)
Normal document flow
You canβt use
top
,right
,bottom
,left
Used when no special positioning is needed.
Most HTML elements are
static
by default.
π Use when: You donβt need to move the element manually.
div {
position: static;
}
2. relative
Element stays in its normal position
You can move it with
top
,left
, etc. relative to itselfUse when you want to move an element slightly from its normal position.
Can also be used as a reference for
absolute
children.
π Use when:
You want to nudge an element without breaking layout.
You want to position a tooltip or badge over a parent element.
Tip: Combine with z-index
to bring things forward or behind.
div {
position: relative;
top: 10px;
left: 20px;
}
3. absolute
Removed from normal flow
Positioned relative to the nearest positioned ancestor
If no positioned ancestor β relative to
<html>
orbody
Use when you want to place something at a precise position.
It removes the element from the normal layout.
π Use when:
Creating dropdown menus.
Positioning tooltips or popups.
Designing modal dialogs or floating boxes.
π‘ Needs a parent with position: relative
or it will stick to the <body>
.
div {
position: absolute;
top: 0;
left: 0;
}
4. fixed
Stays in one place even when scrolling
Positioned relative to the viewport
Use to pin an element to a specific spot on the screen β even when scrolling.
π Use when:
You want a floating button (like a chat icon).
Creating sticky footers/headers that never move.
Displaying persistent alerts or banners.
div {
position: fixed;
bottom: 10px;
right: 10px;
}
5. sticky
Switches between
relative
andfixed
based on scrollSticks to a position when a threshold is reached
Use to make elements stick temporarily while scrolling, then release.
π Use when:
Creating sticky headers or section titles.
Sidebar menus that scroll with the content up to a point.
π‘ Needs a top
, left
, or bottom
value and scrollable parent.
div {
position: sticky;
top: 0;
}
CSS z-index
Property
Controls the stacking order of elements
Higher
z-index
= placed on topWorks only with positioned elements (
relative
,absolute
,fixed
,sticky
)Use when elements overlap and you want to control which one appears on top.
π Use when:
Creating modals, popups, or tooltips.
Fixing dropdown menus behind other elements.
Overlapping images or buttons.
π’ Higher z-index
means it sits on top.
div {
position: absolute;
z-index: 10;
}
Example:
.box1 {
z-index: 1;
}
.box2 {
z-index: 2;
}
box2
will appear above box1
.
Summary Table
Position Type | In Normal Flow? | Can Use Top/Left? | Relative To |
static | β | β | N/A |
relative | β | β | Itself |
absolute | β | β | Nearest ancestor with position |
fixed | β | β | Viewport |
sticky | β (until sticky) | β | Scroll position |
Overflow in CSS
The overflow
property controls what happens when content overflows the boundaries of its container (usually when the content is too large for the box).
β Syntax
selector {
overflow: value;
}
1. visible
(default)
Overflowing content is not clipped.
It spills out of the box.
div {
overflow: visible;
}
2. hidden
Extra content is clipped.
The overflowed part is not visible and no scrollbars appear.
div {
overflow: hidden;
}
3. scroll
Content is clipped.
Scrollbars always appear, even if not needed.
div {
overflow: scroll;
}
4. auto
Content is clipped only when needed.
Scrollbars appear only if necessary.
div {
overflow: auto;
}
Shorthand Options
You can also control horizontal and vertical overflow separately:
overflow-x: auto;
overflow-y: hidden;
Use Cases
Task | Property |
Create a scrollable box | overflow: auto; |
Hide extra content cleanly | overflow: hidden; |
Allow horizontal scrolling only | overflow-x: scroll; overflow-y: hidden; |
Prevent content from spilling out | overflow: hidden; |
Always show scrollbars (rarely used) | overflow: scroll; |
Pseudo Elements in CSS
1. ::before
- Inserts content before the elementβs actual content.
h1::before {
content: "π₯ ";
}
2. ::after
- Inserts content after the elementβs content.
h1::after {
content: " β¨";
}
You must use content:
with ::before
and ::after
.
3. ::first-letter
- Styles the first letter of a block of text.
p::first-letter {
font-size: 2rem;
color: red;
}
4. ::first-line
- Styles the first line of text in a block (depends on screen width).
p::first-line {
font-weight: bold;
}
5. ::selection
- Styles the highlighted (selected) text.
::selection {
background-color: yellow;
color: black;
}
π‘ Use Cases
Pseudo-element | Use For |
::before / ::after | Decorative icons, quotes, tooltips |
::first-letter | Drop caps in articles |
::first-line | Styling first line of paragraphs |
::selection | Customizing selected text background |
Pseudo class in CSS
A pseudo-class in CSS is used to define the special state of an element. It adds style to elements based on their state, position in the DOM, or user interaction, without needing to add extra classes or IDs.
Syntax:
selector:pseudo-class {
property: value;
}
β Common Pseudo-Classes:
πΉ User Interaction
Pseudo-Class | Description |
:hover | When user hovers over an element |
:active | When element is being clicked |
:focus | When element (like input) is focused |
:visited | For visited links |
:link | For unvisited links |
a:hover {
color: red;
}
input:focus {
border-color: blue;
}
πΉ Structural / Position-Based
Pseudo-Class | Description |
:first-child | First child of its parent |
:last-child | Last child of its parent |
:nth-child(n) | Selects the nth child |
:nth-of-type(n) | Selects the nth child of a type |
:only-child | Element that is the only child of its parent |
p:first-child {
font-weight: bold;
}
li:nth-child(2) {
color: green;
}
πΉ State or Type-Based
Pseudo-Class | Description |
:checked | For radio/checkbox when selected |
:disabled | For disabled form elements |
:enabled | For enabled form elements |
:empty | Element that has no children |
:not(selector) | Selects everything except the selector |
input:checked {
background-color: yellow;
}
div:empty {
display: none;
}
button:not(:disabled) {
cursor: pointer;
}
Column layout in CSS
The CSS multi-column layout allows you to easily divide text or content into multiple columns, similar to how newspapers and magazines format text.
Key Properties:
Property | Description |
column-count | Number of columns |
column-width | Preferred width of columns |
columns | Shorthand for column-width and column-count |
column-gap | Space between columns |
column-rule | Adds a line between columns (like a border) |
column-span | Makes an element span across all columns |
break-inside | Prevents column breaks inside an element |
Example:
.container {
column-count: 3;
column-gap: 30px;
column-rule: 1px solid #ccc;
}
<div class="container">
<p>This is some multi-column text. It will be split into 3 columns.</p>
<p>You can put any HTML content inside columns.</p>
</div>
β¨ Shorthand columns
.container {
columns: 200px 3; /* column-width first, then column-count */
}
Spanning Columns
.heading {
column-span: all;
font-weight: bold;
font-size: 24px;
}
Prevent Breaking
.card {
break-inside: avoid;
margin-bottom: 20px;
}
Use Cases
Newspaper-style articles
Blog post previews
Masonry-like layouts (with
break-inside
)Resumes or brochures
Example with column-span
and break-inside
β HTML
<div class="container">
<h2 class="heading">This Heading Spans All Columns</h2>
<div class="card">
<p>This is a card that will not break across columns.</p>
</div>
<div class="card">
<p>This is another card with more content. The entire card will stay in one column because break-inside is set to avoid.</p>
</div>
<p>Other content that will naturally flow across the columns.</p>
</div>
β CSS
.container {
columns: 3 250px;
column-gap: 30px;
column-rule: 1px solid #ccc;
}
.heading {
column-span: all;
font-size: 24px;
margin-bottom: 20px;
color: #3498db;
}
.card {
background-color: #f1f1f1;
padding: 15px;
margin-bottom: 20px;
break-inside: avoid;
border-radius: 5px;
}
.heading
usescolumn-span: all;
β it spans across all columns like a title..card
blocks havebreak-inside: avoid;
β this ensures that they donβt split between two columns even if they're long.The remaining content flows normally into columns.
Flex Box in CSS
Subscribe to my newsletter
Read articles from koustav moitra directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
