Quick reference for CSS basics — selectors, layout, flexbox, grid, and responsive design.
| Concept | Description |
|---|---|
| Element | div — matches all elements of that type |
| Class | .card — matches elements with that class |
| ID | #main — matches the unique element with that ID |
| Attribute | [type="text"] — matches elements with that attribute value |
| Pseudo-class | :hover — matches based on element state |
| Pseudo-element | ::before — targets a virtual child element |
| Child | ul > li — direct children only |
| Descendant | ul li — any nested level |
| Sibling | h2 + p — next adjacent sibling |
/* Box-sizing — use border-box everywhere */
*, *::before, *::after {
box-sizing: border-box;
}
/* Units */
width: 100%; /* percentage of parent */
width: 50vw; /* viewport width */
height: 100vh; /* viewport height */
font-size: 1.5rem; /* relative to root font-size */
font-size: 1.2em; /* relative to parent font-size */
gap: 8px; /* absolute pixels */
.container {
display: flex;
flex-direction: row; /* row | row-reverse | column | column-reverse */
justify-content: center; /* flex-start | flex-end | center | space-between | space-around | space-evenly */
align-items: center; /* flex-start | flex-end | center | stretch | baseline */
flex-wrap: wrap; /* nowrap | wrap | wrap-reverse */
gap: 16px;
}
.item {
flex: 1; /* grow | shrink | basis */
align-self: flex-end; /* override align-items per item */
order: 2; /* reorder items */
}
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
grid-template-columns: 200px 1fr 1fr; /* fixed + flexible */
grid-template-rows: auto 1fr auto;
gap: 16px;
}
.item {
grid-column: 1 / 3; /* span 2 columns */
grid-row: 1 / 4; /* span 3 rows */
grid-area: header; /* named area */
}
/* Named grid areas */
.grid {
grid-template-areas:
"header header header"
"sidebar content content"
"footer footer footer";
}
.static { position: static; } /* default — normal flow */
.relative { position: relative; } /* offset from normal position */
.absolute { position: absolute; } /* relative to positioned ancestor */
.fixed { position: fixed; } /* relative to viewport */
.sticky { position: sticky; top: 0; } /* switches between relative & fixed */
/* Media queries */
@media (max-width: 768px) {
.container { flex-direction: column; }
}
/* Container queries */
@container (min-width: 400px) {
.card { flex-direction: row; }
}
/* clamp() for fluid typography */
h1 {
font-size: clamp(1.5rem, 4vw, 3rem);
}
/* Responsive images */
img {
max-width: 100%;
height: auto;
}
/* Center a div */
.center {
display: grid;
place-items: center;
}
/* Truncate text */
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Scroll snap */
.slider {
scroll-snap-type: x mandatory;
}
.slider > * {
scroll-snap-align: start;
}
/* Aspect ratio */
.video {
aspect-ratio: 16 / 9;
}