CSS Cheatsheet

A comprehensive CSS cheatsheet to help you master styling, layouts, and responsive design.

1. Introduction to CSS

What is CSS?

CSS (Cascading Style Sheets) is a style sheet language used for describing the presentation of a document written in HTML or XML. It controls the layout, design, and appearance of web pages. CSS enables web designers and developers to style elements such as fonts, colors, margins, borders, spacing, and positioning, providing a clean separation between structure (HTML) and presentation (CSS).

Key Features of CSS:

  • Separation of Content and Style: CSS allows you to manage the content of a website (HTML) separately from its design, making the site more maintainable and easier to update.
  • Styling Flexibility: CSS offers a wide variety of styling options, including text formatting, layout management, animations, and much more.
  • Cross-browser Compatibility: Modern browsers can render CSS styles consistently, although some older browsers may need specific adjustments.

Syntax and Structure

CSS uses a specific syntax and structure that is easy to understand. The basic CSS rule consists of two main parts: the selector and the declaration block.

  • Selector: The selector targets the HTML element(s) you want to style (e.g., p, .class, #id).
  • Declaration Block: The declaration block contains one or more property-value pairs enclosed in curly braces {}.

Here's the general structure:


selector {
    property: value;
}
                            

Example:


p {
    color: blue;
    font-size: 16px;
}
                            

In the above example:

  • The selector is p, targeting all <p> (paragraph) elements.
  • The declaration block contains two properties: color and font-size, with corresponding values blue and 16px.

Types of CSS: Inline, Internal, and External

CSS can be implemented in three different ways: Inline CSS, Internal CSS, and External CSS. Each method has its use cases and benefits.

1. Inline CSS:

Inline CSS is used to style a specific element directly within the HTML element's style attribute.

Example:


<p style="color: red; font-size: 18px;">This is an inline styled
 paragraph.</p>
                            

Pros:

  • Quick styling for single elements.
  • No need for external files.

Cons:

  • Difficult to manage and maintain.
  • Does not separate structure from presentation.

2. Internal CSS:

Internal CSS is written within the <style> tag in the <head> section of an HTML document.

Example:


<head>
    <style>
        p {
            color: green;
            font-size: 20px;
        }
    </style>
</head>
                            

Pros:

  • Convenient for styling single pages.
  • Better organization compared to inline CSS.

Cons:

  • Styles are not reusable across multiple pages.
  • Can make the HTML file large and hard to maintain.

3. External CSS:

External CSS is used when you write the CSS in a separate .css file, and link that file to your HTML page.

Example (HTML):


<head>
    <link rel="stylesheet" href="styles.css">
</head>
                            

Example (styles.css):


p {
    color: purple;
    font-size: 22px;
}
                            

Pros: Reusable on multiple pages, keeps HTML clean, and faster to load.

Cons: Needs an extra file.

2. CSS Selectors Overview

CSS selectors are patterns that tell CSS which HTML elements you want to style. There are different ways to select elements based on their tag, class, or ID.

Example:


/* This will change all paragraphs text to blue */
p {
    color: blue;
}

/* This will change the text of all elements with class 'highlight' to yellow */
.highlight {
    color: yellow;
}

/* This will change the text of the element with ID 'header' to green */
#header {
    color: green;
}
                        

1. Element Selectors

Targets HTML tags (like p, h1, div, etc.).

Example:


p {
    color: blue;
}
                            

This will turn all <p> elements blue.

2. Class Selectors

Targets elements with a specific class name.

Example:


.card {
    background-color: lightgray;
}
                            

Use it in HTML like:


<div class="card">Hello</div>
                            

You can reuse a class for multiple elements.

3. ID Selectors

Targets a unique element with a specific ID.

Example:


#main-heading {
    font-size: 24px;
}
                            

Use it in HTML like:


<h1 id="main-heading">Welcome</h1>
                            

Note: IDs should be unique per page.

4. Universal Selector (*)

Targets all elements on the page.

Example:


* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
                            

Great for applying a reset or default style.

5. Attribute Selectors

Target elements based on attributes.

Example:


input[type="text"] {
    border: 1px solid gray;
}
                            

You can target any HTML attribute:


a[target="_blank"] {
    color: red;
}
                            

