CSS Formatter & Minifier

Format unindented stylesheets into structured CSS trees, or minify production stylesheets by stripping comments, whitespace runs, and redundant unit declarations.

Options
Indent:
Input
Lines28
Size445 B
Beautified
.card {
  padding: 0px 16px 0px 16px;
  color: #ffffff;
  background-color: #667eea;
  border-radius: 8px;
  margin: 0em;
}
.card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  opacity: 0.9;
}
h1, h2 {
  font-weight: bold;
  line-height: 1.5;
  margin-top: 0px;
}
@media screen and (max-width: 600px) {
  .card {
    padding: 0px 12px;
    border-radius: 6px;
  }
}
Beautified in <1ms
Output23 lines · 369 B · 5 rules · 12 decls

Removed 2 comments.

All formatting runs 100% locally in your browser — your CSS never leaves your device. Supports CSS, SCSS and Less.

Operation Guide

Step 1

Load Stylesheet

Paste CSS, SCSS, or Less into the input pane, or drop local .css, .scss, or .less files directly into the editor.

Step 2

Configure Rules

Select Beautify (2 spaces, 4 spaces, or tabs) or Minify (comment stripping, zero-unit collapse, and adjacent selector merging).

Step 3

Review & Export

Inspect live byte counts, savings percentage, and highlighted output, then copy to clipboard or download the processed file.

Transformation Examples

1. Minified One-Liner → Structured, Indented Block

Input · Raw Minified String

.card{display:flex;flex-direction:column;padding:16px;background:#fff;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.08)}

Output · Beautify (2 Spaces)

.card {
  display: flex;
  flex-direction: column;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, .08);
}

2. Comment Stripping & Value Optimization

Input · Verbose Comments & Long Values

/* Component header styling */
.header-nav {
  margin: 0px 0px 24px 0px;
  color: #ffffff;
  opacity: 0.80;
  background-image: url("icons/nav-arrow.svg");
}

Output · Minified (Zero-Units Stripped & Unquoted URL)

