A collection of tricks and common things to achieve with CSS.
Centering
- Centering horizontally:
- Inline?
text-align: centeron the parent. - Block?
margin: 0 auto; width: 200px. - Multiple blocks?
display: flex; justify-content: center. - Hack:
- Inline?
- Centering vertically:
- Inline (text)?:
.center-text { height: 100px; line-height: 100px; white-space: nowrap; }- Block?
display: flex; flex-direction: column; justify-content: center;- Hack:
Images
- Fluid images to prevent images from ever overflowing:
img { max-width: 100%; }. - To make background images fit neatly into cards:
aspect-ratio: 16/9; background-image: ...; background-size: cover; background-position: center; - To make
<img>keep its aspect ratio despite its dimensions:width: 100px; height: 100px; object-fit: cover; /* Image is clipped along its width. */ contain; /* Image changes its dimension to fully fit inside the dimensions. */
Misc
- You can combine different units in a
calcexpression, for example:height: calc(100vh - 100px).
display: grid
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr))