Learn R Programming

colourspace (version 0.0.1)

from_css: Parse CSS color strings

Description

Parse CSS color function strings (e.g., oklch(...), rgb(...), hsl(...)) or hex colors and convert them to a target color space. Automatically detects the input format from the CSS syntax.

Usage

from_css(
  css,
  to = "hex",
  fallback = TRUE,
  distance = c("lab", "oklch", "rgb", "hsl")
)

Value

For scalar inputs, a named numeric vector (or hex string or colour name). For vectorised inputs, a matrix with one row per input colour or a character vector for to = "name" or to = "hex".

Arguments

css

Character vector of CSS color strings. Supported formats:

  • oklch(L C H), oklch(L C H / A)

  • oklab(L A B), oklab(L A B / A)

  • rgb(R G B), rgb(R G B / A), rgb(R, G, B), rgb(R, G, B, A)

  • rgba(R, G, B, A)

  • hsl(H S L), hsl(H S L / A), hsl(H, S, L), hsl(H, S, L, A)

  • hsla(H, S, L, A)

  • Hex colors: #rgb, #rrggbb, #rrggbbaa

to

Target colour space. One of "hex" (default), "rgb", "hsl", "oklab", "oklch", or "name".

fallback

Behaviour when mapping to = "name" and no exact hex/name match is found. TRUE (default) returns the closest named colour using distance (a warning is issued). FALSE returns NA for unknown colours.

distance

Distance metric for nearest-colour fallback: one of "lab" (default), "oklch", "rgb", or "hsl".

Details

Both modern (space-separated) and legacy (comma-separated) CSS notations are supported:

  • Modern: rgb(255 0 0), rgb(255 0 0 / 0.5)

  • Legacy: rgb(255, 0, 0), rgb(255, 0, 0, 0.5)

  • Legacy with explicit alpha: rgba(255, 0, 0, 0.5)

Alpha channels are currently parsed but ignored during conversion.

Examples

Run this code
# Parse OKLCH CSS string to hex
from_css("oklch(62.792% 0.258 29.221 / 1)")

# Parse RGB CSS string (modern & legacy)
from_css("rgb(255 0 0 / 1)", to = "oklch")
from_css("rgb(255, 0, 0)", to = "hex")

# Parse HSL CSS string
from_css("hsl(210 50% 40% / 1)", to = "rgb")

# Also works with hex colors
from_css("#ff0000", to = "oklch")

# Vectorized
from_css(c("oklch(62.792% 0.258 29.221 / 1)", "rgb(0 255 0 / 1)"))

Run the code above in your browser using DataLab