跳到正文
DEV Community· orzi zhou·· 4 小時前AI 評分50

如何用 Vanilla JS 解析 OKLCH、處理子像素網格並精簡 Tailwind CSS v4

Parsing OKLCH, Sub-Pixel Grids, and Zero-Bloat Tailwind v4 in Vanilla JS

AI 導讀

orzi zhou 分享一套零依賴 Vanilla JS 方法,將現代 CSS 樣式編譯成精簡的 Tailwind CSS v4 類別。方法可解析多種 CSS 顏色格式,將 RGB 與 21 組 Tailwind v4 標準調色盤以 <= 4 容差匹配,並把相差不超過 2px 的網格軌道視作相等。作者亦提供兩款免費、全程在瀏覽器端運行的工具,並將同一引擎封裝成 SpecQuill 側邊欄擴充功能。

正文

Skip to content

Image 1: DEV Community

Powered by Algolia

Log inCreate account

DEV Community

Image 20 Add reaction

Image 30 Like Image 40 Unicorn Image 50 Exploding Head Image 60 Raised Hands Image 70 Fire

0 Jump to Comments 0 Save Boost

Pick as gem

Copy link

Copied to Clipboard

Share to XShare to LinkedInShare to FacebookShare to Mastodon

Share Post via...Report Abuse

Image 8: Cover image for Parsing OKLCH, Sub-Pixel Grids, and Zero-Bloat Tailwind v4 in Vanilla JS

Image 9: orzi zhou

orzi zhou Posted on Nov 25

Parsing OKLCH, Sub-Pixel Grids, and Zero-Bloat Tailwind v4 in Vanilla JS

#tailwindcss#javascript#css#webdev

If you inspect a modern webpage built with Tailwind CSS v4, shadcn/ui, or Linear using window.getComputedStyle(), classic CSS pickers break in surprisingly ugly ways:

  1. CSS Color 4 everywhere: Chromium now returns oklch(), oklab(), and color(display-p3 ...) instead of rgb(). Any regex looking for rgba?() silently drops colors and breaks WCAG contrast checks.
  2. Computed-style bloat: Dumping raw computed styles spits out dozens of browser defaults (position: static, opacity: 1, flex properties on block containers, and 4 separate padding-* / border-* declarations).
  3. Sub-pixel grid tracks: getComputedStyle(el).gridTemplateColumns resolves repeat(3, minmax(0, 1fr)) into something like 312.33px 312.34px 312.33px. Naive string equality misses grid-cols-3 by 0.01px.
  4. Translucent dark glass cards: Checking contrast against a card with background-color: rgba(255, 255, 255, 0.08) without alpha-compositing up the ancestor stack thinks the card is on pure white.

Here is how I solved these four problems in zero-dependency vanilla JS — plus two free client-side tools you can test right in your browser.


1. Parsing oklch(), oklab(), and display-p3 + Palette Snapping

Tailwind CSS v4 defines its palette in OKLCH. When you convert OKLCH back to 8-bit sRGB using Bjorn Ottosson's inverse OKLab matrix, rounding can shift a channel by ±1 (for example, #18181b might round to #18181c).

