Tags: webdev css reference cheatsheet styling Created: 2025-07-22 Type: Learning Resource Prerequisites: HTML Crash Course & Cheat Sheet

Overview

CSS (Cascading Style Sheets) is the language used to describe the presentation and styling of HTML documents. It controls layout, colors, fonts, spacing, and visual effects.

CSS Syntax

selector {
    property: value;
    another-property: another-value;
}

Example:

h1 {
    color: blue;
    font-size: 24px;
    margin-bottom: 10px;
}

Ways to Add CSS

1. Inline CSS

<p style="color: red; font-size: 16px;">Styled paragraph</p>

2. Internal CSS

<head>
    <style>
        p {
            color: red;
            font-size: 16px;
        }
    </style>
</head>
<head>
    <link rel="stylesheet" href="styles.css">
</head>
/* styles.css */
p {
    color: red;
    font-size: 16px;
}

CSS Selectors

Basic Selectors

SelectorSyntaxExampleTargets
Elementelementp { }All <p> elements
Class.class.intro { }Elements with class="intro"
ID#id#header { }Element with id="header"
Universal** { }All elements

Attribute Selectors

/* Elements with specific attribute */
input[type] { }
 
/* Elements with specific attribute value */
input[type="text"] { }
 
/* Elements with attribute containing value */
a[href*="example"] { }
 
/* Elements with attribute starting with value */
a[href^="https"] { }
 
/* Elements with attribute ending with value */
img[src$=".jpg"] { }

Combinators

/* Descendant selector (any level) */
div p { }
 
/* Child selector (direct children only) */
div > p { }
 
/* Adjacent sibling selector */
h1 + p { }
 
/* General sibling selector */
h1 ~ p { }

Pseudo-classes

/* Link states */
a:link { }          /* Unvisited links */
a:visited { }       /* Visited links */
a:hover { }         /* Mouse over */
a:active { }        /* Being clicked */
 
/* Form states */
input:focus { }     /* When input is focused */
input:valid { }     /* Valid form input */
input:invalid { }   /* Invalid form input */
input:disabled { }  /* Disabled input */
 
/* Structural pseudo-classes */
p:first-child { }   /* First child element */
p:last-child { }    /* Last child element */
p:nth-child(odd) { } /* Odd-numbered children */
p:nth-child(2n) { }  /* Even-numbered children */
p:nth-child(3) { }   /* Third child */

Pseudo-elements

/* Insert content before/after elements */
p::before {
    content: "→ ";
}
 
p::after {
    content: " ←";
}
 
/* Style first letter/line */
p::first-letter {
    font-size: 2em;
    font-weight: bold;
}
 
p::first-line {
    font-weight: bold;
}
 
/* Style selected text */
::selection {
    background-color: yellow;
}

The Box Model

Every HTML element is a rectangular box with four areas:

┌─────────────────────────────────┐
│           Margin                │
│  ┌───────────────────────────┐  │
│  │        Border             │  │
│  │  ┌─────────────────────┐  │  │
│  │  │      Padding        │  │  │
│  │  │  ┌───────────────┐  │  │  │
│  │  │  │    Content    │  │  │  │
│  │  │  └───────────────┘  │  │  │
│  │  └─────────────────────┘  │  │
│  └───────────────────────────┘  │
└─────────────────────────────────┘
.box {
    width: 200px;           /* Content width */
    height: 100px;          /* Content height */
    padding: 20px;          /* Space inside border */
    border: 2px solid black; /* Border around padding */
    margin: 15px;           /* Space outside border */
}

Box-sizing Property

/* Default: padding and border add to width/height */
.default-box {
    box-sizing: content-box;
}
 
/* Recommended: padding and border included in width/height */
.better-box {
    box-sizing: border-box;
}
 
/* Apply to all elements */
* {
    box-sizing: border-box;
}

Typography

Font Properties

