CSS 3 cheatsheet
CSS 3: Positioning, effects and animation
10 common CSS 3 tasks.
Stick an element while scrolling
Keep a header at the top while its container scrolls.
.header {
position: sticky;
top: 0;
}
Cover the parent
Stretch an absolutely positioned child over its positioned parent.
.overlay {
position: absolute;
inset: 0;
}
Crop an image to fit its box
Fill a box with an image without distorting it.
img {
width: 100%;
height: 200px;
object-fit: cover;
}
Truncate text with an ellipsis
Cut off long single-line text with three dots.
.title {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Limit text to a number of lines
Show at most three lines, then an ellipsis.
.excerpt {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
Animate a change smoothly
Fade the background when the user hovers.
.button {
transition: background-color 0.2s ease;
}
.button:hover {
background-color: #115e59;
}
Create an animation
Define keyframes and apply them.
@keyframes fade-in {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: none; }
}
.card {
animation: fade-in 0.3s ease-out;
}
Snap to items while scrolling
Make a horizontal carousel stop at each item.
.carousel {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
}
.carousel > * {
scroll-snap-align: start;
}
Hide text visually but keep it for screen readers
Hide an element from view but keep it available to assistive technology.
.sr-only {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
Style keyboard focus
Show a clear outline only when navigating with the keyboard.
:focus-visible {
outline: 3px solid #0f766e;
outline-offset: 2px;
}