|

CSS 58 💻 Cheatsheet






1. Selectors

Basic Selectors

SelectorSyntaxDescription
Elementp { }Targets all elements by tag name
Class.highlight { }Targets elements with a specific class
ID#main-title { }Targets one unique element
Universal* { }Targets all elements
Attribute[type="text"] { }Targets elements with a specific attribute
p { color: blue; }
.highlight { background-color: yellow; }
#main-title { font-size: 36px; }
* { margin: 0; padding: 0; }
[type="text"] { border: 1px solid black; }

Attribute Selectors

SyntaxDescriptionExample
[attr]Has attribute[disabled] { }
[attr="value"]Exact match[type="text"] { }
[attr^="value"]Starts with[class^="btn-"] { }
[attr$="value"]Ends with[href$=".pdf"] { }
[attr*="value"]Contains[class*="icon"] { }
[attr~="value"]Word match[class~="active"] { }

Combinators

CombinatorSyntaxDescription
Descendantdiv p { }All <p> inside <div>
Childul > li { }Direct children only
Adjacent Siblingh1 + p { }<p> immediately after <h1>
General Siblingh2 ~ p { }All <p> after <h2>
div p { color: red; }
ul > li { font-weight: bold; }
h1 + p { margin-top: 20px; }
h2 ~ p { font-style: italic; }

Pseudo-Classes

Pseudo-ClassDescription
:hoverMouse over element
:focusElement has focus
:activeElement being clicked
:visitedVisited link
:first-childFirst child of parent
:last-childLast child of parent
:nth-child(n)Nth child
:not(selector)Negation
a:hover { color: red; }
input:focus { border-color: blue; }
li:first-child { font-weight: bold; }
li:nth-child(odd) { background: #f0f0f0; }

Pseudo-Elements

Pseudo-ElementDescription
::beforeInsert before content
::afterInsert after content
::first-lineFirst line of text
::first-letterFirst letter
::placeholderInput placeholder
.quote::before { content: "“"; }
.quote::after { content: "”"; }
p::first-letter { font-size: 2em; }
input::placeholder { color: gray; }

2. Box Model

The Four Layers

┌─────────────────────────────────────┐
│              MARGIN                  │
│  ┌───────────────────────────────┐  │
│  │           BORDER               │  │
│  │  ┌─────────────────────────┐  │  │
│  │  │        PADDING          │  │  │
│  │  │  ┌───────────────────┐  │  │  │
│  │  │  │     CONTENT       │  │  │  │
│  │  │  └───────────────────┘  │  │  │
│  │  └─────────────────────────┘  │  │
│  └───────────────────────────────┘  │
└─────────────────────────────────────┘

Properties

/* Margin — space OUTSIDE the border */
margin: 10px;                    /* All sides */
margin: 10px 20px;               /* Vertical | Horizontal */
margin: 10px 20px 30px;          /* Top | Horizontal | Bottom */
margin: 10px 20px 30px 40px;     /* Top | Right | Bottom | Left */
margin: 0 auto;                  /* Center block element */

/* Padding — space INSIDE the border */
padding: 10px;
padding: 10px 20px;
padding: 10px 20px 30px;
padding: 10px 20px 30px 40px;

/* Border */
border: 1px solid black;
border-width: 2px;
border-style: dashed;  /* solid, dashed, dotted, double, groove, ridge, inset, outset */
border-color: red;
border-radius: 8px;    /* Rounded corners */

/* Width & Height */
width: 300px;
height: 200px;
max-width: 100%;
min-height: 100vh;

/* Box Sizing (best practice) */
*, *::before, *::after {
    box-sizing: border-box;
}

3. Typography

/* Font Family */
font-family: 'Segoe UI', Arial, sans-serif;

/* Font Size */
font-size: 16px;
font-size: 1rem;      /* Relative to root */
font-size: 1.2em;     /* Relative to parent */
font-size: clamp(1rem, 2vw, 2rem); /* Responsive */

/* Font Weight */
font-weight: normal;   /* 400 */
font-weight: bold;     /* 700 */
font-weight: 300;      /* Light */

/* Font Style */
font-style: italic;
font-style: normal;

/* Text Alignment */
text-align: left;      /* Default */
text-align: center;
text-align: right;
text-align: justify;

/* Text Decoration */
text-decoration: none;
text-decoration: underline;
text-decoration: line-through;

/* Text Transform */
text-transform: uppercase;
text-transform: lowercase;
text-transform: capitalize;

/* Line Height */
line-height: 1.6;      /* Unitless — recommended */
line-height: 24px;

/* Letter Spacing */
letter-spacing: 2px;

/* Word Spacing */
word-spacing: 4px;

/* Text Shadow */
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);