.text-styling {
    /* Font family (with fallbacks) */
    font-family: "Helvetica Neue", Arial, sans-serif;
    
    /* Font size */
    font-size: 16px;        /* Pixels */
    font-size: 1.2em;       /* Relative to parent */
    font-size: 1.2rem;      /* Relative to root */
    
    /* Font weight */
    font-weight: normal;    /* 400 */
    font-weight: bold;      /* 700 */
    font-weight: 300;       /* Light */
    font-weight: 900;       /* Heavy */
    
    /* Font style */
    font-style: normal;
    font-style: italic;
    font-style: oblique;
    
    /* Text properties */
    color: #333333;
    text-align: left;       /* left, center, right, justify */
    text-decoration: none;  /* none, underline, line-through */
    text-transform: uppercase; /* uppercase, lowercase, capitalize */
    
    /* Line height (spacing between lines) */
    line-height: 1.5;       /* 1.5 times font size */
    line-height: 24px;      /* Fixed pixels */
    
    /* Letter and word spacing */
    letter-spacing: 1px;
    word-spacing: 2px;
}

Text Layout

.text-layout {
    /* Text alignment */
    text-align: left;
    text-align: center;
    text-align: right;
    text-align: justify;
    
    /* Vertical alignment (inline elements) */
    vertical-align: top;
    vertical-align: middle;
    vertical-align: bottom;
    
    /* Text overflow */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    
    /* Word wrapping */
    word-wrap: break-word;
    word-break: break-all;
}

Colors and Backgrounds

Color Values

.color-examples {
    /* Named colors */
    color: red;
    color: blue;
    color: transparent;
    
    /* Hexadecimal */
    color: #ff0000;        /* Red */
    color: #00ff00;        /* Green */
    color: #0000ff;        /* Blue */
    color: #fff;           /* White (shorthand) */
    color: #000;           /* Black (shorthand) */
    
    /* RGB */
    color: rgb(255, 0, 0);     /* Red */
    color: rgba(255, 0, 0, 0.5); /* Semi-transparent red */
    
    /* HSL (Hue, Saturation, Lightness) */
    color: hsl(0, 100%, 50%);    /* Red */
    color: hsla(0, 100%, 50%, 0.5); /* Semi-transparent red */
}

Backgrounds

.background-examples {
    /* Background color */
    background-color: #f0f0f0;
    
    /* Background image */
    background-image: url('image.jpg');
    
    /* Background repeat */
    background-repeat: no-repeat;
    background-repeat: repeat-x;
    background-repeat: repeat-y;
    
    /* Background position */
    background-position: center;
    background-position: top left;
    background-position: 50% 25%;
    
    /* Background size */
    background-size: cover;      /* Scale to cover entire element */
    background-size: contain;    /* Scale to fit inside element */
    background-size: 100% 50%;   /* Specific dimensions */
    
    /* Background attachment */
    background-attachment: fixed;   /* Fixed during scroll */
    background-attachment: scroll;  /* Scrolls with content */
    
    /* Shorthand */
    background: #fff url('bg.jpg') no-repeat center/cover;
}

Gradients

