What Is a CSS Snippet?
Direct answer: A CSS snippet is a small, self-contained block of CSS code that solves one specific styling problem — centering a div, creating a text gradient, building a card hover effect, or setting up a responsive grid. Snippets are meant to be copied, pasted, and adapted rather than written from scratch every time you encounter the same pattern.
Every frontend developer, regardless of experience level, builds up a mental library of CSS patterns they reach for repeatedly. Centering things, making grids responsive, adding smooth transitions, styling scrollbars — these same patterns appear in every project. CSS snippets formalise that mental library into something shareable and searchable.
The difference between a good snippet and a bad one comes down to three things: correctness (does it work across browsers?), explainability (do you understand what each property does?), and adaptability (can you modify it for your context?). This guide provides all three.
Browse all curated snippets in the CSS Snippets library on CSSAwwwards, or submit your own patterns to the community collection.
Centering Snippets
Centering in CSS is the most-searched layout problem in frontend development. There is no single correct answer — the right approach depends on whether you need horizontal centering, vertical centering, or both, and whether the container has a fixed or dynamic size. Here are the definitive modern approaches.
Flexbox Perfect Centre
snippet
.container {
display: flex;
justify-content: center;
align-items: center;
}
/* Full-viewport version */
.full-page-centre {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}justify-content: center centres along the main axis (horizontal by default). align-items: center centres along the cross axis (vertical). Together they create a perfect two-dimensional centre for any child element, regardless of size. Use min-height: 100vh when you want to fill the full viewport — for loading screens, hero sections, or modals.
CSS Grid Perfect Centre
snippet
.container {
display: grid;
place-items: center;
/* or: place-items: center center; */
}
/* Full-viewport grid centre */
.full-page-centre {
display: grid;
place-items: center;
min-height: 100vh;
}place-items is a shorthand for align-items and justify-items. It is the most concise way to centre anything in CSS — two properties collapsed into one. This is often preferred over the Flexbox approach for its brevity, particularly when you only have a single child element to centre.
Horizontal Centre with Margin Auto
snippet
.centred-block {
max-width: 780px;
margin-left: auto;
margin-right: auto;
/* shorthand: margin: 0 auto; */
}
/* Modern logical properties version */
.centred-block {
max-width: 780px;
margin-inline: auto;
}The classic approach for centering block-level content horizontally. Works for any element that is narrower than its container. margin-inline: auto is the modern logical-property equivalent — it respects writing direction (LTR/RTL) automatically, making it better for internationalised designs.
Absolute Positioning Centre
snippet
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}Use this when you need to centre an element over a positioned parent — like a label over a map pin, or a close button inside a card. The transform: translate(-50%, -50%) offsets the element back by half its own width and height, compensating for the fact that top: 50% and left: 50%position the element's top-left corner, not its centre.
Layout Snippets — Grid & Flexbox
Layout snippets solve the structural challenges of arranging content across a page or component. These are the patterns you will reach for on nearly every project.
Responsive Auto-Fill Card Grid
snippet
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 24px;
}This is the most powerful responsive grid pattern in CSS. auto-fill creates as many columns as will fit. minmax(280px, 1fr) sets a minimum column width of 280px and lets it grow to fill remaining space. The result: a grid that reflows from one column on mobile to two, three, or more on wider screens — with zero media queries. Adjust 280px to suit your card design.
Holy Grail Layout (Header / Sidebar / Main / Footer)
snippet
.page {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 240px 1fr;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
@media (max-width: 768px) {
.page {
grid-template-areas:
"header"
"main"
"sidebar"
"footer";
grid-template-columns: 1fr;
}
}Named grid areas make complex layouts readable and self-documenting. The template ASCII art in grid-template-areas directly mirrors the visual layout. On mobile, the media query reshuffles the template to a single-column flow — sidebar moves below main content, which is the correct reading-order pattern for mobile screens.
Flexbox Sticky Footer
snippet
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1; /* grows to fill available space */
}This two-rule pattern pushes the footer to the bottom of the viewport on short pages, without using absolute or fixed positioning. flex: 1 on main makes it expand to consume all available vertical space between the header and footer. Works with any number of intermediate sections between header and footer.
Sidebar + Main Two-Column Layout
snippet
.layout {
display: grid;
grid-template-columns: 220px 1fr;
gap: 40px;
align-items: start;
}
@media (max-width: 768px) {
.layout {
grid-template-columns: 1fr;
}
}A clean two-column layout where the sidebar has a fixed width and the main content area fills the rest. align-items: start keeps both columns anchored at the top — without it, the shorter column stretches to match the taller one's height, which is usually not desirable. Add position: sticky; top: 72px; to the sidebar element for a sticky sidebar on long pages.
Dark Mode Snippets
Dark mode is now a baseline user expectation. The cleanest implementation uses CSS custom properties combined with the prefers-color-scheme media query, so the system-level preference is respected automatically without JavaScript.
System Dark Mode with CSS Variables
snippet
:root {
--color-bg: #ffffff;
--color-ink: #111111;
--color-muted: #6b7280;
--color-border: #e5e7eb;
--color-surface: #f9fafb;
--color-accent: #1D9E75;
}
@media (prefers-color-scheme: dark) {
:root {
--color-bg: #0f0f0f;
--color-ink: #f0f0f0;
--color-muted: #9ca3af;
--color-border: #2a2a2a;
--color-surface: #1a1a1a;
}
}
body {
background: var(--color-bg);
color: var(--color-ink);
}Define your entire colour palette as CSS variables in :root. The dark mode override only needs to redefine the variables that change — the rest of your CSS remains unchanged because it references the variables, not hardcoded values. This is the correct architecture for theming: one source of truth per colour token.
JavaScript-Controlled Dark Mode Toggle
snippet
/* CSS */
:root { --color-bg: #fff; --color-ink: #111; }
[data-theme="dark"] { --color-bg: #0f0f0f; --color-ink: #f0f0f0; }
/* JS toggle */
const toggleTheme = () => {
const current = document.documentElement.dataset.theme;
document.documentElement.dataset.theme =
current === "dark" ? "light" : "dark";
};When users need a manual toggle (ignoring system preference), use a data-theme attribute on the root element. The JavaScript flips the attribute, the CSS responds. Store the preference in localStorage and apply it before first render to avoid a flash of the wrong theme.
Glassmorphism & Visual Effects
Glassmorphism creates a frosted-glass visual effect using backdrop-filter: blur(). It works best when the element is positioned over a colourful or photographic background that benefits from the blur.
Glassmorphism Card
snippet
.glass-card {
background: rgba(255, 255, 255, 0.12);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px); /* Safari */
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 16px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
padding: 24px;
}The backdrop-filter property applies a blur to everything behind the element — it does not blur the element's own background. The semi-transparent background lets the blurred content show through, creating the frosted glass look. Always include the -webkit-backdrop-filter prefix for Safari compatibility. Note: backdrop-filter requires hardware acceleration; use sparingly on performance-sensitive pages.
Gradient Text Effect
snippet
.gradient-text {
background: linear-gradient(135deg, #1D9E75, #0ea5e9);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
/* Animated gradient text */
.gradient-text-animated {
background: linear-gradient(270deg, #1D9E75, #0ea5e9, #7c3aed, #1D9E75);
background-size: 300% 300%;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
animation: gradientShift 4s ease infinite;
}
@keyframes gradientShift {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}The gradient text technique works by clipping a background gradient to the text shape. -webkit-background-clip: text clips the background to the text area; -webkit-text-fill-color: transparent makes the text itself transparent so the clipped gradient shows through. Add background-clip: text (without prefix) for non-WebKit browsers.
Animation & Transition Snippets
CSS animations and transitions add life to interfaces without requiring JavaScript. The key principle for performance is to animate only transform and opacity— these properties are handled by the browser's compositor and do not trigger layout recalculation.
Smooth Hover Transition
snippet
.button {
background: #1D9E75;
color: white;
padding: 10px 20px;
border-radius: 6px;
border: none;
cursor: pointer;
transition: background 0.2s ease, transform 0.15s ease, box-shadow 0.2s ease;
}
.button:hover {
background: #178a62;
transform: translateY(-2px);
box-shadow: 0 4px 16px rgba(29, 158, 117, 0.35);
}
.button:active {
transform: translateY(0);
}Always put transition on the element's default state, not the :hover state. If you put it on :hover, the transition only plays when entering hover — the reverse transition (hover to normal) will be instant. The :active state snaps back immediately, giving tactile feedback that the button was pressed.
CSS Loading Spinner
snippet
.spinner {
width: 36px;
height: 36px;
border: 3px solid rgba(29, 158, 117, 0.2);
border-top-color: #1D9E75;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}A pure CSS loading spinner. The trick is making most of the border semi-transparent and one segment (border-top-color) opaque — rotation then creates the illusion of a spinner. Animate only transform: rotate() so the animation runs on the compositor thread without triggering any layout or paint.
Fade-In on Load
snippet
.fade-in {
animation: fadeIn 0.4s ease forwards;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
/* Staggered children */
.list > * {
animation: fadeIn 0.4s ease both;
}
.list > *:nth-child(1) { animation-delay: 0.05s; }
.list > *:nth-child(2) { animation-delay: 0.10s; }
.list > *:nth-child(3) { animation-delay: 0.15s; }
.list > *:nth-child(4) { animation-delay: 0.20s; }Combine opacity with a small translateY offset for a natural-feeling entrance that suggests the element is rising into place. Use animation-fill-mode: both (or the both shorthand keyword) so the element starts in the from state before the animation begins, preventing a flash of the fully-visible element.
Accessibility note: Always wrap motion animations in a @media (prefers-reduced-motion: no-preference) check, or disable them with @media (prefers-reduced-motion: reduce). Users who have enabled reduced motion in their OS settings can experience nausea or seizures from animations.
Typography Snippets
Typography CSS snippets handle the patterns that make text readable, fluid, and visually consistent across devices and screen sizes.
Fluid Typography with clamp()
snippet
/* Scales from 18px at 320px viewport to 28px at 1200px viewport */
h1 {
font-size: clamp(18px, 2.5vw + 12px, 28px);
}
/* Fluid body text: 15px to 18px */
body {
font-size: clamp(15px, 1vw + 12px, 18px);
}
/* Simple clamp for a heading */
.hero-title {
font-size: clamp(28px, 5vw, 56px);
}clamp(min, preferred, max) eliminates most typography media queries. The min and max values are hard limits; the preferred value scales with the viewport. This creates smooth, continuous scaling between breakpoints rather than hard jumps. The formula Xvw + Ypx in the preferred value gives you precise control over the scaling slope.
Text Truncation with Ellipsis
snippet
/* Single line truncation */
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Multi-line clamp (3 lines) */
.line-clamp-3 {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}Single-line truncation requires all three properties — white-space: nowrap prevents line breaks, overflow: hidden clips the overflowing content, and text-overflow: ellipsisadds the “…”. The multi-line version uses the WebKit-prefixed box model — despite the prefix, this technique is supported in all modern browsers and is the only pure CSS way to clamp text to N lines.
Balanced Headline Wrapping
snippet
h1, h2, h3 {
text-wrap: balance;
}
/* For paragraphs: pretty wrapping avoids orphaned words */
p {
text-wrap: pretty;
}text-wrap: balance makes headings wrap so each line has approximately equal length — eliminating the typographically ugly single-word final line. It is a 2024 CSS feature with strong modern browser support. text-wrap: pretty applies a similar optimisation to paragraphs without the performance overhead of full balancing.
Utility & Accessibility Snippets
These snippets solve specific, recurring problems that don't fit neatly into other categories — from hiding elements accessibly to creating focus-visible outlines.
Visually Hidden (Screen Reader Only)
snippet
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}This pattern hides content visually while keeping it accessible to screen readers. Do not use display: none or visibility: hidden — those remove elements from the accessibility tree entirely. Use .sr-only for skip links, descriptive labels for icon-only buttons, and table summaries that sighted users can infer from context.
Focus-Visible Outline
snippet
/* Remove default outline for mouse users, keep for keyboard */
:focus:not(:focus-visible) {
outline: none;
}
:focus-visible {
outline: 2px solid var(--color-accent);
outline-offset: 3px;
border-radius: 3px;
}:focus-visible is the modern solution to the long-standing tension between removing ugly focus rings for mouse users and keeping them for keyboard users. It only shows the outline when the browser determines focus was received via keyboard navigation. Never remove :focus-visible outlines — they are essential for keyboard accessibility.
Smooth Scroll Behaviour
snippet
html {
scroll-behavior: smooth;
}
/* Respect reduced motion preference */
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
}One property enables smooth scrolling for all anchor links on the page. Always pair it with the reduced-motion media query override — animated scrolling can trigger vestibular disorders in users who have opted into reduced motion. The fallback sets scroll behaviour back to instant.
Custom Scrollbar Snippets
Custom scrollbar styles let you match the scrollbar to your design system. The WebKit approach works in Chrome, Edge, and Safari; the standard scrollbar-width and scrollbar-color properties work in Firefox.
Thin Styled Scrollbar
snippet
/* Works in Chrome, Edge, Safari */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: rgba(100, 100, 100, 0.4);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(100, 100, 100, 0.7);
}
/* Firefox */
* {
scrollbar-width: thin;
scrollbar-color: rgba(100,100,100,0.4) transparent;
}Apply to :root or body for the main page scrollbar, or to a specific container for a localised scrollable area. The combination of both the WebKit pseudo-element approach and the standard properties achieves cross-browser consistency in all major browsers.
How to Use CSS Snippets Effectively
Scope snippets to specific selectors
Apply snippets to a class or component rather than to generic HTML elements. A snippet that targets .card-grid is safer than one targeting div or *. This prevents cascade conflicts with other parts of your project.
Replace hardcoded values with CSS variables
When you adapt a snippet for your project, replace colours, sizes, and timing values with your design system's CSS custom properties. This makes snippets themeable and keeps your codebase consistent — instead of the same hex code appearing ten times across ten snippets.
Test at multiple viewport widths
Resize your browser before closing DevTools. Many snippets that look perfect at desktop width break at 375px. The responsive grid and centering snippets in this guide are designed to work at all widths, but always verify in context.
Remove snippets you are not using
CSS bloat is real. Every KB of unloaded CSS adds to Time to First Byte and blocks rendering. Audit your stylesheets periodically with the DevTools Coverage tab, or use a build-time tool like PurgeCSS to eliminate dead rules before shipping.
For more ready-to-use patterns, visit the CSS Snippets library. If you have a pattern worth sharing, submit it to the community collection.
FAQ
- What is a CSS snippet?
- A CSS snippet is a small, self-contained block of CSS code that solves one specific styling problem — centering a div, creating a gradient effect, building a card grid. Snippets are designed to be copied, pasted, and adapted, not written from scratch each time.
- How do I center a div with CSS in 2025?
- The cleanest approach: set the parent to
display: flex; justify-content: center; align-items: center;. Alternatively,display: grid; place-items: center;achieves the same in fewer properties. For horizontal-only centering of block elements,margin-inline: auto;paired with amax-widthis the standard approach. - Are CSS snippets bad for performance?
- Not inherently — individual snippets are tiny. The risk is accumulating many unused snippets in your CSS bundle. Audit with DevTools Coverage and use PurgeCSS or similar build-time tools to remove unused rules before shipping.
- Where can I find free CSS snippets?
- CSSAwwwards.com/css-snippets is a curated, explained library. Other good sources include CSS-Tricks, MDN Web Docs, and CodePen. Community submissions on CSSAwwwards surface patterns from working frontend developers.
- How do I submit a CSS snippet?
- Visit CSSAwwwards.com/css-snippets/submit. Approved snippets are published with credit to your name and a link to your website. The review typically takes under 7 days.
Conclusion
The CSS snippets in this guide cover the patterns that appear in nearly every frontend project. Bookmark the centering approaches for the next time a designer hands you a component that needs to be vertically and horizontally centred. Keep the responsive card grid in your toolkit for any listing page. Use the dark mode variable architecture as the foundation of every new design system you build.
The difference between a developer who writes the same CSS from scratch every project and one who has a reliable snippet library is not talent — it is tooling. Snippets are tools. Build yours deliberately, understand each one, and trim the ones you never reach for.
Explore the full CSS Snippets library for community-contributed patterns, or submit your own snippet and get credited in the library. For CSS tools to help generate, visualise, and debug your styles, browse the CSS Tools directory.
Frontend developer and curator at CSSAwwwards. Writes about CSS layout, design systems, and developer tooling.