/* Truncate Text */
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;

4. Colors

FormatExampleDescription
NamedredPredefined color names
Hex#FF00006-digit hex
Hex (short)#F003-digit hex
RGBrgb(255, 0, 0)Red, Green, Blue (0–255)
RGBArgba(255, 0, 0, 0.5)RGB + opacity
HSLhsl(0, 100%, 50%)Hue, Saturation, Lightness
HSLAhsla(0, 100%, 50%, 0.5)HSL + opacity
Modernoklch(69% 0.27 240)Perceptually uniform
/* Color Properties */
color: #333;
background-color: rgba(255, 0, 0, 0.5);
border-color: hsl(0, 100%, 75%);
caret-color: red;

/* Opacity */
opacity: 0.7;

/* Gradients */
background: linear-gradient(to right, red, blue);
background: radial-gradient(circle, red, blue);
background: conic-gradient(red, blue, green, red);
background: repeating-linear-gradient(45deg, red 10%, blue 20%);

5. Background

/* Background Color */
background-color: #f0f0f0;

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

/* Background Repeat */
background-repeat: no-repeat;  /* repeat, repeat-x, repeat-y, space, round */

/* Background Position */
background-position: center;   /* top, bottom, left, right, center, % */
background-position: center top;

/* Background Size */
background-size: cover;        /* cover, contain, auto, 100% */
background-size: contain;

/* Background Attachment */
background-attachment: fixed;  /* scroll, fixed, local */

/* Background Clip */
background-clip: padding-box;  /* border-box, padding-box, content-box, text */

/* Background Origin */
background-origin: border-box;

/* Shorthand */
background: url('image.jpg') center / cover no-repeat fixed #f8f9fa;

6. Display

ValueDescription
blockFull width, new line
inlineSits next to other elements
inline-blockInline but respects width/height
flexFlex container
gridGrid container
noneHidden (removed from flow)
display: block;
display: inline;
display: inline-block;
display: flex;
display: grid;
display: none;

7. Positioning

ValueDescription
staticNormal flow (default)
relativeRelative to normal position
absoluteRelative to nearest positioned ancestor
fixedRelative to viewport
stickyRelative until threshold, then fixed
/* Relative */
position: relative;
top: 20px;
left: 30px;

/* Absolute */
position: absolute;
top: 50px;
right: 100px;

/* Fixed */
position: fixed;
bottom: 20px;
left: 30px;

/* Sticky */
position: sticky;
top: 0;

/* Z-index */
z-index: 10;

/* Center with absolute + translate */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

8. Flexbox

Container Properties

.container {
    display: flex;

    /* Direction */
    flex-direction: row;         /* Default */
    flex-direction: column;
    flex-direction: row-reverse;
    flex-direction: column-reverse;

    /* Wrapping */
    flex-wrap: nowrap;           /* Default */
    flex-wrap: wrap;
    flex-wrap: wrap-reverse;

    /* Shorthand */
    flex-flow: row wrap;

    /* Main Axis Alignment */
    justify-content: flex-start;    /* Default */
    justify-content: flex-end;
    justify-content: center;
    justify-content: space-between;
    justify-content: space-around;
    justify-content: space-evenly;

    /* Cross Axis Alignment */
    align-items: stretch;           /* Default */
    align-items: flex-start;
    align-items: flex-end;
    align-items: center;
    align-items: baseline;

    /* Multi-line Alignment */
    align-content: flex-start;
    align-content: center;
    align-content: space-between;

    /* Gap */
    gap: 20px;
    gap: 20px 10px;  /* row-gap column-gap */
}

Item Properties

.item {
    /* Growth */
    flex-grow: 0;        /* Default */
    flex-grow: 1;

    /* Shrinking */
    flex-shrink: 1;      /* Default */
    flex-shrink: 0;

    /* Base Size */
    flex-basis: auto;    /* Default */
    flex-basis: 200px;
    flex-basis: 50%;

    /* Shorthand */
    flex: 1;             /* grow: 1, shrink: 1, basis: 0% */
    flex: auto;          /* grow: 1, shrink: 1, basis: auto */
    flex: none;          /* grow: 0, shrink: 0, basis: auto */
    flex: 2 1 200px;     /* grow: 2, shrink: 1, basis: 200px */

    /* Individual Alignment */
    align-self: center;

    /* Order */
    order: 2;            /* Default is 0 */
}