6. Pseudo-class Selectors

Style elements based on a state or position.

Example:


a:hover {
    color: green;
}

button:active {
    background-color: red;
}
                            

Other pseudo-classes: :nth-child(), :focus, :last-child

7. Pseudo-element Selectors

Style parts of elements.

Example:


p::first-line {
    font-weight: bold;
}

div::before {
    content: "➡️ ";
    color: orange;
}

div::after {
    content: " ✅";
    color: green;
}
                            

Add content or style parts of an element without extra HTML.

8. Grouping Selectors

Apply the same style to multiple selectors at once.

Example:


h1, h2, h3 {
    font-family: Arial, sans-serif;
}
                            

Saves time and keeps code clean.

3. Colors in CSS

1. Named Colors

CSS comes with 140+ predefined color names like:

Example:


color: red;
color: blue;
color: skyblue;
                            

2. Hexadecimal Colors

Uses a hex code starting with #:

Example:


color: #ff0000; /* red */
color: #00ff00; /* green */
color: #0000ff; /* blue */
                            

3. RGB and RGBA

RGB = Red, Green, Blue (0 to 255)

RGBA adds Alpha for transparency (0 to 1)

Example:


color: rgb(255, 0, 0);
color: rgba(0, 0, 255, 0.5); /* 50% transparent blue */
                            

4. HSL and HSLA

HSL = Hue, Saturation, Lightness

HSLA adds transparency

Example:


color: hsl(0, 100%, 50%); /* red */
color: hsla(240, 100%, 50%, 0.7); /* 70% transparent blue */
                            

5. CSS Color Functions

You can use built-in functions:

Example:


color: rgb(255, 0, 0);
background-color: rgba(0, 0, 255, 0.5);
                            

4. Text Styling in CSS

1. Font Family

Set the type of font:

Example:


font-family: 'Arial', sans-serif;
                            

2. Font Size

Control size of text:

Example:


font-size: 16px;
font-size: 1.2em;
                            

3. Font Weight & Style

Weight: boldness | Style: italic/normal

Example:


font-weight: bold;
font-style: italic;
                            

4. Text Alignment & Decoration

Align text and add effects:

Example:


text-align: center;
text-decoration: underline;
                            

5. Text Transform

Change case:

Example:


text-transform: uppercase;
                            

6. Line Height

Spacing between lines:

Example:


line-height: 1.5;
                            

7. Letter Spacing & Word Spacing

Example:


letter-spacing: 2px;
word-spacing: 5px;
                            

8. Text Shadow

Add shadow to text:

Example:


text-shadow: 2px 2px 4px gray;
                            

9. Vertical Alignment

Align text vertically (rarely used on its own):

Example:


vertical-align: middle;
                            

5. CSS Box Model

1. Understanding the Box Model

Every HTML element is a box with 4 layers:


| Margin |
| Border |
| Padding |
| Content |
                            

2. Margin, Padding, and Border

  • Margin: Space outside the element
  • Padding: Space inside the element, around the content
  • Border: Line around the element

Example:


margin: 10px;
padding: 20px;
border: 2px solid black;
                            

3. Box Sizing

Controls how width/height is calculated:

Example:


box-sizing: content-box; /* Default */
box-sizing: border-box; /* Includes padding and border in width/height */
                            

4. Display Property

Controls how elements behave:

Example:


display: block; /* Takes full width, new line */
display: inline; /* Takes only needed width, same line */
display: inline-block; /* Inline but with width/height */
                            

5. Overflow Property

What happens when content overflows:

Example:


overflow: visible; /* Default */
overflow: hidden; /* Clips content */
overflow: scroll; /* Always shows scrollbars */
overflow: auto; /* Shows scrollbars if needed */
                            

6. Positioning in CSS

1. Static Positioning

Default. Element follows normal flow.

Example:


position: static;
                            

2. Relative Positioning

Moves element relative to its original position.

Example:


position: relative;
top: 10px;
left: 20px;
                            

3. Absolute Positioning

Positions relative to the nearest positioned ancestor.

Example:


position: absolute;
top: 0;
right: 0;
                            

4. Fixed Positioning

Stays fixed to the viewport even when scrolling.

Example:


position: fixed;
bottom: 20px;
right: 20px;
                            