.gradients {
    /* Linear gradient */
    background: linear-gradient(to right, red, blue);
    background: linear-gradient(45deg, #ff0000, #0000ff);
    background: linear-gradient(to bottom, red, yellow, green);
    
    /* Radial gradient */
    background: radial-gradient(circle, red, blue);
    background: radial-gradient(ellipse at center, red, blue);
}

Layout Systems

Display Property

.display-examples {
    display: block;          /* Full width, new line */
    display: inline;         /* Inline with text */
    display: inline-block;   /* Inline but can have width/height */
    display: none;           /* Hidden, no space taken */
    display: flex;           /* Flexbox container */
    display: grid;           /* Grid container */
}

Position Property

.position-examples {
    /* Static (default) - normal document flow */
    position: static;
    
    /* Relative - positioned relative to normal position */
    position: relative;
    top: 10px;
    left: 20px;
    
    /* Absolute - positioned relative to nearest positioned ancestor */
    position: absolute;
    top: 0;
    right: 0;
    
    /* Fixed - positioned relative to viewport */
    position: fixed;
    bottom: 20px;
    right: 20px;
    
    /* Sticky - switches between relative and fixed */
    position: sticky;
    top: 0;
}

Float and Clear (Legacy)

.float-examples {
    float: left;
    float: right;
    float: none;
    
    clear: left;      /* Clear left floats */
    clear: right;     /* Clear right floats */
    clear: both;      /* Clear all floats */
}

Flexbox Layout

Flex Container

.flex-container {
    display: flex;
    
    /* Direction */
    flex-direction: row;         /* Default: left to right */
    flex-direction: column;      /* Top to bottom */
    flex-direction: row-reverse; /* Right to left */
    flex-direction: column-reverse; /* Bottom to top */
    
    /* Wrapping */
    flex-wrap: nowrap;          /* Default: no wrapping */
    flex-wrap: wrap;            /* Wrap to new lines */
    flex-wrap: wrap-reverse;    /* Wrap in reverse order */
    
    /* Shorthand for direction and wrap */
    flex-flow: row wrap;
    
    /* Horizontal alignment (main axis) */
    justify-content: flex-start;    /* Default: start */
    justify-content: center;        /* Center */
    justify-content: flex-end;      /* End */
    justify-content: space-between; /* Space between items */
    justify-content: space-around;  /* Space around items */
    justify-content: space-evenly;  /* Even space */
    
    /* Vertical alignment (cross axis) */
    align-items: stretch;       /* Default: stretch to fill */
    align-items: flex-start;    /* Top */
    align-items: center;        /* Center */
    align-items: flex-end;      /* Bottom */
    align-items: baseline;      /* Baseline alignment */
    
    /* Multi-line alignment */
    align-content: stretch;
    align-content: center;
    align-content: space-between;
}

Flex Items

.flex-item {
    /* Flexibility */
    flex-grow: 1;      /* Grow to fill space */
    flex-shrink: 0;    /* Don't shrink */
    flex-basis: 200px; /* Base size before growing/shrinking */
    
    /* Shorthand */
    flex: 1;           /* flex-grow: 1, flex-shrink: 1, flex-basis: 0% */
    flex: 0 0 200px;   /* No grow/shrink, 200px base */
    
    /* Individual alignment */
    align-self: center;
    align-self: stretch;
    
    /* Order */
    order: 2;          /* Change visual order */
}

CSS Grid Layout

Grid Container

.grid-container {
    display: grid;
    
    /* Define columns */
    grid-template-columns: 200px 1fr 100px;        /* Fixed, flexible, fixed */
    grid-template-columns: repeat(3, 1fr);          /* Three equal columns */
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); /* Responsive */
    
    /* Define rows */
    grid-template-rows: 100px auto 50px;
    grid-template-rows: repeat(3, 100px);
    
    /* Gap between items */
    gap: 20px;              /* Both row and column gap */
    row-gap: 15px;          /* Row gap only */
    column-gap: 25px;       /* Column gap only */
    
    /* Alignment */
    justify-items: center;   /* Horizontal alignment of items */
    align-items: center;     /* Vertical alignment of items */
    justify-content: center; /* Horizontal alignment of grid */
    align-content: center;   /* Vertical alignment of grid */
}

Grid Items

.grid-item {
    /* Position by line numbers */
    grid-column-start: 1;
    grid-column-end: 3;
    grid-row-start: 1;
    grid-row-end: 2;
    
    /* Shorthand */
    grid-column: 1 / 3;     /* From line 1 to line 3 */
    grid-row: 1 / 2;        /* From line 1 to line 2 */
    
    /* Span multiple cells */
    grid-column: span 2;    /* Span 2 columns */
    grid-row: span 3;       /* Span 3 rows */
    
    /* Named grid areas */
    grid-area: header;      /* Use named area */
    
    /* Individual alignment */
    justify-self: center;
    align-self: center;
}

Grid Template Areas

.grid-layout {
    display: grid;
    grid-template-areas:
        "header header header"
        "sidebar main main"
        "footer footer footer";
    grid-template-columns: 200px 1fr 1fr;
    grid-template-rows: auto 1fr auto;
}
 
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }

Responsive Design

Media Queries

/* Mobile first approach */
.responsive-element {
    /* Base styles for mobile */
    font-size: 14px;
    padding: 10px;
}
 
/* Tablet and up */
@media (min-width: 768px) {
    .responsive-element {
        font-size: 16px;
        padding: 15px;
    }
}
 
/* Desktop and up */
@media (min-width: 1024px) {
    .responsive-element {
        font-size: 18px;
        padding: 20px;
    }
}
 
/* Large desktop */
@media (min-width: 1200px) {
    .responsive-element {
        font-size: 20px;
        padding: 25px;
    }
}
 