9. Grid

Container Properties

.container {
    display: grid;

    /* Columns */
    grid-template-columns: 1fr 2fr 1fr;
    grid-template-columns: repeat(3, 1fr);
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    grid-template-columns: minmax(100px, 200px) auto;

    /* Rows */
    grid-template-rows: 100px auto 200px;
    grid-template-rows: repeat(3, 1fr);

    /* Named Areas */
    grid-template-areas:
        "header header header"
        "sidebar main main"
        "footer footer footer";

    /* Shorthand */
    grid-template:
        "header header" auto
        "sidebar main" 200px / 1fr 3fr;

    /* Gaps */
    gap: 20px;
    row-gap: 20px;
    column-gap: 10px;

    /* Alignment */
    justify-items: start;   /* start, center, end, stretch */
    align-items: start;     /* start, center, end, stretch */
    justify-content: center; /* whole grid */
    align-content: center;

    /* Auto Placement */
    grid-auto-flow: row;          /* row, column, row dense */
    grid-auto-columns: 200px;
    grid-auto-rows: 100px;
}

Item Properties

.item {
    /* Named Area */
    grid-area: header;

    /* Numeric Placement */
    grid-area: 1 / 1 / 3 / 3;   /* row-start / col-start / row-end / col-end */

    /* Individual */
    grid-row: 1 / 3;
    grid-column: 2 / 4;
    grid-row-start: 1;
    grid-row-end: 3;
    grid-column-start: 2;
    grid-column-end: 4;

    /* Span */
    grid-column: 1 / span 2;

    /* Self Alignment */
    justify-self: center;
    align-self: center;
}

10. Transitions

/* Individual Properties */
transition-property: background-color, transform;
transition-duration: 0.5s;
transition-timing-function: ease-in-out;
transition-delay: 0.2s;
transition-behavior: allow-discrete;  /* For display/visibility */

/* Shorthand */
transition: background-color 0.5s ease;
transition: transform 0.3s ease-in-out 0.1s;
transition: all 0.3s ease;

/* Multiple Properties */
transition: 
    background-color 0.5s ease,
    transform 0.3s ease,
    box-shadow 0.5s ease;

Timing Functions

ValueDescription
easeSlow start, fast middle, slow end (default)
linearConstant speed
ease-inSlow start, fast end
ease-outFast start, slow end
ease-in-outSlow start, fast middle, slow end
cubic-bezier(n,n,n,n)Custom curve
steps(n)Stepped animation

11. Animations

Applying Animations

.box {
    /* Individual Properties */
    animation-name: slideIn;
    animation-duration: 2s;
    animation-timing-function: ease-in-out;
    animation-delay: 0.5s;
    animation-iteration-count: infinite;
    animation-direction: alternate;
    animation-fill-mode: forwards;
    animation-play-state: running;
    animation-timeline: scroll();
    animation-composition: replace;

    /* Shorthand */
    animation: slideIn 2s ease-in-out 0.5s infinite alternate forwards;
}

@keyframes