To avoid emitting ugly arbitrary hex classes (bg-[#18181c]), we:

  • Decode oklch(), oklab(), hsl(), color(srgb ...), and color(display-p3 ...) into { r, g, b, a }.
  • Match the opaque RGB against all 21 standard Tailwind v4 color palettes (slate, gray, zinc, neutral, indigo, violet, rose, etc.) with a tight Euclidean RGB snap tolerance (<= 4).
  • Emit clean Tailwind v4 alpha modifiers when a < 1 (e.g. text-white/80, border-white/10).
function matchTailwindPaletteToken(rgba) {
  const opaqueHex = rgbaToHex({ r: rgba.r, g: rgba.g, b: rgba.b, a: 1 });
  if (EXACT_COLORS.has(opaqueHex)) return EXACT_COLORS.get(opaqueHex);

  let best = null;
  let bestDist = 17; // Euclidean distance <= 4
  for (const entry of PALETTE_RGB_ENTRIES) {
    const dr = rgba.r - entry.r;
    const dg = rgba.g - entry.g;
    const db = rgba.b - entry.b;
    const d2 = dr * dr + dg * dg + db * db;
    if (d2 < bestDist) {
      bestDist = d2;
      best = entry.token;
    }
  }
  return best;
}

2. Sub-Pixel Grid Track Tolerance & Zero-Bloat Style Diffing

Instead of blindly dumping every computed property, we diff each node against a clean same-tag baseline inside a hidden sandboxed iframe, drop flex/grid-only properties when display isn't flex/grid, collapse 4-side shorthands (padding, margin, border-radius), and treat grid tracks within 2px of each other as equal columns:

const cols = declarations['grid-template-columns'].trim().split(/\s+/);
const pxCols = cols.map(parsePx);
const allEqualTracks = cols.length >= 2 && cols.length <= 12 && (
  cols.every((c) => c === cols[0]) ||
  (pxCols.every((n) => n !== null && n > 0) &&
   Math.max(...pxCols) - Math.min(...pxCols) <= 2)
);
if (allEqualTracks) classes.push(`grid-cols-${cols.length}`);

We also compile modern visual rules that older converters drop:

  • backdrop-filter: blur(12px) ->backdrop-blur-md
  • linear-gradient(...) / radial-gradient(...) ->bg-[linear-gradient(...)]
  • background-clip: text ->bg-clip-text
  • text-overflow: ellipsis + overflow: hidden + white-space: nowrap ->truncate
  • Explicit computed width, height, and xmlns on stripped inline <svg> icons so they don't blow up to 100% viewport width when pasted into React JSX.

3. Real Input -> Compiled Tailwind CSS v4 Output

Feed this modern Linear-style dark glass card into the compiler:

.card {
  display: grid;
  grid-template-columns: 312.33px 312.34px 312.33px;
  gap: 24px;
  background-color: oklch(0.21 0.006 285.885);
  color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(12px);
  background-image: linear-gradient(135deg, #2563eb, #7c3aed);
}

Output:

grid gap-6 grid-cols-3 bg-zinc-900 bg-[linear-gradient(135deg,#2563eb,#7c3aed)] text-white/80 border border-white/10 backdrop-blur-md

Try the Free Local Tools (Zero Ads, Zero Sign-Up)

Both web tools run 100% client-side in vanilla JS (full client-side source is public on GitHub at orziz/orzi-apps-site):


Companion Side-Panel Extension: SpecQuill

I also packaged the exact same local engine into a lightweight browser side-panel extension called SpecQuill so you can inspect live webpages without copy-pasting from DevTools:

Image 10: SpecQuill Live UI Inspector & Redlines

Image 11: SpecQuill Tailwind v4, React JSX & AI Prompt Export

  • Hover any element for box dimensions, Alt-key pixel spacing redlines, arrow-key DOM navigation, and multi-layer composited WCAG AA/AAA contrast badges.
  • Export clean HTML/CSS, React JSX + Tailwind v4, full-page OKLCH palettes, inline SVGs, or token-budgeted AI coding specs for Cursor / Claude Code.
  • 100% local processing with least-privilege permissions (no <all_urls> background access).
  • Install Free on Microsoft Edge Add-ons (Chrome Web Store review is currently in progress; v1.1.0 ZIP for Chrome/Brave is available on apps.orzi.me/specquill). Core inspection, clean HTML/CSS, CSS variables, and 3 daily Pro exports are free forever, with an optional $12 one-time lifetime Pro upgrade (no subscription).

If you run into tricky real-world CSS edge cases (weird shorthand orders, color-mix(), complex grid-template-areas, or nested gradients), drop them in the comments and I'll add test coverage to the compiler!

Image 12: profile The DEV TeamPromoted


Image 13: Strands harness

Strands harness is a state-of-the-art, fully assembled agent harness.

Strands harness is a complete, production-ready agent the moment you install it. Shell, file, and web tools, plus context management, memory, sessions, and subagents, are tuned and ready. Run it as a library or from the strands CLI, on any model and any cloud. Every default is yours to change through the open-source Harness SDK.

Get Started with Strands

Read More

Top comments (0)

Subscribe

Image 14: pic

Submit PreviewDismiss

Code of Conduct•Report abuse

Image 15: profile The DEV TeamPromoted


Image 16: Strands harness

Strands harness is a state-of-the-art, fully assembled agent harness.

Strands harness is a complete, production-ready agent the moment you install it. Shell, file, and web tools, plus context management, memory, sessions, and subagents, are tuned and ready. Run it as a library or from the strands CLI, on any model and any cloud. Every default is yours to change through the open-source Harness SDK.

Get Started with Strands

Image 17: Google Cloud Google CloudPromoted

Image 18: Cut Data Warehouse Costs by 54%

Cut Data Warehouse Costs by 54%

Automate the entire data life cycle, from ingestion to AI-driven insights, so you can go from data to AI to action faster on Google Cloud’s data warehouse.

Learn More →

Image 19 orzi zhou

Follow

  • Joined Nov 25, 2026

Trending on DEV Community

Image 20: jaehong kim profile image I Built a Claude Code Plugin Because I Was Becoming a Rubber-Stamp Reviewer #opensource#ai#productivity#programmingImage 21: amananandrai profile image Monuments of India, Part 4: 100 New Monuments, from Harappan Dholavira to the Chenab Rail Bridge #javascript#threejs#webdev#showdevImage 22: Timur Valitov profile image My coding agent says "done". Here's how I make it prove it #ai#opensource#productivity#showdev

Image 23: profile The DEV TeamPromoted


Image 24: Strands harness

Strands harness is a state-of-the-art, fully assembled agent harness.

Strands harness is a complete, production-ready agent the moment you install it. Shell, file, and web tools, plus context management, memory, sessions, and subagents, are tuned and ready. Run it as a library or from the strands CLI, on any model and any cloud. Every default is yours to change through the open-source Harness SDK.

Get Started with Strands

👋 Kindness is contagious


Delve into a trove of insights in this thoughtful post, celebrated by the welcoming DEV Community. Programmers of every stripe are invited to share their viewpoints and enrich our collective expertise.

A simple “thank you” can brighten someone’s day—drop yours in the comments below!

On DEV, exchanging knowledge lightens our path and forges deeper connections. Found this valuable? A quick note of gratitude to the author can make all the difference.

Get Started

DEV Community — A space to discuss and keep up software development and manage your software career

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community © 2016 - 2026.

Image 25: DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log inCreate account

Image 26Image 27Image 28Image 29Image 30

來源:DEV Community · dev.to