8 releases (5 breaking)

0.6.2 Jul 22, 2022
0.6.1 Jul 14, 2022
0.6.0 May 14, 2022
0.5.0 Jun 12, 2021
0.1.0 Dec 13, 2020

#56 in Web programming

Download history 18472/week @ 2024-03-14 20600/week @ 2024-03-21 17548/week @ 2024-03-28 18226/week @ 2024-04-04 17163/week @ 2024-04-11 19497/week @ 2024-04-18 17760/week @ 2024-04-25 19502/week @ 2024-05-02 17785/week @ 2024-05-09 17730/week @ 2024-05-16 15103/week @ 2024-05-23 18240/week @ 2024-05-30 16572/week @ 2024-06-06 18221/week @ 2024-06-13 17629/week @ 2024-06-20 14036/week @ 2024-06-27

69,571 downloads per month
Used in 110 crates (29 directly)

MIT/Apache

57KB
1K SLoC

Rust CSS Color Parser Library

License crates.io Documentation Build Status codecov Total Downloads

Rust library for parsing CSS color string as defined in the W3C's CSS Color Module Level 4.

Supported Color Format

  • Named colors
  • RGB hexadecimal (with and without # prefix)
    • Short format #rgb
    • Short format with alpha #rgba
    • Long format #rrggbb
    • Long format with alpha #rrggbbaa
  • rgb() and rgba()
  • hsl() and hsla()
  • hwb()
  • lab()
  • lch()
  • hwba(), hsv(), hsva() - not in CSS standard.

Example Color Format

Click to expand!
transparent
gold
rebeccapurple
lime
#0f0
#0f0f
#00ff00
#00ff00ff
rgb(0,255,0)
rgb(0% 100% 0%)
rgb(0 255 0 / 100%)
rgba(0,255,0,1)
hsl(120,100%,50%)
hsl(120deg 100% 50%)
hsl(-240 100% 50%)
hsl(-240deg 100% 50%)
hsl(0.3333turn 100% 50%)
hsl(133.333grad 100% 50%)
hsl(2.0944rad 100% 50%)
hsla(120,100%,50%,100%)
hwb(120 0% 0%)
hwb(480deg 0% 0% / 100%)
hsv(120,100%,100%)
hsv(120deg 100% 100% / 100%)

Usage

Add this to your Cargo.toml

csscolorparser = "0.6.2"

Examples

Using csscolorparser::parse() function.

let c = csscolorparser::parse("rgb(100%,0%,0%)")?;

assert_eq!(c.to_array(), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(c.to_rgba8(), [255, 0, 0, 255]);
assert_eq!(c.to_hex_string(), "#ff0000");
assert_eq!(c.to_rgb_string(), "rgb(255,0,0)");

Using parse() method on &str.

use csscolorparser::Color;

let c = "#ff00007f".parse::<Color>()?;

assert_eq!(c.to_rgba8(), [255, 0, 0, 127]);
assert_eq!(c.to_hex_string(), "#ff00007f");

Default Feature

  • named-colors: Enables parsing from named colors. Requires phf. Can be disabled using default-features = false.

Optional Features

  • lab: Enables parsing lab() and lch() color format.
  • rust-rgb: Enables converting from rgb crate types into Color.
  • cint: Enables converting cint crate types to and from Color.
  • serde: Enables serializing (into HEX string) and deserializing (from any supported string color format) using serde framework.

Similar Projects

Dependencies

~0–275KB