/* Other media queries */
@media (max-width: 767px) { /* Mobile only */ }
@media (orientation: landscape) { /* Landscape orientation */ }
@media (prefers-color-scheme: dark) { /* Dark mode preference */ }
@media print { /* Print styles */ }

Flexible Units

.flexible-sizing {
    /* Relative to parent element */
    width: 50%;
    margin: 2em;        /* Relative to element's font-size */
    
    /* Relative to root element */
    font-size: 1.2rem;  /* Relative to root font-size */
    
    /* Viewport units */
    width: 100vw;       /* 100% of viewport width */
    height: 100vh;      /* 100% of viewport height */
    font-size: 4vw;     /* 4% of viewport width */
    
    /* Minimum and maximum */
    width: clamp(200px, 50%, 400px); /* Min 200px, preferred 50%, max 400px */
    font-size: min(4vw, 24px);       /* Smaller of 4vw or 24px */
    width: max(200px, 50%);          /* Larger of 200px or 50% */
}

Animations and Transitions

Transitions

.transition-element {
    /* Properties to transition */
    transition-property: all;           /* or specific properties */
    transition-duration: 0.3s;         /* Duration */
    transition-timing-function: ease;   /* Timing function */
    transition-delay: 0.1s;            /* Delay before starting */
    
    /* Shorthand */
    transition: all 0.3s ease 0.1s;
    transition: color 0.2s, background-color 0.3s;
    
    /* Example usage */
    background-color: blue;
    color: white;
}
 
.transition-element:hover {
    background-color: red;
    color: black;
    transform: scale(1.1);
}

Transforms

.transform-examples {
    /* 2D Transforms */
    transform: translate(50px, 100px);    /* Move */
    transform: scale(1.5);                /* Scale */
    transform: rotate(45deg);             /* Rotate */
    transform: skew(15deg, 0deg);         /* Skew */
    
    /* 3D Transforms */
    transform: translateZ(100px);
    transform: rotateX(45deg);
    transform: rotateY(45deg);
    transform: rotateZ(45deg);
    
    /* Combined transforms */
    transform: translate(50px, 100px) rotate(45deg) scale(1.2);
    
    /* Transform origin */
    transform-origin: center center;
    transform-origin: top left;
    transform-origin: 50% 50%;
}

Keyframe Animations