5. Sticky Positioning

Acts like relative until it reaches a scroll position, then becomes fixed.

Example:


position: sticky;
top: 0;
                            

6. Z-Index

Controls stacking order (which element appears on top).

Example:


z-index: 10;
                            

7. Flexbox (Flexible Box Layout)

1. Introduction to Flexbox

Used for creating 1D layouts (row or column).

Example:


display: flex;
                            

2. Flex Container

The parent element with display: flex;.

3. Flex Items

The children inside the flex container.

4. Justify Content

Controls horizontal alignment:


justify-content: center; /* centers items */
justify-content: space-between; /* distributes items with space between */
                            

5. Align Items

Controls vertical alignment:


align-items: center; /* centers items vertically */
                            

6. Align Self

Aligns individual item:


align-self: flex-end;
                            

7. Flex Direction

Direction of items:


flex-direction: row; /* default */
flex-direction: column; /* stacks items vertically */
                            

8. Flex Wrap

Allows items to wrap to next line:


flex-wrap: wrap;
                            

9. Flex Grow, Shrink, and Basis


flex-grow: 1; /* item can grow */
flex-shrink: 0; /* item cannot shrink */
flex-basis: 100px; /* initial size */
                            

10. Ordering Items


order: 1; /* changes visual order */
                            

8. CSS Grid Layout

1. Introduction to Grid

Used for 2D layouts (rows + columns).


display: grid;
                            

2. Grid Container and Items

Parent with display: grid, children are grid items.

3. Grid Template Columns and Rows

Example:


grid-template-columns: 1fr 1fr 1fr; /* 3 equal columns */
grid-template-rows: auto 100px; /* auto height row, then 100px row */
                            

4. Grid Gaps

Space between rows and columns:


gap: 10px;
                            

5. Grid Areas

Name and place sections:


grid-area: header;
                            

6. Justify Items, Align Items, Place Items

Example:


justify-items: center;
align-items: stretch;
place-items: center; /* shorthand for both */
                            

7. Grid Template Areas

Example:


grid-template-areas:
    "header header"
    "sidebar content";
                            

8. Auto-placement in Grid

Let the browser automatically place items:


grid-auto-flow: row;
                            

9. Responsive Design

1. Media Queries

Apply styles based on screen size:

Example:


@media (max-width: 800px) {
    body {
        background: lightblue;
    }
}
                            

2. Viewport Units

  • vw: 1% of viewport width
  • vh: 1% of viewport height
  • vmin / vmax: smaller/larger of vw or vh

3. Flexbox in Responsive Design

Use flex-wrap, media queries, and flex-direction to adapt layouts.

4. CSS Grid in Responsive Design

Adjust grid-template-columns for different screen sizes.

5. Mobile-first Design

Start with styles for small screens, then use media queries for larger screens.

10. Transitions and Animations

1. CSS Transitions

Smooth changes in styles:


transition: all 0.3s ease;
                            

2. Transition Properties

Example:


transition-property: width, background-color;
transition-duration: 0.5s;
transition-timing-function: ease-in-out;
                            

3. CSS Animations (Keyframes)

More complex movement and changes:


@keyframes slide {
    0% { transform: translateX(0); }
    100% { transform: translateX(100px); }
}

.box {
    animation-name: slide;
    animation-duration: 2s;
}
                            

4. Animation Timing Functions

Control the speed curve:


animation-timing-function: ease-in-out; /* or linear, ease, etc. */
                            

11. Backgrounds and Borders

1. Background Images and Gradients

Add image or gradient in background.


background-image: url('image.jpg');
background: linear-gradient(to right, red, blue);
                            

2. Background Position and Size

Example:


background-position: center;
background-size: cover; /* covers the entire element */
                            

3. Border Styles and Radius

Example:


border: 1px solid black;
border-radius: 8px; /* rounded corners */
                            

4. Box Shadows

Example:


box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
                            

12. Lists and Tables

1. Styling Lists

Example:


ul {
    list-style-type: square; /* or circle, none, decimal */
}
                            

2. Table Styling

Example:


table {
    border-collapse: collapse;
    width: 100%;
}
th, td {
    border: 1px solid #ddd;
    padding: 8px;
}
                            

