Table of Contents
- Introduction to CSS
- CSS Syntax and Selectors
- Adding CSS to HTML
- Colors and Backgrounds
- The Box Model
- Typography
- Layout Techniques
- Positioning
- Flexbox
- CSS Grid
- Responsive Design
- Transitions and Animations
- Transforms
- Pseudo-classes and Pseudo-elements
- CSS Variables
- Best Practices
Introduction to CSS
CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of HTML documents. While HTML provides structure, CSS controls the visual appearance including layout, colors, fonts, and responsive behavior.
Why CSS?
- Separation of Concerns: Keep content (HTML) separate from presentation (CSS)
- Reusability: Apply styles across multiple pages
- Maintainability: Update styles in one place
- Responsive Design: Adapt layouts to different screen sizes
- Performance: Optimize page rendering
CSS Syntax and Selectors
Basic Syntax
selector {
property: value;
property: value;
}CSSExample:
h1 {
color: blue;
font-size: 24px;
}CSSTypes of Selectors
1. Universal Selector
Selects all elements.
* {
margin: 0;
padding: 0;
}CSS2. Element Selector
Selects all elements of a given type.
p {
line-height: 1.6;
}CSS3. Class Selector
Selects elements with a specific class attribute.
.button {
background-color: blue;
padding: 10px 20px;
}CSS<button class="button">Click Me</button>HTML4. ID Selector
Selects a unique element with a specific ID.
#header {
height: 80px;
background: navy;
}CSS<header id="header">Header Content</header>HTML5. Attribute Selector
Selects elements based on attributes.
input[type="text"] {
border: 1px solid #ccc;
}
a[href^="https"] {
color: green;
}
img[alt*="logo"] {
width: 100px;
}CSS6. Combinator Selectors
Descendant Selector (space)
div p {
color: red;
}CSSChild Selector (>)
ul > li {
list-style: none;
}CSSAdjacent Sibling Selector (+)
h2 + p {
font-weight: bold;
}CSSGeneral Sibling Selector (~)
h2 ~ p {
color: gray;
}CSS7. Grouping Selectors
h1, h2, h3 {
font-family: Arial, sans-serif;
}CSSSpecificity
CSS specificity determines which styles are applied when multiple rules target the same element.
Specificity Hierarchy (highest to lowest):
- Inline styles (style attribute)
- IDs
- Classes, attributes, and pseudo-classes
- Elements and pseudo-elements
Example:
/* Specificity: 0-0-1 */
p { color: black; }
/* Specificity: 0-1-0 */
.text { color: blue; }
/* Specificity: 1-0-0 */
#main { color: red; }
/* Specificity: 1-1-1 */
#main .text p { color: green; }CSSAdding CSS to HTML
1. Inline CSS
Directly in HTML elements using the style attribute.
<p style="color: red; font-size: 16px;">Inline styled text</p>HTML2. Internal CSS
Within a <style> tag in the HTML document’s <head>.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #f0f0f0;
}
h1 {
color: navy;
}
</style>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>HTML3. External CSS (Recommended)
Link to an external CSS file using the <link> tag.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Hello World</h1>
</body>
</html>HTMLstyles.css:
body {
background-color: #f0f0f0;
}
h1 {
color: navy;
}CSSColors and Backgrounds
Color Values
1. Named Colors
p {
color: red;
}CSS2. Hexadecimal
h1 {
color: #ff5733;
}CSS3. RGB
div {
color: rgb(255, 87, 51);
}CSS4. RGBA (with transparency)
div {
background-color: rgba(255, 87, 51, 0.5);
}CSS5. HSL
p {
color: hsl(9, 100%, 60%);
}CSS6. HSLA
p {
color: hsla(9, 100%, 60%, 0.8);
}CSSBackground Properties
.box {
/* Background color */
background-color: #f0f0f0;
/* Background image */
background-image: url('image.jpg');
/* Background repeat */
background-repeat: no-repeat; /* repeat, repeat-x, repeat-y */
/* Background position */
background-position: center center; /* top, bottom, left, right, center */
/* Background size */
background-size: cover; /* contain, auto, or specific dimensions */
/* Background attachment */
background-attachment: fixed; /* scroll, local */
/* Shorthand */
background: #f0f0f0 url('image.jpg') no-repeat center/cover;
}CSSGradients
Linear Gradient
.gradient-linear {
background: linear-gradient(to right, red, yellow);
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
background: linear-gradient(to bottom, red 0%, yellow 50%, green 100%);
}CSSRadial Gradient
.gradient-radial {
background: radial-gradient(circle, red, yellow, green);
background: radial-gradient(ellipse at center, #ff6b6b, #4ecdc4);
}CSSThe Box Model
The CSS box model describes how elements are rendered with content, padding, border, and margin.
+----------------------------------+
| MARGIN |
| +--------------------------+ |
| | BORDER | |
| | +-------------------+ | |
| | | PADDING | | |
| | | +------------+ | | |
| | | | CONTENT | | | |
| | | +------------+ | | |
| | +-------------------+ | |
| +--------------------------+ |
+----------------------------------+CSSBox Model Properties
.box {
/* Content dimensions */
width: 300px;
height: 200px;
/* Padding (space inside border) */
padding: 20px;
padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 15px;
padding: 10px 15px; /* top/bottom right/left */
padding: 10px 15px 20px 25px; /* top right bottom left */
/* Border */
border: 2px solid black;
border-width: 2px;
border-style: solid; /* dashed, dotted, double, groove, ridge, inset, outset */
border-color: black;
border-radius: 10px; /* rounded corners */
/* Margin (space outside border) */
margin: 20px;
margin-top: 10px;
margin-right: auto; /* center horizontally */
margin-bottom: 10px;
margin-left: auto;
margin: 10px 20px; /* top/bottom right/left */
}CSSBox Sizing
/* Default: width/height applies only to content */
.box-default {
box-sizing: content-box;
width: 300px;
padding: 20px;
border: 5px solid black;
/* Total width: 300 + 40 + 10 = 350px */
}
/* Border-box: width/height includes padding and border */
.box-border {
box-sizing: border-box;
width: 300px;
padding: 20px;
border: 5px solid black;
/* Total width: 300px */
}
/* Apply to all elements (recommended) */
* {
box-sizing: border-box;
}CSSTypography
Font Properties
.text {
/* Font family */
font-family: Arial, Helvetica, sans-serif;
font-family: 'Georgia', serif;
font-family: 'Courier New', monospace;
/* Font size */
font-size: 16px;
font-size: 1.5em;
font-size: 1.5rem;
font-size: 100%;
/* Font weight */
font-weight: normal; /* 400 */
font-weight: bold; /* 700 */
font-weight: 300; /* light */
font-weight: 600; /* semi-bold */
/* Font style */
font-style: normal;
font-style: italic;
font-style: oblique;
/* Line height */
line-height: 1.6;
line-height: 24px;
/* Text alignment */
text-align: left;
text-align: center;
text-align: right;
text-align: justify;
/* Text decoration */
text-decoration: none;
text-decoration: underline;
text-decoration: line-through;
text-decoration: overline;
/* Text transform */
text-transform: none;
text-transform: uppercase;
text-transform: lowercase;
text-transform: capitalize;
/* Letter spacing */
letter-spacing: 2px;
letter-spacing: 0.1em;
/* Word spacing */
word-spacing: 5px;
/* Text shadow */
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
text-shadow: 0 0 10px red;
}CSSWeb Fonts
Google Fonts
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" rel="stylesheet">HTMLbody {
font-family: 'Roboto', sans-serif;
}CSS@font-face
@font-face {
font-family: 'CustomFont';
src: url('fonts/customfont.woff2') format('woff2'),
url('fonts/customfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
body {
font-family: 'CustomFont', sans-serif;
}CSSLayout Techniques
Display Property
/* Block-level element */
.block {
display: block;
width: 100%;
}
/* Inline element */
.inline {
display: inline;
/* width and height don't apply */
}
/* Inline-block */
.inline-block {
display: inline-block;
width: 200px;
/* width and height apply, but stays inline */
}
/* Hide element */
.hidden {
display: none; /* removes from layout */
}
.invisible {
visibility: hidden; /* hides but keeps space */
}CSSFloat (Legacy)
.float-left {
float: left;
width: 50%;
}
.float-right {
float: right;
width: 30%;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}CSSPositioning
Position Property
1. Static (Default)
.static {
position: static;
/* Follows normal document flow */
}CSS2. Relative
Positioned relative to its normal position.
.relative {
position: relative;
top: 20px;
left: 30px;
/* Offset from original position */
}CSS3. Absolute
Positioned relative to nearest positioned ancestor.
.container {
position: relative;
}
.absolute {
position: absolute;
top: 0;
right: 0;
/* Positioned relative to .container */
}CSS4. Fixed
Positioned relative to viewport.
.fixed-header {
position: fixed;
top: 0;
left: 0;
width: 100%;
/* Stays fixed during scroll */
}CSS5. Sticky
Switches between relative and fixed based on scroll position.
.sticky-nav {
position: sticky;
top: 0;
/* Becomes fixed when reaching top */
}CSSZ-Index
Controls stacking order of positioned elements.
.behind {
position: relative;
z-index: 1;
}
.front {
position: relative;
z-index: 10;
}CSSFlexbox – Complete Guide
Flexbox (Flexible Box Layout) is a powerful one-dimensional layout system designed for distributing space and aligning items within a container, even when their sizes are unknown or dynamic.
Why Use Flexbox?
- One-dimensional layouts: Perfect for rows OR columns
- Dynamic sizing: Items can grow and shrink to fill available space
- Alignment control: Easy vertical and horizontal alignment
- Source order independence: Visual order can differ from HTML order
- Responsive: Adapts naturally to different screen sizes
Flexbox Axes
Flexbox operates on two axes:
- Main Axis: Primary direction (defined by flex-direction)
- Cross Axis: Perpendicular to main axis
flex-direction: row (default)
Main Axis →
┌─────────────────┐
│ Item Item Item│ ↑
└─────────────────┘ Cross Axis
flex-direction: column
┌──────┐
│ Item │ ↓ Main Axis
│ Item │
│ Item │
└──────┘
← Cross Axis →CSSFlex Container Properties
1. display: flex
Activates flexbox layout on the container.
.container {
display: flex; /* Block-level flex container */
display: inline-flex; /* Inline flex container */
}CSS2. flex-direction
Defines the main axis direction.
.container {
flex-direction: row; /* Default: left to right */
flex-direction: row-reverse; /* Right to left */
flex-direction: column; /* Top to bottom */
flex-direction: column-reverse; /* Bottom to top */
}CSSExample:
<div class="container row-demo">
<div>1</div>
<div>2</div>
<div>3</div>
</div>HTML.row-demo {
display: flex;
flex-direction: row;
gap: 10px;
}
.row-demo > div {
padding: 20px;
background: #3498db;
color: white;
}CSS3. flex-wrap
Controls whether items wrap to new lines.
.container {
flex-wrap: nowrap; /* Default: all items on one line */
flex-wrap: wrap; /* Wrap to multiple lines */
flex-wrap: wrap-reverse; /* Wrap in reverse order */
}CSSExample:
.card-container {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 0 0 300px; /* Don't grow, don't shrink, 300px base */
}CSS4. flex-flow (Shorthand)
Combines flex-direction and flex-wrap.
.container {
flex-flow: row wrap;
/* Same as:
flex-direction: row;
flex-wrap: wrap;
*/
}CSS5. justify-content
Aligns items along the main axis.
.container {
justify-content: flex-start; /* Default: pack to start */
justify-content: flex-end; /* Pack to end */
justify-content: center; /* Center items */
justify-content: space-between; /* Equal space between, no space at edges */
justify-content: space-around; /* Equal space around each item */
justify-content: space-evenly; /* Equal space everywhere */
}CSSVisual Examples:
/* flex-start */
[1][2][3]___________
/* flex-end */
___________[1][2][3]
/* center */
_____[1][2][3]______
/* space-between */
[1]_______[2]_______[3]
/* space-around */
__[1]____[2]____[3]__
/* space-evenly */
___[1]___[2]___[3]___CSS6. align-items
Aligns items along the cross axis (single line).
.container {
align-items: stretch; /* Default: stretch to fill container */
align-items: flex-start; /* Align to cross-start */
align-items: flex-end; /* Align to cross-end */
align-items: center; /* Center on cross axis */
align-items: baseline; /* Align baselines */
}CSSExample:
.header {
display: flex;
align-items: center; /* Vertically center logo and nav */
height: 80px;
}
.logo {
height: 50px;
}
.nav {
margin-left: auto; /* Push to right */
}CSS7. align-content
Aligns multiple lines along the cross axis (only works with flex-wrap).
.container {
display: flex;
flex-wrap: wrap;
align-content: flex-start;
align-content: flex-end;
align-content: center;
align-content: space-between;
align-content: space-around;
align-content: stretch; /* Default */
}CSS8. gap
Sets spacing between flex items (modern browsers).
.container {
display: flex;
gap: 20px; /* Gap in both directions */
row-gap: 20px; /* Vertical gap */
column-gap: 30px; /* Horizontal gap */
}CSSFlex Item Properties
1. flex-grow
Defines how much an item should grow relative to other items.
.item {
flex-grow: 0; /* Default: don't grow */
flex-grow: 1; /* Grow equally */
flex-grow: 2; /* Grow twice as much */
}CSSExample:
.container {
display: flex;
width: 600px;
}
.sidebar {
flex-grow: 1; /* Gets 1 part */
/* Will be: 200px */
}
.main {
flex-grow: 2; /* Gets 2 parts */
/* Will be: 400px */
}CSS2. flex-shrink
Defines how much an item should shrink when space is limited.
.item {
flex-shrink: 1; /* Default: can shrink */
flex-shrink: 0; /* Don't shrink */
flex-shrink: 2; /* Shrink twice as fast */
}CSSExample:
.logo {
flex-shrink: 0; /* Never shrink logo */
width: 150px;
}
.search {
flex-shrink: 1; /* Search bar can shrink */
}CSS3. flex-basis
Sets the initial size before flex-grow/shrink apply.
.item {
flex-basis: auto; /* Default: based on content */
flex-basis: 200px; /* Specific size */
flex-basis: 50%; /* Percentage of container */
flex-basis: 0; /* Ignore content size */
}CSS4. flex (Shorthand)
Combines flex-grow, flex-shrink, and flex-basis.
.item {
/* flex: grow shrink basis */
flex: 1; /* flex: 1 1 0% */
flex: 1 0 auto; /* Grow, don't shrink, auto basis */
flex: 0 0 200px; /* Fixed 200px width */
flex: 2; /* Grow twice as much as flex: 1 items */
}CSSCommon Patterns:
/* Equal width items */
.item { flex: 1; }
/* Fixed width, no grow/shrink */
.sidebar { flex: 0 0 250px; }
/* Content-based, can grow */
.content { flex: 1 0 auto; }CSS5. align-self
Overrides align-items for individual items.
.item {
align-self: auto; /* Default: inherit from container */
align-self: flex-start;
align-self: flex-end;
align-self: center;
align-self: stretch;
align-self: baseline;
}CSSExample:
.container {
display: flex;
align-items: flex-start;
}
.featured-item {
align-self: stretch; /* Only this item stretches */
}CSS6. order
Controls visual order of items (doesn’t affect tab order).
.item {
order: 0; /* Default */
order: 1; /* Appears later */
order: -1; /* Appears earlier */
}CSSExample:
.main-content {
order: 2;
}
.sidebar {
order: 1; /* Appears before main on mobile */
}
@media (min-width: 768px) {
.sidebar {
order: 3; /* Appears after main on desktop */
}
}CSSPractical Flexbox Patterns
Pattern 1: Perfect Centering
.center-container {
display: flex;
justify-content: center; /* Horizontal center */
align-items: center; /* Vertical center */
min-height: 100vh;
}CSS<div class="center-container">
<div class="content">Perfectly Centered!</div>
</div>HTMLPattern 2: Sticky Footer
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1; /* Takes all available space */
}
footer {
/* Stays at bottom */
}CSSPattern 3: Navigation Bar
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
}
.nav-links {
display: flex;
gap: 2rem;
list-style: none;
}
.nav-button {
margin-left: auto; /* Pushes button to right */
}CSSPattern 4: Card Layout
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 1 1 calc(33.333% - 20px); /* 3 columns */
min-width: 250px; /* Responsive breakpoint */
display: flex;
flex-direction: column;
}
.card-content {
flex: 1; /* Push button to bottom */
}
.card-button {
margin-top: auto; /* Align to bottom */
}CSSPattern 5: Split Screen
.split-container {
display: flex;
min-height: 100vh;
}
.split-left,
.split-right {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
}
.split-left {
background: #2c3e50;
}
.split-right {
background: #ecf0f1;
}CSSPattern 6: Media Object
.media {
display: flex;
gap: 1rem;
}
.media-image {
flex-shrink: 0; /* Don't shrink image */
width: 100px;
height: 100px;
}
.media-content {
flex: 1; /* Take remaining space */
}CSSPattern 7: Form Layout
.form-row {
display: flex;
gap: 1rem;
margin-bottom: 1rem;
}
.form-field {
flex: 1; /* Equal width fields */
display: flex;
flex-direction: column;
}
.form-field.full-width {
flex-basis: 100%; /* Full width field */
}
.form-field.narrow {
flex: 0 0 150px; /* Fixed narrow field */
}CSSPattern 8: Pricing Cards
.pricing-container {
display: flex;
justify-content: center;
align-items: stretch; /* Equal height cards */
gap: 2rem;
flex-wrap: wrap;
}
.pricing-card {
flex: 0 1 300px;
display: flex;
flex-direction: column;
border: 2px solid #ddd;
border-radius: 8px;
padding: 2rem;
}
.pricing-card.featured {
transform: scale(1.05);
border-color: #3498db;
}
.pricing-features {
flex: 1; /* Push button to bottom */
margin: 2rem 0;
}
.pricing-button {
margin-top: auto;
}CSSResponsive Flexbox
/* Mobile: Stack vertically */
.responsive-container {
display: flex;
flex-direction: column;
gap: 1rem;
}
/* Tablet: 2 columns */
@media (min-width: 768px) {
.responsive-container {
flex-direction: row;
flex-wrap: wrap;
}
.responsive-item {
flex: 1 1 calc(50% - 0.5rem);
}
}
/* Desktop: 3 columns */
@media (min-width: 1024px) {
.responsive-item {
flex: 1 1 calc(33.333% - 0.667rem);
}
}CSSCommon Flexbox Issues and Solutions
Issue 1: Items Overflow Container
Problem:
.item {
flex-shrink: 0; /* Items won't shrink */
min-width: 300px;
}CSSSolution:
.item {
flex-shrink: 1; /* Allow shrinking */
min-width: 0; /* Reset min-width */
}CSSIssue 2: Text Overflow in Flex Items
Problem: Text doesn’t wrap in flex items.
Solution:
.flex-item {
min-width: 0; /* Important! */
overflow-wrap: break-word;
}CSSIssue 3: Unequal Heights
Problem: Cards have different heights.
Solution:
.card-container {
display: flex;
align-items: stretch; /* Default, but be explicit */
}
.card {
display: flex;
flex-direction: column;
}CSSFlexbox vs Grid: When to Use What?
Use Flexbox when:
- Creating one-dimensional layouts (rows OR columns)
- Content size drives layout
- You need alignment control
- Building navigation, toolbars, or UI components
- Order matters (using order property)
Use Grid when:
- Creating two-dimensional layouts (rows AND columns)
- Layout drives content size
- You need precise placement
- Building page layouts or complex grids
Use both:
/* Grid for page layout */
.page {
display: grid;
grid-template-columns: 200px 1fr;
}
/* Flexbox for components within grid */
.header {
display: flex;
justify-content: space-between;
align-items: center;
}CSSCSS Grid – Complete Guide
CSS Grid is a powerful two-dimensional layout system that allows you to create complex layouts with rows and columns simultaneously.
Why Use CSS Grid?
- Two-dimensional layouts: Control both rows AND columns
- Precise placement: Put items exactly where you want
- Responsive by design: Built-in responsive capabilities
- Less markup: Cleaner HTML with fewer wrapper divs
- Overlap items: Layer elements easily
- Alignment control: Powerful alignment options
Grid Terminology
┌─────────────────────────────────┐
│ Grid Container │
│ ┌───────┬───────┬───────┐ │
│ │Grid │Grid │Grid │← Grid Line (column)
│ │Item │Item │Item │ │
│ ├───────┼───────┼───────┤← Grid Line (row)
│ │Grid │Grid │Grid │ │
│ │Track │Track │Track │ │
│ │(row) │(row) │(row) │ │
│ └───────┴───────┴───────┘ │
│ ↑ ↑ ↑ │
│ Grid Track (column) │
│ │
│ ┌───────┐ ← Grid Cell │
│ │Gap │ │
│ └───────┘ │
└─────────────────────────────────┘CSS- Grid Container: Element with
display: grid - Grid Item: Direct children of grid container
- Grid Line: Dividing lines that make up the grid
- Grid Track: Space between two adjacent grid lines (row or column)
- Grid Cell: Single unit of the grid
- Grid Area: Rectangular space spanning multiple cells
Creating a Grid
Basic Grid Setup
.grid-container {
display: grid; /* Block-level grid */
display: inline-grid; /* Inline grid */
}CSSGrid Container Properties
1. grid-template-columns
Defines column structure.
.grid {
/* Fixed widths */
grid-template-columns: 200px 300px 200px;
/* Fractional units (fr) - flexible */
grid-template-columns: 1fr 2fr 1fr; /* 1:2:1 ratio */
/* Mix units */
grid-template-columns: 200px 1fr 300px;
/* Repeat notation */
grid-template-columns: repeat(3, 1fr); /* Three equal columns */
grid-template-columns: repeat(4, 100px);
/* Auto columns */
grid-template-columns: auto auto auto;
/* Min-max */
grid-template-columns: repeat(3, minmax(200px, 1fr));
/* Responsive (auto-fit) */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
/* Responsive (auto-fill) */
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}CSSauto-fit vs auto-fill:
/* auto-fill: Creates empty tracks if space available */
.grid-fill {
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
/* [item][item][empty][empty] */
}
/* auto-fit: Collapses empty tracks */
.grid-fit {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
/* [item][item] - items stretch to fill */
}CSS2. grid-template-rows
Defines row structure.
.grid {
/* Fixed heights */
grid-template-rows: 100px 200px 100px;
/* Flexible */
grid-template-rows: 1fr 2fr 1fr;
/* Auto-sized */
grid-template-rows: auto 1fr auto; /* Header, content, footer */
/* Repeat */
grid-template-rows: repeat(3, 150px);
/* Min-max */
grid-template-rows: repeat(3, minmax(100px, auto));
}CSS3. grid-template-areas
Defines named grid areas (visual layout).
.grid {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"sidebar main main"
"footer footer footer";
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: auto 1fr 1fr auto;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }CSSComplex Layout Example:
.dashboard {
display: grid;
grid-template-areas:
"nav header header header"
"nav main main aside"
"nav main main aside"
"nav footer footer footer";
grid-template-columns: 200px 1fr 1fr 250px;
grid-template-rows: 60px 1fr 1fr 80px;
gap: 20px;
min-height: 100vh;
}
.nav { grid-area: nav; }
.header { grid-area: header; }
.main { grid-area: main; }
.aside { grid-area: aside; }
.footer { grid-area: footer; }CSSEmpty cells with dots:
.grid {
grid-template-areas:
"header header header"
"sidebar main ."
"footer footer .";
/* Dot (.) represents empty cell */
}CSS4. gap (formerly grid-gap)
Sets spacing between grid items.
.grid {
/* Both row and column gap */
gap: 20px;
/* Different gaps */
gap: 20px 30px; /* row-gap column-gap */
/* Individual gaps */
row-gap: 20px;
column-gap: 30px;
}CSS5. justify-items
Aligns items horizontally within their cells.
.grid {
justify-items: stretch; /* Default: fill cell width */
justify-items: start; /* Align to left */
justify-items: end; /* Align to right */
justify-items: center; /* Center horizontally */
}CSS6. align-items
Aligns items vertically within their cells.
.grid {
align-items: stretch; /* Default: fill cell height */
align-items: start; /* Align to top */
align-items: end; /* Align to bottom */
align-items: center; /* Center vertically */
}CSS7. place-items (Shorthand)
.grid {
place-items: center; /* align-items justify-items */
place-items: center start; /* align-items / justify-items */
}CSS8. justify-content
Aligns the entire grid horizontally within the container.
.grid {
justify-content: start; /* Default */
justify-content: end;
justify-content: center;
justify-content: stretch;
justify-content: space-around;
justify-content: space-between;
justify-content: space-evenly;
}CSS9. align-content
Aligns the entire grid vertically within the container.
.grid {
align-content: start; /* Default */
align-content: end;
align-content: center;
align-content: stretch;
align-content: space-around;
align-content: space-between;
align-content: space-evenly;
}CSS10. place-content (Shorthand)
.grid {
place-content: center; /* align-content justify-content */
place-content: center space-between;
}CSS11. grid-auto-columns & grid-auto-rows
Defines size of implicitly created tracks.
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
/* Items beyond 3 columns create implicit tracks */
grid-auto-columns: 150px; /* New columns are 150px */
grid-auto-rows: 100px; /* New rows are 100px */
/* Flexible implicit tracks */
grid-auto-rows: minmax(100px, auto);
}CSS12. grid-auto-flow
Controls how auto-placed items flow.
.grid {
grid-auto-flow: row; /* Default: fill rows */
grid-auto-flow: column; /* Fill columns */
grid-auto-flow: dense; /* Fill gaps (can reorder) */
grid-auto-flow: row dense; /* Row-wise with gap filling */
}CSSGrid Item Properties
1. grid-column
Controls column span and placement.
.item {
/* Start and end lines */
grid-column-start: 1;
grid-column-end: 3;
/* Shorthand: start / end */
grid-column: 1 / 3; /* Columns 1 to 3 */
/* Span notation */
grid-column: 1 / span 2; /* Start at 1, span 2 columns */
grid-column: span 2; /* Span 2 from auto position */
/* Span to end */
grid-column: 1 / -1; /* From line 1 to last line */
}CSS2. grid-row
Controls row span and placement.
.item {
/* Start and end lines */
grid-row-start: 1;
grid-row-end: 4;
/* Shorthand */
grid-row: 1 / 4;
grid-row: 2 / span 3; /* Start at row 2, span 3 rows */
grid-row: span 2; /* Span 2 rows */
grid-row: 1 / -1; /* Span all rows */
}CSS3. grid-area
Full placement shorthand OR named area.
.item {
/* row-start / col-start / row-end / col-end */
grid-area: 1 / 1 / 3 / 3;
/* Named area */
grid-area: header;
}CSSExample:
.featured-card {
grid-area: 1 / 1 / 3 / 3; /* Top-left, 2x2 */
}CSS4. justify-self
Aligns individual item horizontally.
.item {
justify-self: stretch; /* Default */
justify-self: start;
justify-self: end;
justify-self: center;
}CSS5. align-self
Aligns individual item vertically.
.item {
align-self: stretch; /* Default */
align-self: start;
align-self: end;
align-self: center;
}CSS6. place-self (Shorthand)
.item {
place-self: center; /* align-self justify-self */
place-self: start end;
}CSSPractical Grid Patterns
Pattern 1: Responsive Card Grid
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 2rem;
padding: 2rem;
}
.card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
padding: 1.5rem;
}CSSPattern 2: Holy Grail Layout
.holy-grail {
display: grid;
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
gap: 1rem;
}
.header { grid-area: header; }
.nav { grid-area: nav; }
.main { grid-area: main; }
.aside { grid-area: aside; }
.footer { grid-area: footer; }
/* Responsive */
@media (max-width: 768px) {
.holy-grail {
grid-template-areas:
"header"
"nav"
"main"
"aside"
"footer";
grid-template-columns: 1fr;
}
}CSSPattern 3: Masonry-Style Layout
.masonry {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-auto-rows: 20px; /* Small increments */
gap: 1rem;
}
.masonry-item {
/* Items span different numbers of rows */
}
.masonry-item:nth-child(1) { grid-row: span 10; }
.masonry-item:nth-child(2) { grid-row: span 15; }
.masonry-item:nth-child(3) { grid-row: span 8; }
/* etc. */CSSPattern 4: Magazine Layout
.magazine {
display: grid;
grid-template-columns: repeat(6, 1fr);
grid-auto-rows: 200px;
gap: 1rem;
}
.featured {
grid-column: span 4;
grid-row: span 2;
}
.secondary {
grid-column: span 2;
grid-row: span 2;
}
.standard {
grid-column: span 2;
}CSSPattern 5: Dashboard Layout
.dashboard {
display: grid;
grid-template-columns: repeat(12, 1fr);
grid-auto-rows: minmax(100px, auto);
gap: 1.5rem;
padding: 1.5rem;
}
.widget-large {
grid-column: span 8;
grid-row: span 2;
}
.widget-medium {
grid-column: span 4;
grid-row: span 2;
}
.widget-small {
grid-column: span 4;
}
@media (max-width: 768px) {
.widget-large,
.widget-medium,
.widget-small {
grid-column: span 12;
}
}CSSPattern 6: Image Gallery
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-auto-rows: 200px;
gap: 10px;
}
.gallery-item {
overflow: hidden;
}
.gallery-item img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s;
}
.gallery-item:hover img {
transform: scale(1.1);
}
/* Feature image spans larger area */
.gallery-item:nth-child(1) {
grid-column: span 2;
grid-row: span 2;
}CSSPattern 7: Form Layout
.form-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
}
.form-field {
display: flex;
flex-direction: column;
}
.form-field.full-width {
grid-column: span 2;
}
.form-actions {
grid-column: span 2;
display: flex;
justify-content: flex-end;
gap: 1rem;
}
@media (max-width: 600px) {
.form-grid {
grid-template-columns: 1fr;
}
.form-field.full-width {
grid-column: span 1;
}
}CSSPattern 8: Sidebar Layout
.page {
display: grid;
grid-template-columns: 300px 1fr;
gap: 2rem;
max-width: 1400px;
margin: 0 auto;
}
.sidebar {
position: sticky;
top: 2rem;
height: fit-content;
}
@media (max-width: 768px) {
.page {
grid-template-columns: 1fr;
}
.sidebar {
position: static;
}
}CSSNamed Grid Lines
.grid {
display: grid;
grid-template-columns:
[sidebar-start] 200px
[sidebar-end main-start] 1fr
[main-end aside-start] 250px
[aside-end];
}
.sidebar {
grid-column: sidebar-start / sidebar-end;
}
.main {
grid-column: main-start / main-end;
}
.aside {
grid-column: aside-start / aside-end;
}CSSGrid with Nested Grids
.outer-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 2rem;
}
.nested-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}CSSOverlapping Grid Items
.grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: repeat(4, 100px);
}
.background {
grid-column: 1 / 5;
grid-row: 1 / 5;
z-index: 1;
}
.foreground {
grid-column: 2 / 4;
grid-row: 2 / 4;
z-index: 2; /* Appears on top */
}CSSResponsive Grid Techniques
Technique 1: Auto-fit Cards
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
}CSSTechnique 2: Media Query Breakpoints
.grid {
display: grid;
gap: 1rem;
}
/* Mobile */
@media (min-width: 0) {
.grid {
grid-template-columns: 1fr;
}
}
/* Tablet */
@media (min-width: 768px) {
.grid {
grid-template-columns: repeat(2, 1fr);
}
}
/* Desktop */
@media (min-width: 1024px) {
.grid {
grid-template-columns: repeat(4, 1fr);
}
}CSSTechnique 3: Changing Grid Areas
.layout {
display: grid;
gap: 1rem;
}
/* Mobile: Stack */
@media (max-width: 767px) {
.layout {
grid-template-areas:
"header"
"main"
"sidebar"
"footer";
grid-template-columns: 1fr;
}
}
/* Desktop: Sidebar */
@media (min-width: 768px) {
.layout {
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 250px 1fr;
}
}CSSCommon Grid Issues and Solutions
Issue 1: Content Overflow
Problem: Content overflows grid cells.
Solution:
.grid-item {
min-width: 0; /* Allow shrinking below content size */
overflow: hidden; /* Or auto */
}CSSIssue 2: Unequal Heights
Problem: Want equal height items.
Solution:
.grid {
display: grid;
grid-auto-rows: 1fr; /* Equal row heights */
}CSSIssue 3: Gap at Bottom
Problem: Extra space at bottom of grid.
Solution:
.grid {
align-content: start; /* Pack items to top */
}CSSGrid Inspector Tools
Modern browsers provide Grid Inspector tools:
- Firefox: Best grid inspector with line numbers and area names
- Chrome DevTools: Grid overlay and layout inspector
- Safari: Grid inspector in Web Inspector
Performance Considerations
/* Good: Efficient */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
/* Avoid: Too many explicit rows/columns */
.grid-inefficient {
grid-template-columns: repeat(100, 1fr);
grid-template-rows: repeat(100, 1fr);
}CSSCombining Grid and Flexbox
/* Grid for page layout */
.page {
display: grid;
grid-template-areas:
"header"
"main"
"footer";
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
/* Flexbox for header components */
.header {
grid-area: header;
display: flex;
justify-content: space-between;
align-items: center;
}
/* Grid for main content */
.main {
grid-area: main;
display: grid;
grid-template-columns: 250px 1fr;
gap: 2rem;
}
/* Flexbox for cards within grid */
.card {
display: flex;
flex-direction: column;
}CSSResponsive Design
Media Queries
Media queries enable responsive design by applying styles based on device characteristics.
/* Mobile-first approach */
.container {
width: 100%;
padding: 10px;
}
/* Tablets and up */
@media (min-width: 768px) {
.container {
width: 750px;
margin: 0 auto;
}
}
/* Desktops and up */
@media (min-width: 1024px) {
.container {
width: 1000px;
}
}
/* Large screens */
@media (min-width: 1280px) {
.container {
width: 1200px;
}
}CSSCommon Breakpoints
/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) { }
/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) { }
/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) { }
/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px) { }
/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) { }CSSMedia Query Features
/* Orientation */
@media (orientation: portrait) {
/* Styles for portrait mode */
}
@media (orientation: landscape) {
/* Styles for landscape mode */
}
/* Aspect ratio */
@media (min-aspect-ratio: 16/9) {
/* Styles for widescreen */
}
/* Print styles */
@media print {
.no-print {
display: none;
}
}
/* Dark mode */
@media (prefers-color-scheme: dark) {
body {
background-color: #1a1a1a;
color: #ffffff;
}
}
/* Reduced motion */
@media (prefers-reduced-motion: reduce) {
* {
animation: none !important;
transition: none !important;
}
}CSSResponsive Units
.responsive {
/* Viewport width (1vw = 1% of viewport width) */
width: 50vw;
/* Viewport height (1vh = 1% of viewport height) */
height: 100vh;
/* Viewport minimum */
font-size: 5vmin;
/* Viewport maximum */
font-size: 5vmax;
/* Relative to parent */
width: 50%;
padding: 5%;
/* Relative to font size */
margin: 2em; /* relative to element's font-size */
padding: 1rem; /* relative to root font-size */
}CSSFluid Typography
/* Using clamp() */
h1 {
font-size: clamp(1.5rem, 5vw, 3rem);
/* min: 1.5rem, preferred: 5vw, max: 3rem */
}
/* Using calc() */
p {
font-size: calc(16px + 0.5vw);
}CSSTransitions and Animations
Transitions
Transitions provide smooth changes between property values.
.button {
background-color: blue;
color: white;
padding: 10px 20px;
/* Transition properties */
transition-property: background-color, transform;
transition-duration: 0.3s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
/* Shorthand: property duration timing-function delay */
transition: all 0.3s ease-in-out;
}
.button:hover {
background-color: darkblue;
transform: scale(1.05);
}CSSTiming Functions
.element {
/* Built-in timing functions */
transition-timing-function: linear;
transition-timing-function: ease; /* default */
transition-timing-function: ease-in;
transition-timing-function: ease-out;
transition-timing-function: ease-in-out;
/* Custom cubic-bezier */
transition-timing-function: cubic-bezier(0.42, 0, 0.58, 1);
/* Steps */
transition-timing-function: steps(4, end);
}CSSAnimations
Animations create complex sequences using keyframes.
/* Define keyframes */
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes slide {
0% {
transform: translateX(-100%);
}
50% {
transform: translateX(0);
}
100% {
transform: translateX(100%);
}
}
/* Apply animation */
.animated {
animation-name: fadeIn;
animation-duration: 1s;
animation-timing-function: ease-in;
animation-delay: 0s;
animation-iteration-count: 1; /* infinite */
animation-direction: normal; /* reverse, alternate, alternate-reverse */
animation-fill-mode: forwards; /* backwards, both */
animation-play-state: running; /* paused */
/* Shorthand: name duration timing-function delay iteration-count direction fill-mode */
animation: fadeIn 1s ease-in 0s 1 normal forwards;
}CSSAnimation Examples
Pulse Effect
@keyframes pulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.1);
}
}
.pulse {
animation: pulse 2s infinite;
}CSSRotate Spinner
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.spinner {
animation: spin 1s linear infinite;
}CSSBounce
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {
transform: translateY(0);
}
40% {
transform: translateY(-30px);
}
60% {
transform: translateY(-15px);
}
}
.bounce {
animation: bounce 2s infinite;
}CSSTransforms
Transforms modify the coordinate space of elements.
2D Transforms
.transform-examples {
/* Translate (move) */
transform: translate(50px, 100px);
transform: translateX(50px);
transform: translateY(100px);
/* Scale (resize) */
transform: scale(1.5);
transform: scale(2, 0.5); /* x, y */
transform: scaleX(2);
transform: scaleY(0.5);
/* Rotate */
transform: rotate(45deg);
transform: rotate(-30deg);
/* Skew */
transform: skew(20deg, 10deg);
transform: skewX(20deg);
transform: skewY(10deg);
/* Combine multiple transforms */
transform: translate(50px, 50px) rotate(45deg) scale(1.5);
/* Transform origin (pivot point) */
transform-origin: center center; /* default */
transform-origin: top left;
transform-origin: 50% 50%;
}CSS3D Transforms
.transform-3d {
/* 3D translate */
transform: translate3d(50px, 100px, 75px);
transform: translateZ(100px);
/* 3D rotate */
transform: rotateX(45deg);
transform: rotateY(45deg);
transform: rotateZ(45deg);
transform: rotate3d(1, 1, 1, 45deg);
/* 3D scale */
transform: scale3d(1, 1, 2);
transform: scaleZ(2);
/* Perspective */
perspective: 1000px;
/* Preserve 3D */
transform-style: preserve-3d;
}
.perspective-container {
perspective: 1000px;
}
.card {
transition: transform 0.6s;
transform-style: preserve-3d;
}
.card:hover {
transform: rotateY(180deg);
}CSSPseudo-classes and Pseudo-elements
Pseudo-classes
Pseudo-classes style elements based on their state.
/* Link states */
a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: red; }
a:active { color: yellow; }
/* Focus */
input:focus {
border-color: blue;
outline: none;
}
/* Checked (for checkboxes and radio buttons) */
input:checked {
background-color: green;
}
/* Disabled */
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* First and last child */
li:first-child {
font-weight: bold;
}
li:last-child {
border-bottom: none;
}
/* Nth child */
li:nth-child(odd) {
background-color: #f0f0f0;
}
li:nth-child(even) {
background-color: #ffffff;
}
li:nth-child(3) {
color: red;
}
li:nth-child(3n) {
/* Every 3rd element */
color: blue;
}
li:nth-child(3n+1) {
/* 1st, 4th, 7th, etc. */
color: green;
}
/* Nth of type */
p:nth-of-type(2) {
font-style: italic;
}
/* Only child */
p:only-child {
margin: 0;
}
/* Not */
li:not(:last-child) {
border-bottom: 1px solid #ccc;
}
/* Empty */
div:empty {
display: none;
}
/* Target (for anchor links) */
:target {
background-color: yellow;
}
/* Root */
:root {
--main-color: blue;
}CSSPseudo-elements
Pseudo-elements style specific parts of elements.
/* First letter */
p::first-letter {
font-size: 2em;
font-weight: bold;
color: red;
}
/* First line */
p::first-line {
font-variant: small-caps;
}
/* Before */
.quote::before {
content: '"';
font-size: 2em;
color: gray;
}
/* After */
.quote::after {
content: '"';
font-size: 2em;
color: gray;
}
/* Selection */
::selection {
background-color: yellow;
color: black;
}
/* Placeholder */
input::placeholder {
color: #999;
font-style: italic;
}
/* Marker (for list items) */
li::marker {
color: red;
font-weight: bold;
}CSSPractical Examples
Clearfix
.clearfix::after {
content: "";
display: table;
clear: both;
}CSSCustom Checkbox
input[type="checkbox"] {
display: none;
}
input[type="checkbox"] + label::before {
content: "";
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid #333;
margin-right: 10px;
}
input[type="checkbox"]:checked + label::before {
background-color: blue;
}CSSTooltip
.tooltip {
position: relative;
}
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
padding: 5px 10px;
background-color: black;
color: white;
border-radius: 4px;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s;
}
.tooltip:hover::after {
opacity: 1;
}CSSCSS Variables
CSS Variables (Custom Properties) allow you to store values for reuse.
Defining and Using Variables
:root {
/* Define global variables */
--primary-color: #3498db;
--secondary-color: #2ecc71;
--font-size: 16px;
--spacing: 20px;
--border-radius: 8px;
}
.button {
/* Use variables */
background-color: var(--primary-color);
font-size: var(--font-size);
padding: var(--spacing);
border-radius: var(--border-radius);
}
.card {
/* Use with fallback */
color: var(--text-color, #333);
}CSSScoped Variables
.theme-dark {
--bg-color: #1a1a1a;
--text-color: #ffffff;
}
.theme-light {
--bg-color: #ffffff;
--text-color: #333333;
}
.container {
background-color: var(--bg-color);
color: var(--text-color);
}CSSDynamic Variables with JavaScript
<button id="changeColor">Change Color</button>HTML:root {
--dynamic-color: blue;
}
.box {
background-color: var(--dynamic-color);
}CSSdocument.getElementById('changeColor').addEventListener('click', () => {
document.documentElement.style.setProperty('--dynamic-color', 'red');
});JavaScriptCalc() with Variables
:root {
--header-height: 80px;
--spacing: 20px;
}
.content {
height: calc(100vh - var(--header-height));
padding: calc(var(--spacing) * 2);
}CSSBest Practices
1. Organization and Structure
/* Group related properties */
.element {
/* Display & Box Model */
display: flex;
width: 100%;
padding: 20px;
margin: 10px;
/* Positioning */
position: relative;
top: 0;
left: 0;
/* Typography */
font-family: Arial, sans-serif;
font-size: 16px;
color: #333;
/* Visual */
background-color: #f0f0f0;
border: 1px solid #ccc;
/* Misc */
cursor: pointer;
transition: all 0.3s ease;
}CSS2. Naming Conventions
BEM (Block Element Modifier)
/* Block */
.card { }
/* Element */
.card__title { }
.card__content { }
.card__button { }
/* Modifier */
.card--featured { }
.card__button--primary { }CSS3. Reset or Normalize CSS
/* Simple reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Or use a CSS reset library like normalize.css */CSS4. Mobile-First Approach
/* Start with mobile styles */
.container {
width: 100%;
padding: 10px;
}
/* Add complexity for larger screens */
@media (min-width: 768px) {
.container {
width: 750px;
padding: 20px;
}
}CSS5. Avoid !important
/* Bad */
.text {
color: red !important;
}
/* Good: Use specificity */
.container .text {
color: red;
}CSS6. Use Shorthand Properties
/* Instead of */
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;
/* Use */
margin: 10px 20px;
/* Instead of */
background-color: #fff;
background-image: url('img.jpg');
background-repeat: no-repeat;
background-position: center;
/* Use */
background: #fff url('img.jpg') no-repeat center;CSS7. Performance Optimization
/* Use efficient selectors */
/* Good */
.button { }
/* Avoid deep nesting */
/* Bad */
.header .nav .menu .item a { }
/* Use will-change for animations */
.animated {
will-change: transform, opacity;
}
/* Minimize repaints and reflows */
.element {
transform: translateX(10px); /* Better */
/* left: 10px; /* Worse - triggers layout */
}CSS8. Accessibility
/* Ensure sufficient color contrast */
.text {
color: #333;
background-color: #fff;
}
/* Visible focus indicators */
a:focus, button:focus {
outline: 2px solid blue;
outline-offset: 2px;
}
/* Hide visually but keep for screen readers */
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
/* Respect user preferences */
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}CSS9. Comments
/* ==========================================================================
Section Title
========================================================================== */
/**
* Short description
* Long description with multiple lines
*/
.component {
/* Single line comment */
property: value;
}CSS10. Version Control and Documentation
- Use a CSS preprocessor (Sass, Less) for large projects
- Maintain a style guide
- Document custom properties and mixins
- Use linting tools (Stylelint)
Additional Resources
Learn More
- MDN Web Docs – CSS
- CSS-Tricks
- W3C CSS Specifications
- Can I Use – Browser support tables
Tools
- CSS Grid Generator
- Flexbox Froggy – Learning game
- CSS Gradient Generator
- Animista – CSS animations
Modern CSS Features
- Container Queries
- CSS Subgrid
- Cascade Layers (@layer)
- Color Functions (color-mix(), oklch())
- :has() selector
- Scroll-driven Animations
Practice Exercises
Exercise 1: Create a Card Component
Create a responsive card with an image, title, description, and button.
Exercise 2: Build a Navigation Menu
Design a horizontal navigation that becomes a hamburger menu on mobile.
Exercise 3: Implement a Grid Gallery
Create a responsive image gallery using CSS Grid.
Exercise 4: Design a Hero Section
Build a full-screen hero section with centered content and a background image.
Exercise 5: Animate a Loading Spinner
Create a rotating loading spinner using CSS animations.
Conclusion
CSS is a powerful and essential technology for web development. This tutorial covered:
- Fundamentals: Syntax, selectors, and the cascade
- Layout: Flexbox, Grid, and positioning
- Responsive Design: Media queries and fluid layouts
- Visual Effects: Transitions, animations, and transforms
- Modern Techniques: CSS variables and advanced selectors
- Best Practices: Performance, accessibility, and maintainability
Next Steps:
- Practice building real projects
- Explore CSS frameworks (Bootstrap, Tailwind CSS)
- Learn CSS preprocessors (Sass, Less)
- Study advanced animations and interactions
- Keep up with new CSS features and specifications
Remember: The best way to learn CSS is by doing. Experiment, break things, and build projects!
CSS Cheatsheet – Quick Reference Guide
Selectors
/* Universal Selector */
* { }
/* Element Selector */
h1 { }
p { }
/* Class Selector */
.class-name { }
/* ID Selector */
#id-name { }
/* Attribute Selectors */
[attr] { } /* Has attribute */
[attr="value"] { } /* Exact match */
[attr~="value"] { } /* Word match */
[attr^="value"] { } /* Starts with */
[attr$="value"] { } /* Ends with */
[attr*="value"] { } /* Contains */
[attr|="value"] { } /* Starts with or followed by hyphen */
/* Combinators */
div p { } /* Descendant */
div > p { } /* Direct child */
div + p { } /* Adjacent sibling */
div ~ p { } /* General sibling */
/* Grouping */
h1, h2, h3 { } /* Multiple selectors */
/* Pseudo-classes */
:hover { } /* Mouse over */
:active { } /* Being clicked */
:focus { } /* Has focus */
:visited { } /* Visited link */
:link { } /* Unvisited link */
:checked { } /* Checked input */
:disabled { } /* Disabled element */
:enabled { } /* Enabled element */
:first-child { } /* First child */
:last-child { } /* Last child */
:nth-child(n) { } /* Nth child */
:nth-child(odd) { } /* Odd children */
:nth-child(even) { } /* Even children */
:nth-child(3n) { } /* Every 3rd */
:nth-last-child(n) { } /* Nth from end */
:first-of-type { } /* First of type */
:last-of-type { } /* Last of type */
:nth-of-type(n) { } /* Nth of type */
:only-child { } /* Only child */
:only-of-type { } /* Only of type */
:not(selector) { } /* Not matching */
:empty { } /* No children */
:target { } /* URL target */
:root { } /* Root element */
/* Pseudo-elements */
::before { } /* Before content */
::after { } /* After content */
::first-letter { } /* First letter */
::first-line { } /* First line */
::selection { } /* Selected text */
::placeholder { } /* Input placeholder */
::marker { } /* List marker */CSSBox Model
/* Width & Height */
width: 100px;
width: 50%;
width: auto;
width: max-content;
width: min-content;
width: fit-content;
min-width: 200px;
max-width: 1200px;
height: 100px;
height: 100vh;
min-height: 500px;
max-height: 80vh;
/* Box Sizing */
box-sizing: content-box; /* Default */
box-sizing: border-box; /* Include padding & border */
/* Padding */
padding: 10px; /* All sides */
padding: 10px 20px; /* Top/bottom left/right */
padding: 10px 20px 30px 40px; /* Top right bottom left */
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
/* Margin */
margin: 10px;
margin: 10px 20px;
margin: 10px 20px 30px 40px;
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 40px;
margin: 0 auto; /* Center horizontally */
/* Border */
border: 1px solid black;
border-width: 2px;
border-style: solid; /* dashed, dotted, double, groove, ridge, inset, outset */
border-color: #333;
border-top: 1px solid red;
border-right: 2px dashed blue;
border-bottom: 3px dotted green;
border-left: 4px double yellow;
/* Border Radius */
border-radius: 5px; /* All corners */
border-radius: 10px 20px; /* Top-left/bottom-right top-right/bottom-left */
border-radius: 10px 20px 30px 40px; /* TL TR BR BL */
border-top-left-radius: 10px;
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
border-radius: 50%; /* Circle */
/* Outline */
outline: 2px solid blue;
outline-offset: 2px;
outline: none; /* Remove default outline */CSSDisplay & Visibility
display: block;
display: inline;
display: inline-block;
display: flex;
display: inline-flex;
display: grid;
display: inline-grid;
display: none;
display: contents; /* Children appear in parent */
visibility: visible;
visibility: hidden; /* Hidden but keeps space */
visibility: collapse; /* For table elements */
opacity: 1; /* Fully opaque (0-1) */
opacity: 0.5; /* Semi-transparent */
opacity: 0; /* Fully transparent */CSSPosition
position: static; /* Default */
position: relative; /* Relative to normal position */
position: absolute; /* Relative to positioned parent */
position: fixed; /* Relative to viewport */
position: sticky; /* Switches between relative/fixed */
top: 10px;
right: 20px;
bottom: 30px;
left: 40px;
inset: 10px; /* All sides */
inset: 10px 20px; /* Top/bottom left/right */
z-index: 1; /* Stacking order */
z-index: -1; /* Behind */
z-index: 999; /* Front */CSSFlexbox
/* Container Properties */
display: flex;
flex-direction: row; /* row, row-reverse, column, column-reverse */
flex-wrap: nowrap; /* wrap, wrap-reverse */
flex-flow: row wrap; /* direction + wrap */
justify-content: flex-start; /* flex-end, center, space-between, space-around, space-evenly */
align-items: stretch; /* flex-start, flex-end, center, baseline */
align-content: flex-start; /* flex-end, center, space-between, space-around, stretch */
gap: 20px;
row-gap: 20px;
column-gap: 10px;
/* Item Properties */
flex-grow: 0; /* Growth factor */
flex-shrink: 1; /* Shrink factor */
flex-basis: auto; /* Base size */
flex: 1; /* grow shrink basis */
flex: 0 0 200px; /* Fixed size */
align-self: auto; /* Override align-items */
order: 0; /* Visual order */CSSGrid
/* Container Properties */
display: grid;
grid-template-columns: 200px 1fr 200px;
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
grid-template-rows: 100px auto 100px;
grid-template-areas:
"header header header"
"sidebar main aside"
"footer footer footer";
gap: 20px;
row-gap: 20px;
column-gap: 10px;
justify-items: start; /* end, center, stretch */
align-items: start; /* end, center, stretch */
justify-content: start; /* end, center, stretch, space-between, space-around, space-evenly */
align-content: start; /* end, center, stretch, space-between, space-around, space-evenly */
place-items: center; /* align-items + justify-items */
place-content: center; /* align-content + justify-content */
grid-auto-columns: 100px;
grid-auto-rows: 100px;
grid-auto-flow: row; /* column, dense */
/* Item Properties */
grid-column: 1 / 3; /* Start / end */
grid-column: span 2; /* Span 2 columns */
grid-row: 1 / 3;
grid-row: span 2;
grid-area: header; /* Named area */
grid-area: 1 / 1 / 3 / 3; /* row-start / col-start / row-end / col-end */
justify-self: start; /* end, center, stretch */
align-self: start; /* end, center, stretch */
place-self: center; /* align-self + justify-self */CSSTypography
/* Font Family */
font-family: Arial, sans-serif;
font-family: 'Georgia', serif;
font-family: 'Courier New', monospace;
/* Font Size */
font-size: 16px;
font-size: 1em;
font-size: 1.5rem;
font-size: 100%;
font-size: larger;
font-size: smaller;
/* Font Weight */
font-weight: normal; /* 400 */
font-weight: bold; /* 700 */
font-weight: 300; /* Light */
font-weight: 600; /* Semi-bold */
font-weight: 900; /* Black */
/* Font Style */
font-style: normal;
font-style: italic;
font-style: oblique;
/* Font Variant */
font-variant: normal;
font-variant: small-caps;
/* Line Height */
line-height: 1.6;
line-height: 24px;
line-height: 1.5em;
/* Text Alignment */
text-align: left;
text-align: center;
text-align: right;
text-align: justify;
/* Text Decoration */
text-decoration: none;
text-decoration: underline;
text-decoration: overline;
text-decoration: line-through;
text-decoration: underline dotted red;
/* Text Transform */
text-transform: none;
text-transform: uppercase;
text-transform: lowercase;
text-transform: capitalize;
/* Text Indent */
text-indent: 20px;
text-indent: 5%;
/* Letter Spacing */
letter-spacing: normal;
letter-spacing: 2px;
letter-spacing: 0.1em;
/* Word Spacing */
word-spacing: normal;
word-spacing: 5px;
/* White Space */
white-space: normal;
white-space: nowrap; /* No wrapping */
white-space: pre; /* Preserve whitespace */
white-space: pre-wrap; /* Preserve + wrap */
white-space: pre-line; /* Collapse whitespace, preserve newlines */
/* Word Break */
word-break: normal;
word-break: break-all; /* Break anywhere */
word-break: keep-all; /* Don't break words */
/* Word Wrap */
word-wrap: normal;
word-wrap: break-word; /* Break long words */
overflow-wrap: break-word; /* Modern equivalent */
/* Text Overflow */
text-overflow: clip;
text-overflow: ellipsis; /* Show ... */
/* Text Shadow */
text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
text-shadow: 0 0 10px red, 0 0 20px blue; /* Multiple shadows */
/* Vertical Align */
vertical-align: baseline;
vertical-align: top;
vertical-align: middle;
vertical-align: bottom;
vertical-align: text-top;
vertical-align: text-bottom;CSSColors
/* Named Colors */
color: red;
color: transparent;
/* Hex */
color: #ff5733;
color: #f57; /* Shorthand */
/* RGB */
color: rgb(255, 87, 51);
/* RGBA */
color: rgba(255, 87, 51, 0.5);
/* HSL */
color: hsl(9, 100%, 60%);
/* HSLA */
color: hsla(9, 100%, 60%, 0.8);
/* Current Color */
color: currentColor;
/* CSS Variables */
color: var(--primary-color);CSSBackgrounds
/* Background Color */
background-color: #f0f0f0;
background-color: transparent;
/* Background Image */
background-image: url('image.jpg');
background-image: linear-gradient(to right, red, blue);
background-image: radial-gradient(circle, red, blue);
/* Background Repeat */
background-repeat: repeat;
background-repeat: no-repeat;
background-repeat: repeat-x;
background-repeat: repeat-y;
background-repeat: space;
background-repeat: round;
/* Background Position */
background-position: top left;
background-position: center center;
background-position: 50% 50%;
background-position: 10px 20px;
/* Background Size */
background-size: auto;
background-size: cover; /* Cover entire area */
background-size: contain; /* Fit within area */
background-size: 100px 200px;
background-size: 50%;
/* Background Attachment */
background-attachment: scroll;
background-attachment: fixed; /* Fixed during scroll */
background-attachment: local;
/* Background Origin */
background-origin: padding-box;
background-origin: border-box;
background-origin: content-box;
/* Background Clip */
background-clip: border-box;
background-clip: padding-box;
background-clip: content-box;
background-clip: text; /* Clip to text */
/* Shorthand */
background: #fff url('img.jpg') no-repeat center/cover;
background: linear-gradient(to bottom, red, blue);
/* Multiple Backgrounds */
background:
url('front.png') no-repeat center,
url('back.png') no-repeat center;CSSGradients
/* Linear Gradient */
background: linear-gradient(red, blue);
background: linear-gradient(to right, red, blue);
background: linear-gradient(45deg, red, blue);
background: linear-gradient(to bottom right, red, blue);
background: linear-gradient(red 0%, yellow 50%, green 100%);
/* Radial Gradient */
background: radial-gradient(red, blue);
background: radial-gradient(circle, red, blue);
background: radial-gradient(ellipse, red, blue);
background: radial-gradient(circle at top left, red, blue);
/* Conic Gradient */
background: conic-gradient(red, yellow, green, blue);
background: conic-gradient(from 45deg, red, blue);
/* Repeating Gradients */
background: repeating-linear-gradient(red, blue 20px);
background: repeating-radial-gradient(circle, red, blue 20px);CSSBorders & Outlines
/* Border */
border: 1px solid black;
border-top: 2px dashed red;
border-width: 1px 2px 3px 4px;
border-style: solid; /* dashed, dotted, double, groove, ridge, inset, outset, none, hidden */
border-color: red blue green yellow;
/* Border Radius */
border-radius: 10px;
border-radius: 10px 20px 30px 40px;
border-top-left-radius: 10px;
border-radius: 50%; /* Circle */
/* Border Image */
border-image: url('border.png') 30 round;
border-image-source: url('border.png');
border-image-slice: 30;
border-image-width: 10px;
border-image-repeat: stretch; /* repeat, round, space */
/* Outline */
outline: 2px solid blue;
outline-width: 2px;
outline-style: solid;
outline-color: blue;
outline-offset: 5px;CSSShadows
/* Box Shadow */
box-shadow: 2px 2px 4px rgba(0,0,0,0.3);
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
box-shadow: inset 0 0 10px rgba(0,0,0,0.5); /* Inner shadow */
box-shadow:
0 2px 4px rgba(0,0,0,0.2),
0 4px 8px rgba(0,0,0,0.1); /* Multiple shadows */
/* Text Shadow */
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
text-shadow: 0 0 10px red, 0 0 20px blue;
/* Drop Shadow (Filter) */
filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.3));CSSTransforms
/* 2D Transforms */
transform: translate(50px, 100px);
transform: translateX(50px);
transform: translateY(100px);
transform: scale(1.5);
transform: scale(2, 0.5);
transform: scaleX(2);
transform: scaleY(0.5);
transform: rotate(45deg);
transform: skew(20deg, 10deg);
transform: skewX(20deg);
transform: skewY(10deg);
/* 3D Transforms */
transform: translate3d(50px, 100px, 75px);
transform: translateZ(100px);
transform: scale3d(1, 1, 2);
transform: scaleZ(2);
transform: rotateX(45deg);
transform: rotateY(45deg);
transform: rotateZ(45deg);
transform: rotate3d(1, 1, 1, 45deg);
/* Multiple Transforms */
transform: translate(50px, 100px) rotate(45deg) scale(1.5);
/* Transform Origin */
transform-origin: center center;
transform-origin: top left;
transform-origin: 50% 50%;
transform-origin: 0 0;
/* Transform Style */
transform-style: flat;
transform-style: preserve-3d;
/* Perspective */
perspective: 1000px;
perspective-origin: center center;
/* Backface Visibility */
backface-visibility: visible;
backface-visibility: hidden;CSSTransitions
/* Individual Properties */
transition-property: all;
transition-property: background-color, transform;
transition-duration: 0.3s;
transition-timing-function: ease;
transition-delay: 0s;
/* Shorthand */
transition: all 0.3s ease;
transition: background-color 0.3s ease, transform 0.5s ease-in-out;
/* Timing Functions */
transition-timing-function: linear;
transition-timing-function: ease;
transition-timing-function: ease-in;
transition-timing-function: ease-out;
transition-timing-function: ease-in-out;
transition-timing-function: cubic-bezier(0.42, 0, 0.58, 1);
transition-timing-function: steps(4, end);CSSAnimations
/* Define Keyframes */
@keyframes slideIn {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-20px); }
}
/* Animation Properties */
animation-name: slideIn;
animation-duration: 1s;
animation-timing-function: ease;
animation-delay: 0s;
animation-iteration-count: 1;
animation-iteration-count: infinite;
animation-direction: normal; /* reverse, alternate, alternate-reverse */
animation-fill-mode: none; /* forwards, backwards, both */
animation-play-state: running; /* paused */
/* Shorthand */
animation: slideIn 1s ease 0s 1 normal forwards;
animation: bounce 2s infinite;
/* Multiple Animations */
animation: slideIn 1s, fadeIn 0.5s;CSSFilters
filter: blur(5px);
filter: brightness(1.2);
filter: contrast(150%);
filter: grayscale(100%);
filter: hue-rotate(90deg);
filter: invert(100%);
filter: opacity(50%);
filter: saturate(200%);
filter: sepia(100%);
filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.3));
/* Multiple Filters */
filter: blur(2px) brightness(1.2) contrast(1.5);
/* Backdrop Filter */
backdrop-filter: blur(10px);CSSLayout & Overflow
/* Overflow */
overflow: visible;
overflow: hidden;
overflow: scroll;
overflow: auto;
overflow-x: hidden;
overflow-y: scroll;
/* Float */
float: none;
float: left;
float: right;
/* Clear */
clear: none;
clear: left;
clear: right;
clear: both;
/* Columns */
columns: 3;
columns: 300px 3;
column-count: 3;
column-width: 200px;
column-gap: 30px;
column-rule: 1px solid #ccc;
column-span: all;
/* Object Fit */
object-fit: fill;
object-fit: contain;
object-fit: cover;
object-fit: none;
object-fit: scale-down;
object-position: center;
object-position: top left;CSSLists
/* List Style */
list-style: none;
list-style: disc inside;
list-style-type: disc; /* circle, square, decimal, lower-alpha, upper-roman */
list-style-position: inside; /* outside */
list-style-image: url('marker.png');
/* Counter */
counter-reset: section;
counter-increment: section;
content: counter(section);
content: counters(section, ".");CSSTables
/* Table Layout */
table-layout: auto;
table-layout: fixed;
/* Border Collapse */
border-collapse: separate;
border-collapse: collapse;
/* Border Spacing */
border-spacing: 10px;
border-spacing: 10px 20px;
/* Caption Side */
caption-side: top;
caption-side: bottom;
/* Empty Cells */
empty-cells: show;
empty-cells: hide;CSSMedia Queries
/* Mobile First */
@media (min-width: 576px) { }
@media (min-width: 768px) { }
@media (min-width: 992px) { }
@media (min-width: 1200px) { }
@media (min-width: 1400px) { }
/* Desktop First */
@media (max-width: 1399px) { }
@media (max-width: 1199px) { }
@media (max-width: 991px) { }
@media (max-width: 767px) { }
@media (max-width: 575px) { }
/* Orientation */
@media (orientation: portrait) { }
@media (orientation: landscape) { }
/* Aspect Ratio */
@media (min-aspect-ratio: 16/9) { }
@media (max-aspect-ratio: 4/3) { }
/* Resolution */
@media (min-resolution: 2dppx) { }
@media (min-resolution: 192dpi) { }
/* Color Scheme */
@media (prefers-color-scheme: dark) { }
@media (prefers-color-scheme: light) { }
/* Reduced Motion */
@media (prefers-reduced-motion: reduce) { }
/* Hover Capability */
@media (hover: hover) { }
@media (hover: none) { }
/* Print */
@media print { }
/* Combining Queries */
@media (min-width: 768px) and (max-width: 1024px) { }
@media (min-width: 768px) and (orientation: landscape) { }
@media screen and (min-width: 768px), print { }CSSCSS Variables
/* Define Variables */
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--font-size: 16px;
--spacing: 20px;
}
/* Use Variables */
.element {
color: var(--primary-color);
font-size: var(--font-size);
padding: var(--spacing);
}
/* Fallback Values */
.element {
color: var(--undefined-color, #333);
}
/* Scoped Variables */
.theme-dark {
--bg-color: #1a1a1a;
--text-color: #ffffff;
}
/* Calc with Variables */
.element {
width: calc(100% - var(--spacing) * 2);
}CSSFunctions
/* Calc */
width: calc(100% - 50px);
height: calc(100vh - 80px);
font-size: calc(16px + 1vw);
/* Min / Max */
width: min(100%, 1200px);
width: max(300px, 50%);
height: max(500px, 100vh);
/* Clamp */
font-size: clamp(1rem, 2vw, 2rem); /* min, preferred, max */
width: clamp(300px, 50%, 800px);
/* Attr */
content: attr(data-value);
content: attr(href);
/* URL */
background-image: url('image.jpg');
background-image: url(../images/photo.png);
/* Color Functions */
color: rgb(255, 0, 0);
color: rgba(255, 0, 0, 0.5);
color: hsl(120, 100%, 50%);
color: hsla(120, 100%, 50%, 0.5);CSSUnits
/* Absolute Units */
px /* Pixels */
pt /* Points (1pt = 1/72 inch) */
cm /* Centimeters */
mm /* Millimeters */
in /* Inches */
/* Relative Units */
em /* Relative to font-size */
rem /* Relative to root font-size */
% /* Percentage */
vw /* Viewport width (1vw = 1%) */
vh /* Viewport height (1vh = 1%) */
vmin /* Viewport minimum */
vmax /* Viewport maximum */
ch /* Width of "0" character */
ex /* Height of "x" character */
/* Flex Units */
fr /* Fraction (Grid only) */CSSCursor
cursor: auto;
cursor: default;
cursor: pointer;
cursor: wait;
cursor: text;
cursor: move;
cursor: help;
cursor: not-allowed;
cursor: grab;
cursor: grabbing;
cursor: zoom-in;
cursor: zoom-out;
cursor: crosshair;
cursor: none;
cursor: url('cursor.png'), auto;CSSUser Interaction
/* Pointer Events */
pointer-events: auto;
pointer-events: none;
/* User Select */
user-select: auto;
user-select: none;
user-select: text;
user-select: all;
/* Touch Action */
touch-action: auto;
touch-action: none;
touch-action: pan-x;
touch-action: pan-y;
touch-action: manipulation;
/* Resize */
resize: none;
resize: both;
resize: horizontal;
resize: vertical;
/* Scroll Behavior */
scroll-behavior: auto;
scroll-behavior: smooth;
/* Scroll Snap */
scroll-snap-type: x mandatory;
scroll-snap-type: y proximity;
scroll-snap-align: start;
scroll-snap-align: center;
scroll-snap-align: end;CSSContent & Quotes
/* Content */
content: "text";
content: attr(data-label);
content: counter(section);
content: open-quote;
content: close-quote;
content: url('icon.png');
content: "";
/* Quotes */
quotes: "«" "»" "‹" "›";
quotes: """ """ "'" "'";CSSMiscellaneous
/* Appearance */
appearance: none; /* Remove default styling */
appearance: auto;
/* Mix Blend Mode */
mix-blend-mode: normal;
mix-blend-mode: multiply;
mix-blend-mode: screen;
mix-blend-mode: overlay;
mix-blend-mode: darken;
mix-blend-mode: lighten;
mix-blend-mode: color-dodge;
mix-blend-mode: color-burn;
/* Clip Path */
clip-path: circle(50%);
clip-path: ellipse(25% 40%);
clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
clip-path: inset(10px 20px 30px 40px);
/* Mask */
mask-image: url('mask.png');
mask-size: cover;
mask-repeat: no-repeat;
mask-position: center;
/* Writing Mode */
writing-mode: horizontal-tb;
writing-mode: vertical-rl;
writing-mode: vertical-lr;
/* Direction */
direction: ltr;
direction: rtl;
/* Unicode Bidi */
unicode-bidi: normal;
unicode-bidi: embed;
unicode-bidi: bidi-override;
/* Break */
break-before: auto; /* avoid, always, left, right, page, column */
break-after: auto;
break-inside: auto; /* avoid */
/* Orphans & Widows */
orphans: 2; /* Min lines at bottom of page */
widows: 2; /* Min lines at top of page */
/* Page Break (Legacy) */
page-break-before: auto; /* avoid, always, left, right */
page-break-after: auto;
page-break-inside: auto; /* avoid */
/* Will Change */
will-change: auto;
will-change: transform;
will-change: opacity;
will-change: scroll-position;
/* Isolation */
isolation: auto;
isolation: isolate;
/* All */
all: initial; /* Reset all properties */
all: inherit;
all: unset;CSSCommon Patterns
/* Center Element */
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* Flexbox Center */
.flex-center {
display: flex;
justify-content: center;
align-items: center;
}
/* Grid Center */
.grid-center {
display: grid;
place-items: center;
}
/* Clearfix */
.clearfix::after {
content: "";
display: table;
clear: both;
}
/* Truncate Text */
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Hide Element */
.hide {
display: none;
}
.invisible {
visibility: hidden;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
/* Aspect Ratio */
.aspect-ratio {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
}
.aspect-ratio > * {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
/* Responsive Image */
img {
max-width: 100%;
height: auto;
}
/* Reset List */
ul, ol {
list-style: none;
padding: 0;
margin: 0;
}
/* Reset Button */
button {
border: none;
background: none;
padding: 0;
cursor: pointer;
}
/* Full Height */
.full-height {
min-height: 100vh;
}
/* Container */
.container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
padding: 0 15px;
}
/* Sticky Footer */
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1;
}
/* Card */
.card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
padding: 1.5rem;
}
/* Overlay */
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
z-index: 999;
}
/* Focus Styles */
:focus-visible {
outline: 2px solid blue;
outline-offset: 2px;
}
/* Smooth Scroll */
html {
scroll-behavior: smooth;
}
/* Box Sizing */
*, *::before, *::after {
box-sizing: border-box;
}
/* Reset */
* {
margin: 0;
padding: 0;
}CSSPrint Styles
@media print {
/* Hide non-essential elements */
nav, aside, .no-print {
display: none;
}
/* Page breaks */
h1, h2, h3 {
page-break-after: avoid;
}
img {
page-break-inside: avoid;
}
/* Show URLs for links */
a[href]::after {
content: " (" attr(href) ")";
}
/* Black text on white */
body {
color: black;
background: white;
}
/* Remove shadows */
* {
box-shadow: none !important;
text-shadow: none !important;
}
}CSSPerformance Tips
/* Use transform instead of position */
/* Good */
.animated {
transform: translateX(10px);
}
/* Avoid */
.animated {
left: 10px;
}
/* Use will-change for animations */
.will-animate {
will-change: transform;
}
/* Remove after animation */
.animated {
will-change: auto;
}
/* Contain layout */
.component {
contain: layout;
contain: style;
contain: paint;
contain: content; /* layout + style + paint */
}
/* Content visibility */
.below-fold {
content-visibility: auto;
}CSSBrowser Prefixes
/* Vendor Prefixes (use autoprefixer instead) */
-webkit-property: value; /* Chrome, Safari, newer Opera */
-moz-property: value; /* Firefox */
-ms-property: value; /* IE, Edge */
-o-property: value; /* Old Opera */
property: value; /* Standard */
/* Common prefixed properties */
-webkit-appearance: none;
-webkit-transform: rotate(45deg);
-webkit-transition: all 0.3s;
-webkit-animation: slide 1s;
-webkit-box-shadow: 0 2px 4px rgba(0,0,0,0.3);CSSSpecificity
/* Specificity Hierarchy (from low to high) */
/* 0-0-0-1 */ element { }
/* 0-0-1-0 */ .class { }
/* 0-1-0-0 */ #id { }
/* 1-0-0-0 */ style="" (inline)
/* Examples */
/* 0-0-0-1 */ p { }
/* 0-0-1-0 */ .text { }
/* 0-0-1-1 */ p.text { }
/* 0-0-2-0 */ .container .text { }
/* 0-1-0-0 */ #main { }
/* 0-1-1-1 */ #main .text p { }
/* !important overrides all (use sparingly) */
color: red !important;CSSQuick Tips:
- Use
box-sizing: border-box;globally - Mobile-first media queries are easier to manage
- Use CSS variables for theming
- Prefer flexbox/grid over floats
- Use
remfor font sizes - Test in multiple browsers
- Use developer tools for debugging
- Validate CSS with linters
Resources:
CSS Tricks: https://css-tricks.com/
MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/CSS
Can I Use: https://caniuse.com/
Discover more from Altgr Blog
Subscribe to get the latest posts sent to your email.