/* Using from/to */
@keyframes fadeIn {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Using percentages */
@keyframes bounce {
    0%   { transform: translateY(0); }
    50%  { transform: translateY(-50px); }
    100% { transform: translateY(0); }
}

/* Multi-step */
@keyframes multiStep {
    0%   { background: red; transform: translate(0, 0); }
    25%  { background: blue; transform: translate(100px, 0); }
    50%  { background: green; transform: translate(100px, 100px); }
    75%  { background: yellow; transform: translate(0, 100px); }
    100% { background: red; transform: translate(0, 0); }
}

Animation Properties Reference

PropertyValuesDefault
animation-name@keyframes namenone
animation-durations, ms0s
animation-timing-functionease, linear, etc.ease
animation-delays, ms0s
animation-iteration-countnumber, infinite1
animation-directionnormal, reverse, alternate, alternate-reversenormal
animation-fill-modenone, forwards, backwards, bothnone
animation-play-staterunning, pausedrunning
animation-timelineauto, none, scroll(), view()auto
animation-compositionreplace, add, accumulatereplace

12. Transforms

/* 2D Transforms */
transform: translate(50px, 25px);
transform: translateX(50px);
transform: translateY(25px);
transform: scale(1.5);
transform: scale(1.5, 2);
transform: scaleX(2);
transform: scaleY(0.5);
transform: rotate(45deg);
transform: skew(30deg, -20deg);
transform: skewX(30deg);
transform: skewY(20deg);

/* 3D Transforms */
transform: translate3d(50px, 25px, 100px);
transform: translateZ(100px);
transform: scale3d(1.5, 1.5, 2);
transform: scaleZ(2);
transform: rotate3d(1, 1, 1, 90deg);
transform: rotateX(45deg);
transform: rotateY(45deg);
transform: rotateZ(45deg);

/* Matrix */
transform: matrix(1, 0, 0, 1, 100, 100);
transform: matrix3d(...);  /* 16 values */

/* Combined */
transform: rotate(45deg) scale(1.5) translate(20px, 10px);

/* Related Properties */
transform-origin: center center;  /* top left, bottom right, % */
transform-style: preserve-3d;
perspective: 800px;
backface-visibility: hidden;

13. Media Queries

Common Breakpoints

BreakpointDevice
320pxSmall phones
480pxLarger phones
768pxTablets
1024pxSmall laptops
1200pxDesktops
1440pxLarge desktops

Syntax

/* Width-based */
@media (min-width: 768px) { }
@media (max-width: 1024px) { }
@media (min-width: 768px) and (max-width: 1024px) { }

/* Orientation */
@media (orientation: portrait) { }
@media (orientation: landscape) { }

/* Dark mode */
@media (prefers-color-scheme: dark) { }
@media (prefers-color-scheme: light) { }

/* Reduced motion */
@media (prefers-reduced-motion: reduce) { }
@media (prefers-reduced-motion: no-preference) { }

/* Contrast */
@media (prefers-contrast: more) { }
@media (prefers-contrast: less) { }

/* Hover capability */
@media (hover: hover) { }
@media (hover: none) { }

/* Pointer accuracy */
@media (pointer: fine) { }
@media (pointer: coarse) { }
@media (pointer: none) { }

/* Reduced data */
@media (prefers-reduced-data: reduce) { }

/* Reduced transparency */
@media (prefers-reduced-transparency: reduce) { }

/* Forced colors (high contrast mode) */
@media (forced-colors: active) { }

/* Print */
@media print { }

/* Range syntax (modern) */
@media (width >= 768px) { }
@media (768px <= width <= 1024px) { }

Common Media Features

FeatureDescription
width / min-width / max-widthViewport width
height / min-height / max-heightViewport height
orientationportrait / landscape
aspect-ratioViewport ratio
resolutionPixel density (dpi, dppx)
hover / any-hoverHover capability
pointer / any-pointerPointer accuracy
prefers-color-schemeDark/light mode
prefers-reduced-motionReduced motion
prefers-contrastContrast preference
prefers-reduced-dataData saver
prefers-reduced-transparencyTransparency preference
forced-colorsHigh contrast mode
color-gamutColor space (srgb, p3, rec2020)
dynamic-rangeHDR support
scriptingJavaScript availability
updateRefresh rate (none, slow, fast)
overflow-blockBlock axis overflow
overflow-inlineInline axis overflow
gridGrid-based screen

14. Units

Absolute Units

UnitDescription
pxPixels (1/96 inch)
cmCentimeters
mmMillimeters
inInches
ptPoints (1/72 inch)
pcPicas (12 points)

Relative Units

UnitRelative To
%Parent element
emCurrent font size
remRoot font size
vwViewport width (1% = 1vw)
vhViewport height
vminSmaller of vw/vh
vmaxLarger of vw/vh
chWidth of ‘0’ character
exx-height of font
frFraction of available space
lhLine height

Angle Units

UnitDescription
degDegrees (360 = full circle)
radRadians (2π = full circle)
gradGradians (400 = full circle)
turnTurns (1 = full circle)

15. Other Useful Properties

/* Visibility */
visibility: hidden;
display: none;
opacity: 0.5;

/* Overflow */
overflow: hidden;
overflow: auto;
overflow: scroll;
overflow-x: auto;
overflow-y: scroll;

/* Cursor */
cursor: pointer;
cursor: default;
cursor: not-allowed;

/* Box Shadow */
box-shadow: 2px 4px 6px rgba(0, 0, 0, 0.5);
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
box-shadow: 0 4px 6px rgba(0,0,0,0.1), 0 10px 20px rgba(0,0,0,0.05);

/* Filters */
filter: blur(5px);
filter: brightness(150%);
filter: contrast(200%);
filter: grayscale(100%);
filter: hue-rotate(180deg);
filter: invert(100%);
filter: saturate(200%);
filter: sepia(70%);
filter: drop-shadow(0 4px 6px rgba(0,0,0,0.3));

/* Object Fit */
object-fit: cover;      /* contain, fill, none, scale-down */
object-position: center;

/* Aspect Ratio */
aspect-ratio: 16 / 9;

/* Writing Mode */
writing-mode: vertical-rl;
writing-mode: horizontal-tb;

/* Scroll Behavior */
scroll-behavior: smooth;

/* User Select */
user-select: none;

/* Pointer Events */
pointer-events: none;
pointer-events: auto;

16. Best Practices

✅ Do This

/* Use box-sizing globally */
*, *::before, *::after {
    box-sizing: border-box;
}

/* Use CSS custom properties for theming */
:root {
    --primary: #007bff;
    --text: #333;
}
.button {
    background: var(--primary);
    color: var(--text);
}

/* Use transform instead of top/left for animations */
.box {
    transition: transform 0.3s ease;
}
.box:hover {
    transform: translateY(-5px);
}

/* Use rem for font sizes */
html { font-size: 16px; }
h1 { font-size: 2rem; }

/* Use modern layout systems */
.container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}

