CSS
Web Styling | Beginner to Advanced
Cascading Style Sheets – Making the Web Beautiful
What is CSS?
CSS (Cascading Style Sheets) is the language used to control the visual presentation of HTML documents.
It was first proposed by Håkon Wium Lie in 1994 and standardized by the W3C. CSS separates content
(HTML) from presentation, making websites easier to maintain and redesign.
The 'cascading' in CSS refers to the order in which styles are applied. When multiple rules target the same
element, the cascade determines which rule wins based on specificity, inheritance, and source order.
How CSS Works
• Browser loads HTML and builds the DOM tree
• Browser loads CSS and builds the CSSOM tree
• DOM + CSSOM are combined into the Render Tree
• Browser calculates layout (positions and sizes)
• Browser paints pixels on the screen
Ways to Add CSS
<!-- 1. External stylesheet (recommended) -->
<link rel='stylesheet' href='[Link]'>
<!-- 2. Internal style block -->
<style>
body { background: white; }
</style>
<!-- 3. Inline style (avoid for maintainability) -->
<p style='color: red; font-size: 16px;'>Text</p>
CSS Selectors
Basic Selectors
* { } /* Universal — all elements */
p { } /* Element/type selector */
.card { } /* Class selector */
#header { } /* ID selector (unique on page) */
[type='text'] { } /* Attribute selector */
Combinators
div p { } /* Descendant — p inside div */
div > p { } /* Child — direct child p of div */
h1 + p { } /* Adjacent sibling — p right after h1 */
h1 ~ p { } /* General sibling — all p after h1 */
Pseudo-Classes
a:hover { } /* Mouse over element */
a:focus { } /* Element has keyboard focus */
a:visited { } /* Link already visited */
li:first-child { } /* First child element */
li:last-child { } /* Last child element */
li:nth-child(2) { }/* Second child */
li:nth-child(odd){} /* All odd children */
input:disabled { } /* Disabled form inputs */
p:not(.skip) { } /* All p except class .skip */
Pseudo-Elements
p::first-line { } /* First line of paragraph */
p::first-letter { }/* First letter — for drop caps */
.btn::before { content: '» '; } /* Insert before */
.btn::after { content: ' ✓'; } /* Insert after */
::selection { background: yellow; } /* Selected text */
The CSS Box Model
Every element in CSS is treated as a rectangular box. The box model describes how the size of elements is
calculated, consisting of four areas from inside to outside: content, padding, border, and margin.
div {
/* Content area */
width: 300px;
height: 200px;
/* Padding — space inside the border */
padding: 20px; /* all sides */
padding: 10px 20px; /* top/bottom left/right */
padding: 5px 10px 15px 20px; /* top right bottom left */
/* Border */
border: 2px solid #333;
border-radius: 8px; /* rounded corners */
/* Margin — space outside the border */
margin: 30px auto; /* center horizontally */
/* box-sizing: border-box makes width include padding+border */
box-sizing: border-box;
}
■ Always add * { box-sizing: border-box; } to your CSS reset — it makes layout calculations much more intuitive.
Display Property
display: block; /* Full width, starts on new line */
display: inline; /* Flows in text, no width/height */
display: inline-block; /* Inline flow but accepts width/height */
display: none; /* Remove from layout entirely */
display: flex; /* Enable Flexbox */
display: grid; /* Enable CSS Grid */
Colors
color: red; /* Named color */
color: #ff0000; /* Hex (shorthand: #f00) */
color: rgb(255, 0, 0); /* RGB */
color: rgba(255, 0, 0, 0.5); /* RGBA — 50% opacity */
color: hsl(0, 100%, 50%); /* Hue, Saturation, Lightness */
color: hsla(0, 100%, 50%, 0.5); /* HSLA with alpha */
color: oklch(0.7 0.2 30); /* Modern color space (CSS4) */
background-color: #f0f4f8;
background: linear-gradient(135deg, #667eea, #764ba2);
background: radial-gradient(circle, #ff6b6b, #feca57);
Typography
/* Font family */
font-family: 'Inter', Arial, sans-serif;
/* Import Google Font */
@import url('[Link]
/* Font properties */
font-size: 16px; /* Base size */
font-size: 1rem; /* Relative to root (better) */
font-weight: 400; /* 100-900; 400=normal, 700=bold */
font-style: italic;
line-height: 1.6; /* Unitless recommended */
letter-spacing: 0.5px;
text-align: center; /* left | right | center | justify */
text-decoration: none; /* Remove underline from links */
text-transform: uppercase;
text-overflow: ellipsis; /* Truncate overflowing text */
white-space: nowrap;
Flexbox Layout
Flexbox (Flexible Box Layout) is a one-dimensional layout method for arranging items in rows or columns. It
excels at distributing space and aligning content.
/* Flex Container */
.container {
display: flex;
flex-direction: row; /* row | column | row-reverse */
flex-wrap: wrap; /* wrap items to new line */
justify-content: space-between; /* main axis alignment */
align-items: center; /* cross axis alignment */
align-content: flex-start; /* multi-line cross axis */
gap: 16px; /* space between items */
}
/* Flex Items */
.item {
flex: 1; /* grow, shrink, basis shorthand */
flex-grow: 1; /* how much to grow */
flex-shrink: 0; /* prevent shrinking */
flex-basis: 200px; /* initial size before growing */
align-self: flex-end; /* override container alignment */
order: 2; /* change visual order */
}
justify-content Values
• flex-start – Items packed to the start
• flex-end – Items packed to the end
• center – Items centered
• space-between – Equal space between items
• space-around – Equal space around items
• space-evenly – Equal space everywhere
CSS Grid Layout
CSS Grid is a two-dimensional layout system — it handles both rows and columns simultaneously. It is the
most powerful layout tool in CSS.
/* Grid Container */
.grid {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* 3 columns */
grid-template-columns: repeat(3, 1fr); /* same thing */
grid-template-columns: 200px auto 200px;
grid-template-rows: 80px 1fr 60px;
gap: 20px; /* shorthand for row-gap + column-gap */
row-gap: 16px;
column-gap: 24px;
}
/* Grid Items — span multiple cells */
.hero {
grid-column: 1 / 3; /* span columns 1 to 3 */
grid-row: 1 / 2; /* row 1 */
}
.sidebar {
grid-column: span 1; /* span 1 column */
grid-row: span 2; /* span 2 rows */
}
/* Named areas */
.layout {
grid-template-areas:
'header header header'
'sidebar main main '
'footer footer footer';
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
CSS Positioning
position: static; /* Default — normal document flow */
position: relative; /* Offset from its normal position */
top: 10px; /* Move 10px down from where it would be */
left: 20px;
position: absolute; /* Removed from flow, positioned relative
to nearest positioned ancestor */
top: 0; right: 0; /* Top-right corner of parent */
position: fixed; /* Fixed to viewport — stays on scroll */
bottom: 20px; right: 20px; /* Floating action button */
position: sticky; /* Relative until scroll threshold, then fixed */
top: 0; /* Sticks to top when scrolled to */
z-index: 10; /* Stack order (higher = in front) */
Common Positioning Patterns
/* Center element absolutely */
.centered {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
/* Sticky navigation bar */
nav {
position: sticky;
top: 0;
background: white;
z-index: 100;
}
/* Fixed floating button */
.fab {
position: fixed;
bottom: 24px; right: 24px;
width: 56px; height: 56px;
border-radius: 50%;
}
Responsive Design & Media Queries
Responsive design ensures your website looks great on all devices — from mobile phones to desktop
monitors. The key tools are media queries, flexible units, and fluid layouts.
/* Mobile-first approach (recommended) */
/* Base styles — mobile */
.container { width: 100%; padding: 16px; }
.nav { flex-direction: column; }
/* Tablet — min-width: 768px */
@media (min-width: 768px) {
.container { max-width: 768px; margin: 0 auto; }
.nav { flex-direction: row; }
.grid { grid-template-columns: repeat(2, 1fr); }
}
/* Desktop — min-width: 1024px */
@media (min-width: 1024px) {
.container { max-width: 1200px; }
.grid { grid-template-columns: repeat(3, 1fr); }
}
/* Large screens */
@media (min-width: 1440px) {
.container { max-width: 1440px; }
}
/* Dark mode preference */
@media (prefers-color-scheme: dark) {
body { background: #1a1a2e; color: #eee; }
}
/* Reduced motion for accessibility */
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; }
}
Transitions & Animations
Transitions
/* Smooth hover effect */
.button {
background: #2196f3;
transition: background 0.3s ease, transform 0.2s ease;
}
.button:hover {
background: #1565c0;
transform: translateY(-2px);
}
/* transition shorthand */
transition: property duration timing-function delay;
transition: all 0.3s ease-in-out 0s;
Keyframe Animations
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
.card {
animation: fadeIn 0.5s ease forwards;
}
.loader {
animation: spin 1s linear infinite;
}
/* animation shorthand */
animation: name duration timing-function delay
iteration-count direction fill-mode;
CSS Custom Properties (Variables)
:root {
/* Define variables globally */
--primary: #2196f3;
--secondary: #ff5722;
--bg: #ffffff;
--text: #333333;
--radius: 8px;
--shadow: 0 4px 12px rgba(0,0,0,0.1);
--font-main: 'Inter', sans-serif;
--spacing-sm: 8px;
--spacing-md: 16px;
--spacing-lg: 32px;
}
.card {
background: var(--bg);
color: var(--text);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: var(--spacing-md);
}
.btn-primary {
background: var(--primary);
}
/* Override locally */
.dark-section {
--bg: #1a1a2e;
--text: #eeeeee;
}
Modern CSS Features
• clamp() – Fluid sizing: clamp(1rem, 2.5vw, 2rem)
• min() / max() – Responsive widths: width: min(600px, 100%)
• aspect-ratio: 16/9 – Maintain proportions easily
• gap on flex/grid – Clean spacing without margins
• Logical properties – margin-inline, padding-block for RTL support
• :is() / :where() – Group selectors efficiently
• container queries – Style based on parent width (2023+)
• @layer – Manage cascade layers explicitly
Specificity & The Cascade
When multiple CSS rules target the same element, specificity determines which rule wins. Specificity is
calculated as a three-part score: (ID, Class, Element).
• Inline styles: 1,0,0,0 (highest)
• ID selectors (#header): 0,1,0,0
• Class, attribute, pseudo-class (.btn, [type], :hover): 0,0,1,0
• Element, pseudo-element (p, ::before): 0,0,0,1
• Universal selector (*): 0,0,0,0 (no specificity)
/* Specificity: 0,0,0,1 */
p { color: blue; }
/* Specificity: 0,0,1,0 — wins over above */
.intro { color: green; }
/* Specificity: 0,1,0,0 — wins over above */
#main { color: red; }
/* !important — overrides all (avoid using) */
p { color: purple !important; }
Inheritance
Some CSS properties are inherited by child elements (font-family, color, line-height). Others are not
inherited (margin, padding, border, background). You can explicitly control inheritance:
color: inherit; /* Force inheritance */
color: initial; /* Reset to browser default */
color: unset; /* Inherited if inheritable, else initial */
color: revert; /* Reset to browser stylesheet value */
CSS Best Practices
• Use a CSS reset or [Link] to ensure consistency across browsers
• Follow a naming convention like BEM (Block__Element--Modifier)
• Use CSS custom properties for colors, spacing, and typography
• Write mobile-first — add complexity for larger screens
• Avoid using !important; fix specificity issues properly
• Keep selectors short and flat — avoid over-nesting
• Use shorthand properties: margin, padding, font, background
• Organize CSS in sections: reset, variables, base, layout, components
• Use rem for font sizes and spacing (scales with user preferences)
• Lint your CSS with Stylelint to catch errors automatically
CSS Methodologies
• BEM – Block Element Modifier: .card__title--highlighted
• SMACSS – Scalable and Modular Architecture for CSS
• OOCSS – Object Oriented CSS: separate structure from skin
• Utility-first – Tailwind CSS approach with small utility classes
• CSS-in-JS – Styled-components, Emotion for React applications
Learning Resources
• MDN CSS Reference – [Link]/en-US/docs/Web/CSS
• CSS Tricks – [Link] (deep dives and guides)
• Flexbox Froggy – [Link] (interactive game)
• Grid Garden – [Link] (interactive game)
• Lea Verou's CSS Secrets book – advanced techniques
• Can I Use – [Link] (browser support tables)
■ CSS is easy to learn but takes years to master. Focus on Flexbox and Grid as your primary layout tools — they
cover 95% of all layout needs.