.header-nav{margin:0;color:#fff;opacity:.8;background-image:url(icons/nav-arrow.svg)}

3. Adjacent Duplicate Selector Merging & Cascade Overrides

Input · Scattered Adjacent Rules

.btn-primary {
  padding: 8px 16px;
  color: #ffffff;
  font-weight: 500;
}
.btn-primary {
  color: #f8fafc;
  border-radius: 6px;
}

Output · Merged Single Rule (Last Value Preserved)

.btn-primary{padding:8px 16px;color:#f8fafc;font-weight:500;border-radius:6px}

4. Nested SCSS / Less Hierarchy Preservation

Input · Preprocessor Nesting & Media Query

// SCSS nesting with media breakpoint
.card {
  padding: 16px;
  & > .title {
    font-size: 1.25rem;
    color: #1e293b;
  }
  @media (max-width: 640px) {
    padding: 12px;
  }
}

Output · Minified with Nesting Hierarchy Intact

.card{padding:16px;& > .title{font-size:1.25rem;color:#1e293b}@media (max-width:640px){padding:12px}}

Processing Rules & Configuration Reference

SettingApplicable ModeMechanism & Safety Boundary
Indentation WidthBeautifyApplies 2 spaces, 4 spaces, or physical tabs per nesting level. Depth increments on opening braces ({) and decrements on closing braces (}).
Remove CommentsBeautify & MinifyStrips standard /* ... */ comments and SCSS line comments (//) while protecting protocols in url(https://...) and quoted string literals.
Sort DeclarationsBeautify & MinifyOrders property declarations alphabetically (A–Z) within each rule block. Preserves declaration values and !important flags without crossing block boundaries.
Sort SelectorsBeautify & MinifyReorders top-level rule blocks alphabetically by selector name. Modifies source order in the cascade; verify multi-class priority before production deployment.
Merge Duplicate SelectorsMinify (Advanced)Merges strictly adjacent rule blocks with identical selectors. Resolves conflicting properties by keeping the last declaration unless an earlier declaration carries !important.
Optimize ValuesMinifyConverts zero lengths (0px, 0rem, 0% → 0), shortens hex colors (#ffffff → #fff), drops leading zeros (0.5 → .5), and removes quotes from safe URIs.

CSS Lexical Parsing & AST Transformation Pipeline

Cascading Style Sheets cannot be safely formatted or compressed using global regular expressions alone. Unescaped quotes inside content: "/* comment */", semicolon delimiters inside inline base64 data:image/... URIs, and mathematical operators inside calc() require structured token boundary isolation. This engine processes styles through four discrete phases:

Phase 1

Literal Protection

Extracts single- and double-quoted strings and comment blocks, swapping them for unique sentinel placeholders before any whitespace manipulation or character stripping begins.

Phase 2

Bracket Balancing

Scans curly braces while tracking parenthesis depth (depth = 0), preventing nested functions like rgb() or clamp() from being prematurely parsed as statement delimiters.

Phase 3

AST Tree Walk

Separates rule blocks, at-rules (@media, @keyframes, @supports), and raw declarations. Applies indentation depth in beautify mode or strips redundant syntax in minify mode.

Phase 4

Payload Restoration

Rehydrates protected string literals and preserved comments byte-for-byte into their placeholder positions, guaranteeing zero corruption of generated font names or background paths.

Cascade Order, Specificity & Adjacency Merging Mechanics

Under the CSS Cascading and Inheritance Level 4 specification, declaration resolution depends on four primary criteria: origin, importance, specificity, and source order. Arbitrary selector deduplication that ignores source sequence breaks layout fidelity:

The Adjacency Constraint

Non-adjacent blocks sharing the same selector cannot be blindly merged if intermediate rules possess overlapping specificity. If .btn { color: red; } is followed by .header .btn { color: blue; } and later .btn { color: green; }, pulling the second .btn upward alters specificity resolution. Therefore, safe merging only operates across strictly contiguous sibling blocks.

// Adjacent (Safe to Merge):
.box { margin: 0; } .box { padding: 10px; } → .box { margin:0; padding:10px; }
// Interleaved (Unsafe):
.box { ... } .nav .box { ... } .box { ... } → Merging breaks cascade

Declaration Conflict & !important Handling

When combining identical adjacent blocks, duplicate properties are resolved according to standard CSS precedence: normal declarations are overwritten by later normal declarations. However, an earlier declaration with an !important annotation overrides subsequent normal declarations, preserving intended developer overrides.

// Input:
.card { color: red !important; } .card { color: blue; }
// Resolved:
.card { color: red !important; } → !important wins over later normal value

W3C Value Optimization & Redundant Unit Rules

Not all CSS values can be reduced equally. The W3C CSS Values and Units specification outlines strict rules governing when units are optional and when they are required by browser parsing engines:

Value CategoryOriginal SyntaxOptimized SyntaxSpecification Boundary & Constraints
Length Units (<length>)0px, 0rem, 0em, 0vh, 0%0CSS allows unitless 0 for all length values (e.g. margin: 0px 10px 0px 10px → margin:0 10px 0 10px), removing unnecessary unit suffixes.
Time & Frequency Units0s, 0ms, 0HzPreserved (0s)In transition-duration and animation-delay, unitless 0 is rejected by modern browsers; the unit identifier (s or ms) is strictly mandatory.
Hexadecimal Colors#ffffff, #00aa00#fff, #0a0When each R, G, and B channel consists of duplicate nibbles (R1==R2 && G1==G2 && B1==B2), 6-digit hex values compress into 3-character notation without loss of precision.
Floating Decimal Points0.75, 0.5, 0.125.75, .5, .125Leading zero digits preceding decimal fractions carry no numerical significance and are safely dropped across opacity, scale, and line-height values.
URI Quotation Marksurl("path/icon.svg")url(path/icon.svg)Quotes are optional in CSS url() unless the target URI contains whitespace, quotation marks, or parenthesis characters.

Render-Blocking CSSOM & Core Web Vitals Optimization

HTML documents can be rendered incrementally, but CSS is fundamentally render-blocking: the browser cannot display painted content until it downloads and processes all linked stylesheets to construct the CSS Object Model (CSSOM). Stylesheet footprint directly controls Core Web Vitals milestones:

First Contentful Paint (FCP)

The browser's layout engine delays painting until all <link rel="stylesheet"> tags resolve. Minified CSS fits into fewer initial TCP packets (within the standard 14 KB initial congestion window), advancing FCP by dozens of milliseconds.

Largest Contentful Paint (LCP)

When hero images or primary heading typography depend on external styles, blocking CSS directly holds back the LCP timestamp. Smaller stylesheets clear the render pipeline faster, allowing hero elements to paint sooner.

Cumulative Layout Shift (CLS)

Inlining minified critical above-the-fold CSS directly inside a <style> block prevents Flash of Unstyled Content (FOUC), eliminating sudden geometric re-layouts when external stylesheets arrive asynchronously.

Minification vs Wire Compression (Gzip / Brotli Synergy)

Developers often assume that enabling server-side Brotli or Gzip eliminates the need for source minification. In practice, minification and wire compression address different performance constraints and yield compounding benefits:

Client-Side Memory Budget

Gzip and Brotli compress bytes only while in transit over the network. Once received, the browser's HTTP client decompresses the file back to its uncompressed byte size before passing it to the CSS parser, directly consuming device RAM.

CSSOM Tokenization Cost

Every comment character, blank line, and extra space must be scanned and evaluated by the browser's lexer. Minified CSS minimizes string tokenization overhead, reducing CPU execution times on constrained mobile chipsets.

Dictionary Entropy Reduction

Brotli's sliding-window LZ77 algorithm searches for recurring byte patterns. Removing non-repetitive developer comments and erratic indentation stops dictionary slots from being wasted, resulting in 5–15% smaller compressed transfer payloads.

Target Use Cases in Production Workflows

Debugging Production Bundles

Expand minified single-line vendor stylesheets into readable, indented trees with clear property declarations for browser inspection and local testing.

Pre-Deploy Asset Compression

Strip developer notes, redundant zero units, and formatting whitespace before deploying stylesheets to static hosting providers or CDN edge nodes.

Critical CSS Inlining

Compress above-the-fold styling for direct injection into server-side rendered (SSR) <style> tags to eliminate render-blocking HTTP round trips.

Design System Normalization

Re-sort property declarations alphabetically across shared component libraries to enforce code consistency and streamline pull request diff reviews.

CSS-in-JS & Preprocessor Cleanup

Sanitize verbose selector patterns, trailing semicolons, and irregular whitespace generated by Sass, Less, or styled-components compilation pipelines.

HTML Email Style Budgeting

Compress embedded CSS rules in transactional email templates to prevent message clipping past the strict 102 KB Gmail message ceiling.

Frequently Asked Questions

What is the difference between CSS Beautify (formatting) and CSS Minify (compression)?

CSS Beautify expands minified or unformatted stylesheets by inserting consistent indentation (2 spaces, 4 spaces, or tabs) and line breaks—one declaration per line—making code human-readable and easy to debug. CSS Minify performs the reverse: it strips comments, collapses redundant whitespace, removes optional trailing semicolons, and optimizes zero units to generate the smallest possible stylesheet payload for production delivery.

Will formatting or minifying CSS break styles, animations, or custom properties?

No. Safe CSS minification protects literal strings inside quotes (such as font names and content: "..." properties), data URIs, CSS variables (--custom-prop), @keyframes animation stops, and @media queries using delimiter isolation. Only purely cosmetic whitespace, non-functional comments, and redundant unit identifiers (like 0px to 0) are eliminated.

What exact transforms does the CSS minifier execute to reduce byte size?

The engine strips /* ... */ block comments and SCSS // line comments, collapses whitespace around braces and colons, drops trailing semicolons before closing braces, converts zero lengths (0px, 0rem, 0% to 0), shortens 6-character hex colors (#ffffff to #fff), drops leading zeros in decimals (0.5 to .5), and unquotes safe URIs in url() declarations.

Why does CSS strictly require whitespace around operators inside calc() expressions?

Per the W3C CSS Values and Units Level 4 specification, the addition (+) and subtraction (-) operators inside calc(), min(), max(), and clamp() must have surrounding spaces (e.g. calc(100% - 24px)). Without spaces, -24px is tokenized as a negative length value rather than an operator, causing the browser to reject the declaration as invalid syntax. Multiplication (*) and division (/) do not strictly require spaces, but keeping them maintains cross-engine consistency.

How does "Merge duplicate selectors" work, and when is it safe to use?

The merge algorithm combines strictly contiguous rule blocks that share the exact same selector string. When conflicting property declarations appear, subsequent declarations overwrite earlier ones following standard cascade order, while preserving !important flags. Restricting merges to adjacent blocks prevents disrupting the specificity precedence of interleaved selectors.

Why can sorting selectors (sortSelectors) inadvertently alter visual rendering?

In CSS cascade rules, when two selectors have identical specificity (such as .primary-btn and .disabled-btn applied to the same HTML element), the rule declared later in stylesheet source order takes precedence. Alphabetical selector sorting modifies source sequence, which can flip the cascade winner and cause visual regressions. Use selector sorting for auditing structured token libraries rather than arbitrary multi-class stylesheets.

Does this formatter preserve nested rules from SCSS, Less, or the CSS Nesting Module?

Yes. The recursive AST parser treats nested blocks (&:hover, & > .child) and media query wrappers as hierarchical rule nodes rather than flattening them. Indentation scales proportionally in beautify mode, and minification compresses inner tokens while keeping nesting hierarchy intact so the output remains valid for preprocessors or native CSS nesting engines.

Why is CSS minification still necessary when Brotli or Gzip compression is enabled?

HTTP wire compression reduces transfer size over the network, but the browser must decompress the stream back to its uncompressed byte volume in memory before tokenizing rules into the CSSOM. Minifying CSS lowers memory consumption and CPU execution time on mobile devices. Furthermore, stripping comments and formatting noise lowers dictionary entropy, allowing Brotli and Gzip to achieve 5–15% higher compression ratios.

How does reducing CSS payload size directly improve Core Web Vitals (FCP, LCP, CLS)?

External stylesheets are render-blocking resources: the browser suspends First Contentful Paint (FCP) and Largest Contentful Paint (LCP) until all linked styles in the document head are downloaded and parsed. Smaller CSS bundles download in fewer TCP round trips, unblocking the critical rendering path. Additionally, inlining minified critical styles prevents Flash of Unstyled Content (FOUC), stabilizing Cumulative Layout Shift (CLS).