3. Table Layout and Borders

Example:


table {
    table-layout: fixed;
    border-spacing: 0;
}
                            

4. Styling Table Cells and Headers

Example:


th {
    background-color: #f2f2f2;
    text-align: left;
}
                            

13. Typography

1. Web Fonts

Use Google Fonts:


<link href="https://fonts.googleapis.com/css2?family=Poppins" rel="stylesheet">
                            

2. Font-Weight and Font-Family

Example:


font-weight: bold;
font-family: Arial, sans-serif;
                            

3. Text Decoration

Example:


text-decoration: underline;
                            

4. Font Sizing Units

Example:


font-size: 16px;
font-size: 1em;
font-size: 1rem;
                            

5. Line Height and Letter Spacing

Example:


line-height: 1.6;
letter-spacing: 0.5px;
                            

14. CSS Variables

1. Introduction to CSS Variables (Custom Properties)

Store values and reuse them.

2. Declaring and Using Variables

Example:


:root {
    --primary-color: blue;
}
p {
    color: var(--primary-color);
}
                            

3. Scoped Variables

Variables inside a selector are scoped to it only.

4. Benefits

  • Easy to update.
  • Clean and reusable code.
  • Great for theming.

15. Advanced CSS

1. CSS Shapes

Create non-rectangular shapes with clip-path.

2. Clip-path Property

Clip elements into custom shapes.


clip-path: circle(50% at 50% 50%);
                            

3. CSS Filters

Apply image-like effects:


filter: grayscale(100%);
                            

4. Object Fit and Object Position

Control image sizing inside container.


object-fit: cover;
object-position: center;
                            

5. CSS Transforms

Move, rotate, scale elements:


transform: rotate(45deg);
transform: scale(1.2);
transform: translate(10px, 20px);
                            

16. CSS Best Practices

1. Naming Conventions (BEM, OOCSS)

  • BEM (Block Element Modifier)
  • Example:

    
    .block__element--modifier { /* styles */ }
                                    
  • OOCSS (Object-Oriented CSS)
  • Separate structure and skin for reuse:

    
    .button { /* structure */ }
    .button--red { /* skin */ }
                                    

2. Using CSS Preprocessors (Sass, LESS)

Sass / LESS allow nesting, variables, mixins, etc.

Example (Sass):


$primary-color: #337ab7;
.button {
    background-color: $primary-color;
    &:hover {
        background-color: darken($primary-color, 10%);
    }
}
                            

3. Modular and Scalable CSS

  • Break styles into components.
  • Avoid global styles.
  • Use clear folder structure (e.g., base/, components/, layouts/).

4. Performance Tips

  • Minify CSS files.
  • Combine CSS files to reduce HTTP requests.
  • Use shorthand properties.

17. CSS Frameworks and Libraries

1. Popular Frameworks

  • Bootstrap – Ready UI components & grid system.
  • Tailwind CSS – Utility-first approach (e.g., bg-blue-500, text-center).
  • Foundation – Responsive, accessible components.

Example (Bootstrap Button):


<button class="btn btn-primary">Click Me</button>
                            

Example (Tailwind CSS Button):


<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
    Click Me
</button>
                            

2. When to Use Frameworks

  • Need to build fast.
  • Reuse UI components.
  • Consistent styling across large projects.

18. CSS in Practice

1. Layouts

Structure common areas:

Example:


/* Basic Grid Layout */
.container {
    display: grid;
    grid-template-areas:
        "header"
        "main"
        "footer";
    grid-template-rows: auto 1fr auto;
    min-height: 100vh;
}