/* Define animation */
@keyframes slideIn {
    from {
        transform: translateX(-100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}
 
@keyframes bounce {
    0%, 20%, 60%, 100% {
        transform: translateY(0);
    }
    40% {
        transform: translateY(-20px);
    }
    80% {
        transform: translateY(-10px);
    }
}
 
/* Apply animation */
.animated-element {
    animation-name: slideIn;
    animation-duration: 0.5s;
    animation-timing-function: ease-out;
    animation-delay: 0.2s;
    animation-iteration-count: 1;
    animation-direction: normal;
    animation-fill-mode: forwards;
    
    /* Shorthand */
    animation: slideIn 0.5s ease-out 0.2s 1 normal forwards;
    animation: bounce 1s infinite;
}

Advanced Selectors and Techniques

Advanced Pseudo-classes

/* Form-specific pseudo-classes */
input:required { }      /* Required form fields */
input:optional { }      /* Optional form fields */
input:valid { }         /* Valid input */
input:invalid { }       /* Invalid input */
input:in-range { }      /* Value within range */
input:out-of-range { }  /* Value outside range */
 
/* UI state pseudo-classes */
:enabled { }            /* Enabled elements */
:disabled { }           /* Disabled elements */
:checked { }            /* Checked checkboxes/radio buttons */
:indeterminate { }      /* Indeterminate checkboxes */
 
/* Structural pseudo-classes */
:empty { }              /* Elements with no children */
:only-child { }         /* Only child of parent */
:first-of-type { }      /* First element of its type */
:last-of-type { }       /* Last element of its type */
:nth-of-type(2n) { }    /* Every 2nd element of its type */
 
/* Negation pseudo-class */
:not(.special) { }      /* Elements without 'special' class */
:not(p) { }            /* All elements except paragraphs */

CSS Variables (Custom Properties)

/* Define variables in root */
:root {
    --primary-color: #3498db;
    --secondary-color: #2ecc71;
    --font-size-base: 16px;
    --spacing-unit: 1rem;
}
 
/* Use variables */
.component {
    color: var(--primary-color);
    font-size: var(--font-size-base);
    margin: var(--spacing-unit);
    
    /* Fallback value */
    background-color: var(--tertiary-color, #f0f0f0);
}
 
/* Override variables in specific contexts */
.dark-theme {
    --primary-color: #5dade2;
    --secondary-color: #58d68d;
}

Common CSS Patterns

Centering Elements

/* Horizontal centering */
.center-horizontal {
    margin: 0 auto;        /* Block elements with fixed width */
    text-align: center;    /* Inline elements */
}
 
/* Vertical centering */
.center-vertical-flex {
    display: flex;
    align-items: center;
    justify-content: center;
}
 
.center-vertical-grid {
    display: grid;
    place-items: center;
}
 
.center-vertical-absolute {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

Card Components

.card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    padding: 1.5rem;
    margin: 1rem 0;
    transition: transform 0.2s, box-shadow 0.2s;
}
 
.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}
.nav {
    display: flex;
    list-style: none;
    margin: 0;
    padding: 0;
}
 
.nav-item {
    margin-right: 2rem;
}
 
.nav-link {
    text-decoration: none;
    color: #333;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    transition: background-color 0.2s;
}
 
.nav-link:hover,
.nav-link.active {
    background-color: #f0f0f0;
}

Quick Reference Cheat Sheet

Most Common Properties

/* Layout */
display, position, top, right, bottom, left
width, height, margin, padding
flex, grid, float, clear
 
/* Typography */
font-family, font-size, font-weight, font-style
color, text-align, line-height, letter-spacing
 
/* Background */
background-color, background-image, background-size
background-position, background-repeat
 
/* Border */
border, border-radius, box-shadow
 
/* Transforms & Animation */
transform, transition, animation
 
/* Responsive */
@media, clamp(), min(), max()

Units Reference

UnitDescriptionUse Case
pxPixels (absolute)Borders, fixed sizes
%Percentage of parentResponsive widths
emRelative to font-sizeMargins, padding
remRelative to root font-sizeFont sizes
vw1% of viewport widthResponsive typography
vh1% of viewport heightFull-height sections
frFraction of available spaceCSS Grid

Flexbox Quick Reference

/* Container */
display: flex;
flex-direction: row | column;
justify-content: flex-start | center | flex-end | space-between | space-around;
align-items: stretch | flex-start | center | flex-end;
 
/* Items */
flex: 1;               /* Grow to fill space */
flex: 0 0 200px;       /* Fixed 200px width */
align-self: center;    /* Override container alignment */

Grid Quick Reference

/* Container */
display: grid;
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: auto 1fr auto;
gap: 1rem;
 
/* Items */
grid-column: 1 / 3;    /* Span from column 1 to 3 */
grid-row: span 2;      /* Span 2 rows */

Best Practices

🎯 Organization

  • Use consistent naming conventions (BEM, SMACSS)
  • Group related properties together
  • Use comments to explain complex sections
  • Keep selectors as simple as possible

🚀 Performance

  • Minimize use of expensive properties (box-shadow, border-radius)
  • Use transform and opacity for animations
  • Avoid complex selectors
  • Use CSS-in-JS or CSS modules for large applications

♿ Accessibility

  • Ensure sufficient color contrast (4.5:1 for normal text)
  • Don’t rely on color alone to convey information
  • Use relative units for better scaling
  • Test with screen readers and keyboard navigation

📱 Responsive Design

  • Use mobile-first approach
  • Design with flexible layouts (Flexbox, Grid)
  • Use relative units when appropriate
  • Test on multiple devices and screen sizes

Common Mistakes to Avoid

Don’t:

  • Use !important unless absolutely necessary
  • Set fixed heights unless required
  • Use position: absolute for layout
  • Ignore browser prefixes for newer properties
  • Use inline styles for styling (use for dynamic values only)
  • Overuse div and class selectors

Do:

  • Use semantic HTML with CSS
  • Follow the cascade and specificity rules
  • Use CSS Grid and Flexbox for layout
  • Test cross-browser compatibility
  • Optimize for performance
  • Write maintainable, organized code

Last Updated: 2025-07-22