/* Respect user preferences */
@media (prefers-reduced-motion: reduce) {
    * { animation: none; transition: none; }
}
@media (prefers-color-scheme: dark) {
    :root { --bg: #1a1a1a; --text: #f8f9fa; }
}

/* Use logical properties */
margin-inline: auto;   /* Instead of margin-left/right */
padding-block: 20px;   /* Instead of padding-top/bottom */

❌ Don’t Do This

/* Don't use !important */
.button { color: red !important; }

/* Don't use px for font sizes (accessibility issue) */
p { font-size: 16px; }  /* Use rem instead */

/* Don't animate layout properties */
.box { transition: width 0.3s, height 0.3s; }

/* Don't use IDs for styling */
#button { }  /* Use classes instead */

/* Don't use transition: all */
.box { transition: all 0.3s; }  /* Specify properties */

/* Don't ignore reduced motion */
/* Always provide @media (prefers-reduced-motion: reduce) */

/* Don't use fixed pixel widths for responsive layouts */
.container { width: 1200px; }  /* Use max-width + % */

17. CSS Custom Properties (Variables)

/* Define */
:root {
    --primary-color: #007bff;
    --secondary-color: #6c5ce7;
    --text-color: #333;
    --spacing: 20px;
    --border-radius: 8px;
    --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

/* Use */
.button {
    background: var(--primary-color);
    color: var(--text-color);
    padding: var(--spacing);
    border-radius: var(--border-radius);
    box-shadow: var(--shadow);
}

/* Fallback */
.color {
    color: var(--text-color, #333);
}

/* Override for dark mode */
@media (prefers-color-scheme: dark) {
    :root {
        --text-color: #f8f9fa;
        --primary-color: #4dabf7;
    }
}

18. Functions

/* calc() — Calculations */
width: calc(100% - 40px);
height: calc(100vh - 80px);
font-size: calc(1rem + 2vw);

/* clamp() — Responsive sizing */
font-size: clamp(1rem, 2vw, 2rem);
width: clamp(300px, 50%, 800px);

/* min() / max() */
width: min(100%, 800px);
width: max(300px, 50%);

/* var() — Custom properties */
color: var(--text-color);

/* url() — Resources */
background-image: url('image.jpg');

/* Counter */
counter-reset: section;
counter-increment: section;
content: counter(section);

Quick Reference Card

SELECTORS          BOX MODEL         FLEXBOX          GRID
─────────          ─────────         ───────          ────
p { }              margin            display: flex    display: grid
.class { }         padding           flex-direction   grid-template-columns
#id { }            border            justify-content  grid-template-rows
* { }              width/height      align-items      gap
[attr] { }         box-sizing        gap              grid-area
div p { }                            flex             grid-row / grid-column
ul > li { }        POSITION          flex-wrap
h1 + p { }         ────────          align-self       ANIMATION
h2 ~ p { }         static            order            ─────────
                   relative                           animation
:hover { }         absolute          TRANSITIONS      @keyframes
::before { }       fixed             ───────────      animation-name
                   sticky            transition       animation-duration
UNITS                                transition-property
─────              TYPOGRAPHY        transition-duration
px  em  rem        ──────────        transition-timing-function
%   vw  vh         font-family       transition-delay
fr  ch  deg        font-size
                   font-weight       TRANSFORMS
                   text-align        ──────────
                   line-height       translate
                   letter-spacing    scale
                   text-transform    rotate
                   text-shadow       skew
                                     perspective

Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!