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

koustav moitrakoustav moitra
28 min read

Table of contents

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

MethodHow to UseExample
InlineInside the HTML tag<p style="color:red;">Text</p>
InternalInside a <style> tag in <head><style>p { color: red; }</style>
External βœ…Linked .css file<link rel="stylesheet" href="styles.css">
πŸ’‘
External is the best for real projects.

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.

SelectorMeaning
:hoverWhen mouse is over element
:focusWhen an input is focused
:first-childFirst child of a parent
:last-childLast 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 TypeSpecificity Score
Element (p)1
Class (.x)10
ID (#id)100
Inline Style1000
<!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 wheel

  • Saturation: 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:

FormatExampleNotes
Color nameredSimple, readable
HEX#FF0000Compact, web standard
RGBrgb(255, 0, 0)Easy for dynamic values
RGBArgba(255, 0, 0, 0.5)Supports transparency
HSLhsl(0, 100%, 50%)Great for tweaking colors
HSLAhsla(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.

UnitDescriptionExample
pxPixels (screen dots)width: 100px;
ptPoints (1pt = 1/72 inch)font-size: 12pt;
cmCentimetersmargin: 2cm;
mmMillimeterspadding: 10mm;
inInches (1in = 2.54cm)width: 1in;
pcPicas (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.

UnitRelative ToExample
%Parent elementwidth: 50%;
emFont size of the parentpadding: 2em;
remFont size of the root (<html>)font-size: 1.5rem;
vw1% of the viewport widthwidth: 80vw;
vh1% of the viewport heightheight: 50vh;
vmin1% of the smaller of vw or vhfont-size: 5vmin;
vmax1% of the larger of vw or vhpadding: 3vmax;
chWidth of the character "0"width: 40ch;
exx-height (height of lowercase "x")line-height: 2ex;

Use Case: Responsive layouts, scaling text, flexible designs.


βœ… Quick Comparison:

ScenarioUse Unit
Responsive layout%, vw, vh, rem
Font size (scalable)em, rem
Fixed-size elementspx
Print layoutcm, 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.

πŸ’‘
Fallback fonts are alternative fonts that the browser will use if the primary font is not available.
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 Roman

  • sans-serif – like Arial

  • monospace – like Courier

  • cursive, 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.

box model

  • 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.
PropertyDescriptionExample
widthSets the width of the contentwidth: 300px;
heightSets the height of the contentheight: 150px;
min-width, max-widthSet limits on widthmax-width: 500px;
min-height, max-heightSet limits on heightmin-height: 100px;
overflowControls content overflowoverflow: hidden;
displayAffects box behaviordisplay: block;

πŸ”Ή 2. Padding Area

  • Space between content and border.
PropertyDescriptionExample
paddingShorthand for all sidespadding: 20px;
padding-topTop paddingpadding-top: 10px;
padding-rightRight paddingpadding-right: 15px;
padding-bottomBottom paddingpadding-bottom: 10px;
padding-leftLeft paddingpadding-left: 15px;

πŸ”Ή 3. Border Area

  • The visible edge surrounding padding and content.
PropertyDescriptionExample
borderShorthand for width, style, colorborder: 1px solid black;
border-widthControls thicknessborder-width: 2px;
border-styleControls style (solid, dashed, etc.)border-style: dashed;
border-colorSets the border colorborder-color: red;
border-top, border-right, border-bottom, border-leftIndividual bordersborder-top: 2px dotted blue;
border-radiusRounds cornersborder-radius: 10px;

πŸ”Ή 4. Margin Area

  • Space outside the border, between this element and others.
PropertyDescriptionExample
marginShorthand for all sidesmargin: 10px;
margin-topTop marginmargin-top: 5px;
margin-rightRight marginmargin-right: 10px;
margin-bottomBottom marginmargin-bottom: 5px;
margin-leftLeft marginmargin-left: 10px;
margin: autoCenters an element (used with width)margin: auto;

πŸ”Ή 5. Box Behavior / Control

  • Properties that influence how the box behaves.
PropertyDescriptionExample
box-sizingDefines how width/height are calculatedbox-sizing: border-box;
displayBlock, inline, flex, grid, etc.display: flex;
visibilityShow/hide the boxvisibility: hidden;
overflowWhat happens if content overflowsoverflow: scroll;
outlineA 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

TypeFunction
linear-gradientTransitions in a line
radial-gradientRadiates from center
conic-gradientSpins 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 edges

  • spread-radius (optional) β†’ Expand or shrink the shadow

  • color β†’ 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

Featurebox-shadowdrop-shadow()
Used onAny HTML elementElements, images, SVGs
Applies toThe box itself (border area)The rendered image or content
Spread controlYesNo
Inset optionYes (inset)No
Transparent imagesNo 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

FilterWhat It DoesExample
blur()Blurs the elementblur(5px)
brightness()Makes the element lighter/darkerbrightness(1.2)
contrast()Increases or decreases contrastcontrast(150%)
grayscale()Converts to black and whitegrayscale(100%)
invert()Inverts the colorsinvert(100%)
opacity()Controls transparencyopacity(0.5)
saturate()Adjusts color saturationsaturate(200%)
sepia()Gives a warm brown (old photo) looksepia(80%)
hue-rotate()Rotates colors (in degrees)hue-rotate(90deg)
drop-shadow()Adds a shadow to the rendered contentdrop-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 box

  • inside β€” 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 πŸ˜„):

  • 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

CombinatorExampleMeaning
(space)A BSelects B inside A (any depth)
>A > BSelects B that is a direct child of A
+A + BSelects B that is the next sibling of A
~A ~ BSelects 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 and height.

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 or height.

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 and height.

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

TaskUse this display
Stack items verticallyblock
Place items side-by-sideinline or inline-block
Custom buttons or links with padding & widthinline-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 itself

  • Use 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> or body

  • 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 and fixed based on scroll

  • Sticks 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 top

  • Works 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 TypeIn 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

TaskProperty
Create a scrollable boxoverflow: auto;
Hide extra content cleanlyoverflow: hidden;
Allow horizontal scrolling onlyoverflow-x: scroll; overflow-y: hidden;
Prevent content from spilling outoverflow: 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-elementUse For
::before / ::afterDecorative icons, quotes, tooltips
::first-letterDrop caps in articles
::first-lineStyling first line of paragraphs
::selectionCustomizing 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-ClassDescription
:hoverWhen user hovers over an element
:activeWhen element is being clicked
:focusWhen element (like input) is focused
:visitedFor visited links
:linkFor unvisited links
a:hover {
  color: red;
}
input:focus {
  border-color: blue;
}

πŸ”Ή Structural / Position-Based

Pseudo-ClassDescription
:first-childFirst child of its parent
:last-childLast child of its parent
:nth-child(n)Selects the nth child
:nth-of-type(n)Selects the nth child of a type
:only-childElement 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-ClassDescription
:checkedFor radio/checkbox when selected
:disabledFor disabled form elements
:enabledFor enabled form elements
:emptyElement 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:

PropertyDescription
column-countNumber of columns
column-widthPreferred width of columns
columnsShorthand for column-width and column-count
column-gapSpace between columns
column-ruleAdds a line between columns (like a border)
column-spanMakes an element span across all columns
break-insidePrevents 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 uses column-span: all; – it spans across all columns like a title.

  • .card blocks have break-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

0
Subscribe to my newsletter

Read articles from koustav moitra directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

koustav moitra
koustav moitra