.header { grid-area: header; background-color: #f0f0f0; padding: 1rem; }
.main { grid-area: main; padding: 1rem; }
.footer { grid-area: footer; background-color: #333; color: white; padding: 1rem; text-align: center; }
                            

<div class="container">
    <header class="header">Header</header>
    <main class="main">Main Content</main>
    <footer class="footer">Footer</footer>
</div>
                            

2. Navigation Menus

Example:


/* Simple Horizontal Navigation */
.navbar ul {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    justify-content: space-around;
    background-color: #eee;
    border-radius: 0.5rem;
}

.navbar li a {
    display: block;
    padding: 0.8rem 1.2rem;
    text-decoration: none;
    color: #333;
    transition: background-color 0.3s ease;
    border-radius: 0.5rem;
}

.navbar li a:hover {
    background-color: #ddd;
}
                            

<nav class="navbar">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
</nav>
                            

3. Styling Forms

Example:


/* Basic Form Styling */
.form-group {
    margin-bottom: 1rem;
}

.form-label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 600;
    color: #444;
}

.form-control {
    width: 100%;
    padding: 0.75rem;
    border: 1px solid #ccc;
    border-radius: 0.5rem;
    box-sizing: border-box; /* Include padding and border in element's total width and height */
    font-size: 1rem;
}

.form-control:focus {
    border-color: #6366f1;
    outline: none;
    box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.2);
}
                            

<form>
    <div class="form-group">
        <label for="name" class="form-label">Name:</label>
        <input type="text" id="name" class="form-control" placeholder="Your Name">
    </div>
    <div class="form-group">
        <label for="email" class="form-label">Email:</label>
        <input type="email" id="email" class="form-control" placeholder="Your Email">
    </div>
    <button type="submit" class="btn-primary">Submit</button>
</form>
                            

4. Buttons and Icons

Example:


/* Styled Button */
.styled-button {
    background-color: #6366f1;
    color: white;
    padding: 0.8rem 1.5rem;
    border: none;
    border-radius: 0.75rem;
    cursor: pointer;
    font-size: 1rem;
    font-weight: 600;
    transition: background-color 0.3s ease, transform 0.2s ease;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.styled-button:hover {
    background-color: #4f46e5;
    transform: translateY(-2px);
}

/* Icon Styling (using Font Awesome) */
.icon-example {
    font-size: 1.2em; /* Adjust size relative to parent text */
    margin-right: 0.5rem; /* Space between icon and text */
    color: #6366f1; /* Example color for icons */
}
                            

<button class="styled-button">
    <i class="fas fa-download icon-example"></i> Download
</button>

<a href="#">
    <i class="fas fa-home icon-example"></i> Home
</a>
                            

19. Tools and Resources

1. CSS Validators

Check for errors:

W3C CSS Validator

Example (using a validator):


/* This CSS has a typo (colr instead of color) */
.my-element {
    colr: red;
    font-size: 16px;
}
/* A CSS validator would flag 'colr' as an invalid property. */
                            

2. Code Generators

Generate CSS visually:

Example (Generated Gradient CSS):


.my-gradient-box {
    background: linear-gradient(to right, #ff7e5f, #feb47b);
    border-radius: 8px;
    padding: 20px;
    color: white;
    text-align: center;
}
                            

3. Useful Plugins

Easy-to-use CSS tools:

Example (Animate.css):


<h1 class="animate__animated animate__bounce">Hello World!</h1>
                            

/* You would include Animate.css via a CDN or local file */
/* <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" /> */
                            

📌 Note:

Tap on any of the links above to directly open the tools in your browser. These resources will help you write, test, and improve your CSS faster and more efficiently!

20. Appendix

1. Quick Reference

Quick Reference for Common CSS Properties.

Example (Common Properties):


/* Box Model */
margin: 10px;
padding: 15px;
border: 1px solid #333;
box-sizing: border-box;

/* Typography */
font-family: 'Inter', sans-serif;
font-size: 16px;
color: #333;
text-align: center;

/* Layout */
display: flex;
justify-content: center;
align-items: center;
                            

2. Browser Compatibility

Always check support using: caniuse.com

Example (Checking Compatibility):


// Visit caniuse.com and search for 'grid' to see its browser support.
// You'll see a table indicating which browser versions support the feature.
                            

3. Learning Resources

Example (Applying Learning):


/* After learning about Flexbox from MDN, you might apply it like this: */
.flex-container {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}
                            

Download the Full CSS Cheatsheet PDF!

Click the button below to get your copy of this CSS cheatsheet in a handy PDF format. Download will be ready in 5 seconds.

Ready for the JavaScript Cheatsheet?

Explore our comprehensive JavaScript Cheatsheet to enhance your coding skills. Click below to dive in!

Other Cheatsheets

Stay Updated

Get coding tips and resource updates. No spam.

We respect your privacy. Unsubscribe at any time.