units

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 17, 2025 License: MIT Imports: 2 Imported by: 0

README

units

CI Go Reference Go Report Card

A comprehensive, type-safe Go implementation of the CSS Values and Units Module Level 4 specification. Perfect for layout engines, CSS parsers, rendering systems, and any application that needs to work with CSS-style measurements.

Features

  • Complete CSS Unit Coverage: Supports all CSS value types including lengths, angles, time, frequency, resolution, numbers, percentages, and ratios
  • Type-Safe API: Strongly-typed units prevent mixing incompatible measurements
  • Accurate Conversions: Implements CSS spec-compliant conversion algorithms
  • Context-Aware Resolution: Resolves relative units (em, vh, cqw, etc.) using rendering context
  • Zero Dependencies: Pure Go implementation with no external dependencies
  • Well Documented: Extensive godoc comments with references to CSS specifications and MDN docs
  • Fully Tested: Comprehensive test coverage

Installation

go get github.com/SCKelemen/units

Quick Start

package main

import (
    "fmt"
    "github.com/SCKelemen/units"
)

func main() {
    // Create length values
    width := units.Px(400)
    margin := units.Em(1.5)
    height := units.Vh(100)

    // Perform arithmetic operations
    doubled := width.Mul(2)
    fmt.Println(doubled) // 800.00px

    // Convert between absolute units
    inches := units.In(1)
    pixels, _ := inches.ToPx()
    fmt.Println(pixels) // 96.00px

    // Work with angles
    angle := units.Deg(90)
    radians := angle.ToRad()
    fmt.Println(radians) // 1.57rad

    // Use time values
    duration := units.Sec(2.5)
    ms := duration.ToMs()
    fmt.Println(ms) // 2500.00ms

    // Work with ratios
    aspectRatio := units.NewRatio(16, 9)
    height := aspectRatio.ApplyToWidth(1920)
    fmt.Println(height) // 1080
}

Supported Unit Types

Length Units
Absolute Lengths
  • px - Pixels (anchor unit)
  • cm - Centimeters
  • mm - Millimeters
  • Q - Quarter-millimeters
  • in - Inches
  • pt - Points (1/72 inch)
  • pc - Picas (12 points)
Font-Relative Lengths
  • em, rem - Font size (element, root)
  • ex, rex - X-height (element, root)
  • cap, rcap - Cap height (element, root)
  • ch, rch - Character width of "0" (element, root)
  • ic, ric - Ideographic character width (element, root)
  • lh, rlh - Line height (element, root)
Viewport-Relative Lengths
  • vw, vh - Viewport width/height
  • vmin, vmax - Viewport minimum/maximum
  • vb, vi - Viewport block/inline size
  • svw, svh, svb, svi - Small viewport units
  • lvw, lvh, lvb, lvi - Large viewport units
  • dvw, dvh, dvb, dvi - Dynamic viewport units
Container-Relative Lengths
  • cqw, cqh - Container query width/height
  • cqi, cqb - Container query inline/block size
  • cqmin, cqmax - Container query minimum/maximum
Other Value Types
  • Angle: deg, grad, rad, turn
  • Time: s, ms
  • Frequency: Hz, kHz
  • Resolution: dpi, dpcm, dppx
  • Number: Dimensionless values
  • Percentage: Relative percentages
  • Integer: Whole numbers
  • Ratio: Aspect ratios (e.g., 16/9)

Context-Aware Resolution

Resolve relative units to absolute pixels using a rendering context:

// Create a context with rendering information
ctx := &units.Context{
    FontSize:       16.0,
    RootFontSize:   16.0,
    ViewportWidth:  1920.0,
    ViewportHeight: 1080.0,
}

// Resolve relative units
emLength := units.Em(2)
px, _ := emLength.Resolve(ctx)
fmt.Println(px) // 32.00px

vwLength := units.Vw(50)
px, _ = vwLength.Resolve(ctx)
fmt.Println(px) // 960.00px

Unit Conversions

Absolute Length Conversions
// Convert between absolute units
cm := units.Cm(2.54)
px, _ := cm.ToPx()
fmt.Println(px) // 96.00px

// Use generic To() method
inches := units.In(1)
pt, _ := inches.To(units.PT)
fmt.Println(pt) // 72.00pt
Angle Conversions
degrees := units.Deg(180)
radians := degrees.ToRad()
turns := degrees.ToTurns()
fmt.Println(radians) // 3.14rad
fmt.Println(turns)   // 0.50turn
Time Conversions
seconds := units.Sec(2.5)
ms := seconds.ToMs()
fmt.Println(ms) // 2500.00ms

Arithmetic Operations

// Same-unit operations
a := units.Px(100)
b := units.Px(50)
sum := a.Add(b)      // 150.00px
diff := a.Sub(b)     // 50.00px

// Scalar operations
doubled := a.Mul(2)  // 200.00px
half := a.Div(2)     // 50.00px

// Comparisons
isLess := a.LessThan(b)    // false
isGreater := a.GreaterThan(b) // true

Use Cases

  • Layout Engines: Building CSS-compliant layout systems
  • CSS Parsers: Parsing and validating CSS values
  • Design Tools: Creating design systems with precise measurements
  • Rendering Systems: Converting units for different display contexts
  • Animation Systems: Working with time-based animations
  • Media Queries: Handling viewport and container queries
  • Typography: Managing font sizes and line heights

Documentation

Full API documentation is available at pkg.go.dev/github.com/SCKelemen/units.

Each type includes:

  • Constructor functions for easy value creation
  • String() methods for CSS-compatible output
  • Arithmetic operations (Add, Sub, Mul, Div)
  • Comparison operations (LessThan, GreaterThan, Equals)
  • Unit conversion methods
  • Utility methods specific to each type

References

This package implements the following specifications:

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

License

BearWare 1.0 License - see the LICENSE file for details.

Origin

Originally implemented in github.com/SCKelemen/layout and extracted as a standalone package for reuse across layout engines, text rendering, and other CSS-based projects.

Documentation

Overview

Package units implements the CSS Values and Units Module Level 4 specification.

This package provides type-safe value types for CSS units including:

  • Absolute lengths (px, cm, mm, in, pt, pc)
  • Font-relative lengths (em, rem, ch, ex, cap, ic, lh)
  • Viewport-relative lengths (vw, vh, vmin, vmax, vb, vi)
  • Container-relative lengths (cqw, cqh, cqi, cqb, cqmin, cqmax)

Originally implemented in github.com/SCKelemen/layout and extracted as a standalone package for reuse across layout engines, text rendering, and other CSS-based projects.

References:

See also:

Index

Constants

This section is empty.

Variables

View Source
var (
	// Common aspect ratios
	Ratio16x9   = NewRatio(16, 9)    // Standard widescreen
	Ratio16x10  = NewRatio(16, 10)   // Computer display
	Ratio4x3    = NewRatio(4, 3)     // Traditional TV/monitor
	Ratio3x2    = NewRatio(3, 2)     // Classic 35mm film
	Ratio21x9   = NewRatio(21, 9)    // Ultrawide
	Ratio1x1    = NewRatio(1, 1)     // Square
	GoldenRatio = NewRatio(1.618, 1) // Golden ratio (φ)
)

Functions

This section is empty.

Types

type Angle

type Angle struct {
	Value float64
	Unit  AngleUnit
}

Angle represents a CSS angle value.

Angles are used in various CSS properties like transforms, gradients, and animations. CSS supports four angle units: degrees, gradians, radians, and turns.

References:

func Deg

func Deg(value float64) Angle

Deg creates an angle value in degrees.

Example:

angle := units.Deg(45)  // 45 degrees

func Grad

func Grad(value float64) Angle

Grad creates an angle value in gradians.

Example:

angle := units.Grad(200)  // 200 gradians (half circle)

func Rad

func Rad(value float64) Angle

Rad creates an angle value in radians.

Example:

angle := units.Rad(math.Pi)  // π radians (half circle)

func Turns

func Turns(value float64) Angle

Turns creates an angle value in turns.

Example:

angle := units.Turns(0.25)  // 0.25 turns (quarter circle)

func (Angle) Add

func (a Angle) Add(other Angle) Angle

Add adds two angles with the same unit. Panics if the units are different.

func (Angle) Div

func (a Angle) Div(scalar float64) Angle

Div divides the angle by a scalar value.

func (Angle) GreaterThan

func (a Angle) GreaterThan(other Angle) bool

GreaterThan returns true if this angle is greater than the other. Panics if the units are different.

func (Angle) IsZero

func (a Angle) IsZero() bool

IsZero returns true if the angle value is zero.

func (Angle) LessThan

func (a Angle) LessThan(other Angle) bool

LessThan returns true if this angle is less than the other. Panics if the units are different.

func (Angle) Mul

func (a Angle) Mul(scalar float64) Angle

Mul multiplies the angle by a scalar value.

func (Angle) Normalize

func (a Angle) Normalize() Angle

Normalize returns an equivalent angle in the range [0, full circle). This is useful for angles that may have wrapped around multiple times.

Example:

angle := units.Deg(450)
norm := angle.Normalize()  // Returns units.Deg(90)

func (Angle) Raw

func (a Angle) Raw() float64

Raw returns the raw numeric value of the angle.

func (Angle) String

func (a Angle) String() string

String returns the string representation of the angle.

func (Angle) Sub

func (a Angle) Sub(other Angle) Angle

Sub subtracts another angle with the same unit. Panics if the units are different.

func (Angle) To

func (a Angle) To(targetUnit AngleUnit) Angle

To converts the angle to another unit.

Example:

angle := units.Deg(90)
rad := angle.To(units.Radian)  // Returns units.Rad(π/2)

func (Angle) ToDeg

func (a Angle) ToDeg() Angle

ToDeg converts any angle to degrees.

Example:

angle := units.Turns(0.5)
deg := angle.ToDeg()  // Returns units.Deg(180)

func (Angle) ToGrad

func (a Angle) ToGrad() Angle

ToGrad converts any angle to gradians.

Example:

angle := units.Deg(180)
grad := angle.ToGrad()  // Returns units.Grad(200)

func (Angle) ToRad

func (a Angle) ToRad() Angle

ToRad converts any angle to radians.

Example:

angle := units.Deg(180)
rad := angle.ToRad()  // Returns units.Rad(π)

func (Angle) ToTurns

func (a Angle) ToTurns() Angle

ToTurns converts any angle to turns.

Example:

angle := units.Deg(180)
turns := angle.ToTurns()  // Returns units.Turns(0.5)

type AngleUnit

type AngleUnit string

AngleUnit represents a CSS angle unit type.

const (
	Degree  AngleUnit = "deg"  // Degrees: 360deg = full circle
	Gradian AngleUnit = "grad" // Gradians: 400grad = full circle
	Radian  AngleUnit = "rad"  // Radians: 2π rad = full circle
	Turn    AngleUnit = "turn" // Turns: 1turn = full circle
)

CSS angle units per CSS Values Level 4.

Relationship:

  • 1turn = 360deg = 400grad = 2π rad
  • 1deg = 1/360 turn
  • 1grad = 1/400 turn
  • 1rad = 1/(2π) turn

type Context

type Context struct {
	// Font metrics for font-relative units
	FontSize       float64 // For em, ch, ex, etc. (in px)
	RootFontSize   float64 // For rem, rch, rex, etc. (in px)
	XHeight        float64 // For ex (in px)
	CapHeight      float64 // For cap (in px)
	ChWidth        float64 // For ch - width of "0" glyph (in px)
	IcWidth        float64 // For ic - width of "水" glyph (in px)
	LineHeight     float64 // For lh (in px)
	RootLineHeight float64 // For rlh (in px)

	// Viewport dimensions for viewport-relative units
	ViewportWidth  float64 // For vw, vi, etc. (in px)
	ViewportHeight float64 // For vh, vb, etc. (in px)

	// Container dimensions for container-relative units
	ContainerWidth  float64 // For cqw, cqi (in px)
	ContainerHeight float64 // For cqh, cqb (in px)
}

Context provides the necessary information to resolve relative lengths to absolute values.

type Frequency

type Frequency struct {
	Value float64
	Unit  FrequencyUnit
}

Frequency represents a CSS frequency value.

Frequency values are used in CSS for audio properties and other frequency-based features. CSS supports hertz and kilohertz.

References:

func Hz

func Hz(value float64) Frequency

Hz creates a frequency value in hertz.

Example:

freq := units.Hz(440)  // 440 Hz (A4 note)

func KHz

func KHz(value float64) Frequency

KHz creates a frequency value in kilohertz.

Example:

freq := units.KHz(20)  // 20 kHz

func (Frequency) Add

func (f Frequency) Add(other Frequency) Frequency

Add adds two frequency values with the same unit. Panics if the units are different.

func (Frequency) Div

func (f Frequency) Div(scalar float64) Frequency

Div divides the frequency by a scalar value.

func (Frequency) GreaterThan

func (f Frequency) GreaterThan(other Frequency) bool

GreaterThan returns true if this frequency is greater than the other. Panics if the units are different.

func (Frequency) IsZero

func (f Frequency) IsZero() bool

IsZero returns true if the frequency value is zero.

func (Frequency) LessThan

func (f Frequency) LessThan(other Frequency) bool

LessThan returns true if this frequency is less than the other. Panics if the units are different.

func (Frequency) Mul

func (f Frequency) Mul(scalar float64) Frequency

Mul multiplies the frequency by a scalar value.

func (Frequency) Raw

func (f Frequency) Raw() float64

Raw returns the raw numeric value of the frequency.

func (Frequency) String

func (f Frequency) String() string

String returns the string representation of the frequency.

func (Frequency) Sub

func (f Frequency) Sub(other Frequency) Frequency

Sub subtracts another frequency value with the same unit. Panics if the units are different.

func (Frequency) To

func (f Frequency) To(targetUnit FrequencyUnit) Frequency

To converts the frequency to another unit.

Example:

freq := units.Hz(1500)
khz := freq.To(units.Kilohertz)  // Returns units.KHz(1.5)

func (Frequency) ToHz

func (f Frequency) ToHz() Frequency

ToHz converts any frequency value to hertz.

Example:

freq := units.KHz(2.5)
hz := freq.ToHz()  // Returns units.Hz(2500)

func (Frequency) ToKHz

func (f Frequency) ToKHz() Frequency

ToKHz converts any frequency value to kilohertz.

Example:

freq := units.Hz(2500)
khz := freq.ToKHz()  // Returns units.KHz(2.5)

type FrequencyUnit

type FrequencyUnit string

FrequencyUnit represents a CSS frequency unit type.

const (
	Hertz     FrequencyUnit = "Hz"  // Hertz
	Kilohertz FrequencyUnit = "kHz" // Kilohertz
)

CSS frequency units per CSS Values Level 4.

Relationship:

  • 1kHz = 1000Hz

type Integer

type Integer struct {
	Value int64
}

Integer represents a CSS integer value.

Integer values are whole numbers (no fractional component). They're used in properties like z-index, column-count, grid-row-start, and anywhere a count or index is needed.

References:

func Int

func Int(value int64) Integer

Int creates an integer value.

Example:

zIndex := units.Int(10)      // z-index: 10
columns := units.Int(3)      // column-count: 3

func (Integer) Abs

func (i Integer) Abs() Integer

Abs returns the absolute value of the integer.

func (Integer) Add

func (i Integer) Add(other Integer) Integer

Add adds two integers.

func (Integer) Clamp

func (i Integer) Clamp(minValue, maxValue int64) Integer

Clamp returns an integer clamped to the given range.

Example:

num := units.Int(150)
clamped := num.Clamp(0, 100)  // Returns units.Int(100)

func (Integer) Div

func (i Integer) Div(other Integer) Integer

Div divides by another integer (integer division, truncates toward zero).

func (Integer) Equals

func (i Integer) Equals(other Integer) bool

Equals returns true if this integer equals the other.

func (Integer) Float

func (i Integer) Float() float64

Float returns the integer as a float64.

func (Integer) GreaterThan

func (i Integer) GreaterThan(other Integer) bool

GreaterThan returns true if this integer is greater than the other.

func (Integer) IsEven

func (i Integer) IsEven() bool

IsEven returns true if the integer is even.

func (Integer) IsNegative

func (i Integer) IsNegative() bool

IsNegative returns true if the integer is less than zero.

func (Integer) IsOdd

func (i Integer) IsOdd() bool

IsOdd returns true if the integer is odd.

func (Integer) IsPositive

func (i Integer) IsPositive() bool

IsPositive returns true if the integer is greater than zero.

func (Integer) IsZero

func (i Integer) IsZero() bool

IsZero returns true if the integer value is zero.

func (Integer) LessThan

func (i Integer) LessThan(other Integer) bool

LessThan returns true if this integer is less than the other.

func (Integer) Maximum added in v1.0.2

func (i Integer) Maximum(other Integer) Integer

Maximum returns the larger of two integers.

func (Integer) Minimum added in v1.0.2

func (i Integer) Minimum(other Integer) Integer

Minimum returns the smaller of two integers.

func (Integer) Mod

func (i Integer) Mod(other Integer) Integer

Mod returns the remainder of division (modulo operation).

func (Integer) Mul

func (i Integer) Mul(other Integer) Integer

Mul multiplies two integers.

func (Integer) Pow

func (i Integer) Pow(exponent int64) Integer

Pow raises the integer to the given integer power.

func (Integer) Raw

func (i Integer) Raw() int64

Raw returns the raw integer value.

func (Integer) String

func (i Integer) String() string

String returns the string representation of the integer.

func (Integer) Sub

func (i Integer) Sub(other Integer) Integer

Sub subtracts another integer.

type Length

type Length struct {
	Value float64
	Unit  LengthUnit
}

Length represents a CSS length value with an explicit unit.

Per CSS Values spec, lengths can be:

  • Absolute: px, cm, mm, Q, in, pt, pc
  • Font-relative: em, rem, ex, rex, cap, rcap, ch, rch, ic, ric, lh, rlh
  • Viewport-relative: vw, vh, vmin, vmax, vb, vi, svw, svh, lvw, lvh, dvw, dvh
  • Container-relative: cqw, cqh, cqi, cqb, cqmin, cqmax

Example:

width := units.Px(400)    // 400 pixels
margin := units.Em(1.5)   // 1.5em
height := units.Vh(100)   // 100vh (full viewport height)

func Cap

func Cap(value float64) Length

Cap creates a length in cap units.

func Ch

func Ch(value float64) Length

Ch creates a length in ch units (character width, typically "0" glyph).

func Cm

func Cm(value float64) Length

Cm creates a length in centimeters (cm).

func Cqb

func Cqb(value float64) Length

Cqb creates a length in cqb units (container query block size).

func Cqh

func Cqh(value float64) Length

Cqh creates a length in cqh units (container query height).

func Cqi

func Cqi(value float64) Length

Cqi creates a length in cqi units (container query inline size).

func Cqmax

func Cqmax(value float64) Length

Cqmax creates a length in cqmax units.

func Cqmin

func Cqmin(value float64) Length

Cqmin creates a length in cqmin units.

func Cqw

func Cqw(value float64) Length

Cqw creates a length in cqw units (container query width).

func Em

func Em(value float64) Length

Em creates a length in em units.

func Ex

func Ex(value float64) Length

Ex creates a length in ex units.

func Ic

func Ic(value float64) Length

Ic creates a length in ic units (ideographic character width).

func In

func In(value float64) Length

In creates a length in inches (in).

func Lh

func Lh(value float64) Length

Lh creates a length in lh units (line height).

func Mm

func Mm(value float64) Length

Mm creates a length in millimeters (mm).

func Pc

func Pc(value float64) Length

Pc creates a length in picas (pc).

func Pt

func Pt(value float64) Length

Pt creates a length in points (pt).

func Px

func Px(value float64) Length

Px creates a length in pixels (px).

func Q

func Q(value float64) Length

Q creates a length in quarter-millimeters (Q).

func Rcap

func Rcap(value float64) Length

Rcap creates a length in rcap units.

func Rch

func Rch(value float64) Length

Rch creates a length in rch units.

func Rem

func Rem(value float64) Length

Rem creates a length in rem units.

func Rex

func Rex(value float64) Length

Rex creates a length in rex units.

func Ric

func Ric(value float64) Length

Ric creates a length in ric units.

func Rlh

func Rlh(value float64) Length

Rlh creates a length in rlh units.

func Vb

func Vb(value float64) Length

Vb creates a length in vb units (viewport block size).

func Vh

func Vh(value float64) Length

Vh creates a length in vh units (viewport height percentage).

func Vi

func Vi(value float64) Length

Vi creates a length in vi units (viewport inline size).

func Vmax

func Vmax(value float64) Length

Vmax creates a length in vmax units.

func Vmin

func Vmin(value float64) Length

Vmin creates a length in vmin units.

func Vw

func Vw(value float64) Length

Vw creates a length in vw units (viewport width percentage).

func (Length) Add

func (l Length) Add(other Length) Length

Add adds two lengths with the same unit. Panics if units don't match.

func (Length) Div

func (l Length) Div(scalar float64) Length

Div divides a length by a scalar.

func (Length) GreaterThan

func (l Length) GreaterThan(other Length) bool

GreaterThan returns true if this length is greater than another. Panics if units don't match.

func (Length) IsAbsolute

func (l Length) IsAbsolute() bool

IsAbsolute returns true if the unit is an absolute length unit.

func (Length) IsContainerRelative

func (l Length) IsContainerRelative() bool

IsContainerRelative returns true if the unit is container-relative.

func (Length) IsFontRelative

func (l Length) IsFontRelative() bool

IsFontRelative returns true if the unit is font-relative.

func (Length) IsViewportRelative

func (l Length) IsViewportRelative() bool

IsViewportRelative returns true if the unit is viewport-relative.

func (Length) IsZero

func (l Length) IsZero() bool

IsZero returns true if the length value is zero.

func (Length) LessThan

func (l Length) LessThan(other Length) bool

LessThan returns true if this length is less than another. Panics if units don't match.

func (Length) Mul

func (l Length) Mul(scalar float64) Length

Mul multiplies a length by a scalar.

func (Length) Raw

func (l Length) Raw() float64

Raw returns the raw float64 value, discarding unit information. Use this when interfacing with APIs that need raw numbers.

func (Length) Resolve

func (l Length) Resolve(ctx *Context) (Length, error)

Resolve converts any length (absolute or relative) to pixels using the provided context.

Example:

ctx := &units.Context{
    FontSize: 16.0,
    ViewportWidth: 1920.0,
}
length := units.Em(2)
px, err := length.Resolve(ctx)  // Returns units.Px(32)

func (Length) String

func (l Length) String() string

String returns a CSS-compatible string representation.

func (Length) Sub

func (l Length) Sub(other Length) Length

Sub subtracts two lengths with the same unit. Panics if units don't match.

func (Length) To

func (l Length) To(targetUnit LengthUnit) (Length, error)

To converts an absolute length to another absolute unit. Returns error if either unit is relative.

Example:

length := units.In(1)
cm, err := length.To(units.Centimeter)  // Returns units.Cm(2.54)

func (Length) ToPx

func (l Length) ToPx() (Length, error)

ToPx converts an absolute length to pixels. Returns error if the length unit is relative (requires context).

Example:

length := units.In(1)
px, err := length.ToPx()  // Returns units.Px(96)

type LengthUnit

type LengthUnit string

LengthUnit specifies the unit of measurement for a length value.

const (

	// PX - Absolute length, anchor unit
	// 1px = 1/96 of 1 inch
	// Reference: https://www.w3.org/TR/css-values-4/#absolute-lengths
	PX LengthUnit = "px"

	// CM - Absolute length
	// 1cm = 96px/2.54
	// Reference: https://www.w3.org/TR/css-values-4/#absolute-lengths
	CM LengthUnit = "cm"

	// MM - Absolute length
	// 1mm = 1/10 of 1cm
	// Reference: https://www.w3.org/TR/css-values-4/#absolute-lengths
	MM LengthUnit = "mm"

	// QQ - Absolute length (quarter-millimeter)
	// 1Q = 1/40 of 1cm
	// Reference: https://www.w3.org/TR/css-values-4/#absolute-lengths
	QQ LengthUnit = "Q"

	// IN - Absolute length
	// 1in = 2.54cm = 96px
	// Reference: https://www.w3.org/TR/css-values-4/#absolute-lengths
	IN LengthUnit = "in"

	// PT - Absolute length (typography)
	// 1pt = 1/72 of 1in
	// Reference: https://www.w3.org/TR/css-values-4/#absolute-lengths
	PT LengthUnit = "pt"

	// PC - Absolute length (typography)
	// 1pc = 1/6 of 1in = 12pt
	// Reference: https://www.w3.org/TR/css-values-4/#absolute-lengths
	PC LengthUnit = "pc"

	// Convenience aliases (long-form names only, short names conflict with constructors)
	Pixel             LengthUnit = PX
	Centimeter        LengthUnit = CM
	Millimeter        LengthUnit = MM
	QuarterMillimeter LengthUnit = QQ
	Inch              LengthUnit = IN
	Point             LengthUnit = PT
	Pica              LengthUnit = PC
)

Absolute length units are fixed in relation to each other and anchored to some physical measurement. They are mainly useful when the output environment is known.

The anchor unit is the pixel (px). The reference pixel is the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm's length.

const (

	// EM - Font-relative length
	// Equal to the computed value of font-size on the element
	EM LengthUnit = "em"

	// REM - Font-relative length
	// Equal to the computed value of font-size on the root element
	REM LengthUnit = "rem"

	// EX - Font-relative length
	// Equal to the x-height of the font (height of lowercase 'x')
	EX LengthUnit = "ex"

	// REX - Font-relative length
	// Equal to the x-height of the root element's font
	REX LengthUnit = "rex"

	// CAP - Font-relative length
	// Equal to the cap-height of the font (height of capital letters)
	CAP LengthUnit = "cap"

	// RCAP - Font-relative length
	// Equal to the cap-height of the root element's font
	RCAP LengthUnit = "rcap"

	// CH - Font-relative length
	// Equal to the advance measure of the "0" (ZERO, U+0030) glyph
	// Used for monospace width calculations (terminal cells)
	CH LengthUnit = "ch"

	// RCH - Font-relative length
	// Equal to the advance measure of "0" in the root element's font
	RCH LengthUnit = "rch"

	// IC - Font-relative length
	// Equal to the advance measure of the "水" (CJK water ideograph, U+6C34) glyph
	// Used for ideographic character width
	IC LengthUnit = "ic"

	// RIC - Font-relative length
	// Equal to the advance measure of "水" in the root element's font
	RIC LengthUnit = "ric"

	// LH - Font-relative length
	// Equal to the computed value of line-height on the element
	LH LengthUnit = "lh"

	// RLH - Font-relative length
	// Equal to the computed value of line-height on the root element
	RLH LengthUnit = "rlh"

	// Convenience aliases (Unit suffix only, short names conflict with constructors)
	EmUnit   LengthUnit = EM
	RemUnit  LengthUnit = REM
	ExUnit   LengthUnit = EX
	RexUnit  LengthUnit = REX
	CapUnit  LengthUnit = CAP
	RcapUnit LengthUnit = RCAP
	ChUnit   LengthUnit = CH
	RchUnit  LengthUnit = RCH
	IcUnit   LengthUnit = IC
	RicUnit  LengthUnit = RIC
	LhUnit   LengthUnit = LH
	RlhUnit  LengthUnit = RLH
)

Font-relative lengths define length values in terms of the font metrics of the element on which they are used (or, for the "root" variants, the root element).

const (

	// VW - Viewport width
	// Equal to 1% of viewport width
	VW LengthUnit = "vw"

	// VH - Viewport height
	// Equal to 1% of viewport height
	VH LengthUnit = "vh"

	// VMIN - Viewport minimum
	// Equal to the smaller of vw or vh
	VMIN LengthUnit = "vmin"

	// VMAX - Viewport maximum
	// Equal to the larger of vw or vh
	VMAX LengthUnit = "vmax"

	// VB - Viewport block size
	// Equal to 1% of viewport size in block axis
	VB LengthUnit = "vb"

	// VI - Viewport inline size
	// Equal to 1% of viewport size in inline axis
	VI LengthUnit = "vi"

	// Small viewport units (smallest possible viewport)
	SVW LengthUnit = "svw"
	SVH LengthUnit = "svh"
	SVB LengthUnit = "svb"
	SVI LengthUnit = "svi"

	// Large viewport units (largest possible viewport)
	LVW LengthUnit = "lvw"
	LVH LengthUnit = "lvh"
	LVB LengthUnit = "lvb"
	LVI LengthUnit = "lvi"

	// Dynamic viewport units (current viewport, accounting for dynamic UI)
	DVW LengthUnit = "dvw"
	DVH LengthUnit = "dvh"
	DVB LengthUnit = "dvb"
	DVI LengthUnit = "dvi"

	// Convenience aliases (Unit suffix only, short names conflict with constructors)
	VwUnit   LengthUnit = VW
	VhUnit   LengthUnit = VH
	VminUnit LengthUnit = VMIN
	VmaxUnit LengthUnit = VMAX
	VbUnit   LengthUnit = VB
	ViUnit   LengthUnit = VI
	SvwUnit  LengthUnit = SVW
	SvhUnit  LengthUnit = SVH
	SvbUnit  LengthUnit = SVB
	SviUnit  LengthUnit = SVI
	LvwUnit  LengthUnit = LVW
	LvhUnit  LengthUnit = LVH
	LvbUnit  LengthUnit = LVB
	LviUnit  LengthUnit = LVI
	DvwUnit  LengthUnit = DVW
	DvhUnit  LengthUnit = DVH
	DvbUnit  LengthUnit = DVB
	DviUnit  LengthUnit = DVI
)

Viewport-percentage lengths define length values relative to the size of the initial containing block (viewport).

const (

	// CQW - Container query width
	// Equal to 1% of query container's width
	CQW LengthUnit = "cqw"

	// CQH - Container query height
	// Equal to 1% of query container's height
	CQH LengthUnit = "cqh"

	// CQI - Container query inline size
	// Equal to 1% of query container's inline size
	CQI LengthUnit = "cqi"

	// CQB - Container query block size
	// Equal to 1% of query container's block size
	CQB LengthUnit = "cqb"

	// CQMIN - Container query minimum
	// Equal to the smaller of cqi or cqb
	CQMIN LengthUnit = "cqmin"

	// CQMAX - Container query maximum
	// Equal to the larger of cqi or cqb
	CQMAX LengthUnit = "cqmax"

	// Convenience aliases (Unit suffix only, short names conflict with constructors)
	CqwUnit   LengthUnit = CQW
	CqhUnit   LengthUnit = CQH
	CqiUnit   LengthUnit = CQI
	CqbUnit   LengthUnit = CQB
	CqminUnit LengthUnit = CQMIN
	CqmaxUnit LengthUnit = CQMAX
)

Container query length units specify lengths relative to the dimensions of a query container.

type Number

type Number struct {
	Value float64
}

Number represents a CSS number value.

Number values are dimensionless real numbers, possibly with a fractional component. They're used in properties like line-height, opacity, flex-grow, and as multipliers in various calculations.

References:

func Num

func Num(value float64) Number

Num creates a number value.

Example:

lineHeight := units.Num(1.5)  // line-height: 1.5
opacity := units.Num(0.8)     // opacity: 0.8

func (Number) Abs

func (n Number) Abs() Number

Abs returns the absolute value of the number.

func (Number) Add

func (n Number) Add(other Number) Number

Add adds two numbers.

func (Number) Ceil

func (n Number) Ceil() Number

Ceil returns the smallest integer greater than or equal to the number.

func (Number) Clamp

func (n Number) Clamp(minValue, maxValue float64) Number

Clamp returns a number clamped to the given range.

Example:

num := units.Num(1.8)
clamped := num.Clamp(0, 1)  // Returns units.Num(1)

func (Number) Div

func (n Number) Div(other Number) Number

Div divides by another number.

func (Number) Equals

func (n Number) Equals(other Number) bool

Equals returns true if this number equals the other.

func (Number) Floor

func (n Number) Floor() Number

Floor returns the largest integer less than or equal to the number.

func (Number) GreaterThan

func (n Number) GreaterThan(other Number) bool

GreaterThan returns true if this number is greater than the other.

func (Number) IsNegative

func (n Number) IsNegative() bool

IsNegative returns true if the number is less than zero.

func (Number) IsPositive

func (n Number) IsPositive() bool

IsPositive returns true if the number is greater than zero.

func (Number) IsZero

func (n Number) IsZero() bool

IsZero returns true if the number value is zero.

func (Number) LessThan

func (n Number) LessThan(other Number) bool

LessThan returns true if this number is less than the other.

func (Number) Mul

func (n Number) Mul(other Number) Number

Mul multiplies two numbers.

func (Number) Pow

func (n Number) Pow(exponent float64) Number

Pow raises the number to the given power.

func (Number) Raw

func (n Number) Raw() float64

Raw returns the raw numeric value.

func (Number) Round

func (n Number) Round() Number

Round returns the number rounded to the nearest integer.

func (Number) Sqrt

func (n Number) Sqrt() Number

Sqrt returns the square root of the number.

func (Number) String

func (n Number) String() string

String returns the string representation of the number.

func (Number) Sub

func (n Number) Sub(other Number) Number

Sub subtracts another number.

type Percentage

type Percentage struct {
	Value float64
}

Percentage represents a CSS percentage value.

Percentage values are always relative to another quantity. The meaning of 100% depends on the context in which the percentage is used. For example, width: 50% means 50% of the containing block's width.

References:

func Percent

func Percent(value float64) Percentage

Percent creates a percentage value.

Example:

width := units.Percent(50)  // 50%

func (Percentage) Add

func (p Percentage) Add(other Percentage) Percentage

Add adds two percentage values.

func (Percentage) Clamp

func (p Percentage) Clamp(minValue, maxValue float64) Percentage

Clamp returns a percentage clamped to the given range.

Example:

pct := units.Percent(150)
clamped := pct.Clamp(0, 100)  // Returns units.Percent(100)

func (Percentage) Div

func (p Percentage) Div(scalar float64) Percentage

Div divides the percentage by a scalar value.

func (Percentage) Equals

func (p Percentage) Equals(other Percentage) bool

Equals returns true if this percentage equals the other.

func (Percentage) Fraction

func (p Percentage) Fraction() float64

Fraction returns the percentage as a fraction (e.g., 50% -> 0.5).

func (Percentage) GreaterThan

func (p Percentage) GreaterThan(other Percentage) bool

GreaterThan returns true if this percentage is greater than the other.

func (Percentage) IsZero

func (p Percentage) IsZero() bool

IsZero returns true if the percentage value is zero.

func (Percentage) LessThan

func (p Percentage) LessThan(other Percentage) bool

LessThan returns true if this percentage is less than the other.

func (Percentage) Mul

func (p Percentage) Mul(scalar float64) Percentage

Mul multiplies the percentage by a scalar value.

func (Percentage) Of

func (p Percentage) Of(value float64) float64

Of calculates the percentage of a given value.

Example:

pct := units.Percent(50)
result := pct.Of(200)  // Returns 100 (50% of 200)

func (Percentage) Raw

func (p Percentage) Raw() float64

Raw returns the raw numeric value of the percentage.

func (Percentage) String

func (p Percentage) String() string

String returns the string representation of the percentage.

func (Percentage) Sub

func (p Percentage) Sub(other Percentage) Percentage

Sub subtracts another percentage value.

type Ratio

type Ratio struct {
	First  float64
	Second float64
}

Ratio represents a CSS ratio value.

Ratio values consist of two positive numbers separated by a slash (/), representing the ratio of the first number to the second. Common uses include aspect-ratio property for maintaining proportions.

If the second number is omitted, it defaults to 1.

References:

func NewRatio

func NewRatio(first, second float64) Ratio

NewRatio creates a ratio value from two numbers.

Example:

aspectRatio := units.NewRatio(16, 9)  // 16:9 aspect ratio
square := units.NewRatio(1, 1)        // 1:1 aspect ratio

func RatioFrom

func RatioFrom(value float64) Ratio

RatioFrom creates a ratio from a single number (equivalent to n/1).

Example:

ratio := units.RatioFrom(2)  // 2/1 ratio

func (Ratio) ApplyToHeight

func (r Ratio) ApplyToHeight(height float64) float64

ApplyToHeight calculates the width for a given height based on this ratio.

Example:

ratio := units.NewRatio(16, 9)  // 16:9
width := ratio.ApplyToHeight(1080)  // Returns 1920

func (Ratio) ApplyToWidth

func (r Ratio) ApplyToWidth(width float64) float64

ApplyToWidth calculates the height for a given width based on this ratio.

Example:

ratio := units.NewRatio(16, 9)  // 16:9
height := ratio.ApplyToWidth(1920)  // Returns 1080

func (Ratio) Equals

func (r Ratio) Equals(other Ratio) bool

Equals returns true if two ratios are equal.

func (Ratio) FitHeight

func (r Ratio) FitHeight(maxHeight float64) (width, height float64)

FitHeight returns the dimensions that fit within maxHeight while maintaining the ratio.

func (Ratio) FitWidth

func (r Ratio) FitWidth(maxWidth float64) (width, height float64)

FitWidth returns the dimensions that fit within maxWidth while maintaining the ratio.

func (Ratio) GreaterThan

func (r Ratio) GreaterThan(other Ratio) bool

GreaterThan returns true if this ratio is greater than the other.

func (Ratio) Inverse

func (r Ratio) Inverse() Ratio

Inverse returns the inverse of the ratio (swaps first and second).

Example:

ratio := units.NewRatio(16, 9)
inverse := ratio.Inverse()  // Returns 9/16

func (Ratio) IsSquare

func (r Ratio) IsSquare() bool

IsSquare returns true if the ratio is 1:1.

func (Ratio) IsTall

func (r Ratio) IsTall() bool

IsTall returns true if the ratio is taller than it is wide (first < second).

func (Ratio) IsWide

func (r Ratio) IsWide() bool

IsWide returns true if the ratio is wider than it is tall (first > second).

func (Ratio) LessThan

func (r Ratio) LessThan(other Ratio) bool

LessThan returns true if this ratio is less than the other.

func (Ratio) Simplify

func (r Ratio) Simplify() Ratio

Simplify returns a simplified version of the ratio by dividing both numbers by their greatest common divisor.

Example:

ratio := units.NewRatio(16, 8)
simplified := ratio.Simplify()  // Returns 2/1

func (Ratio) String

func (r Ratio) String() string

String returns the string representation of the ratio.

func (Ratio) Value

func (r Ratio) Value() float64

Value returns the ratio as a decimal number (first / second).

Example:

ratio := units.NewRatio(16, 9)
value := ratio.Value()  // Returns ~1.778

type Resolution

type Resolution struct {
	Value float64
	Unit  ResolutionUnit
}

Resolution represents a CSS resolution value.

Resolution values are used in CSS media queries and image properties to describe the density of pixels. CSS supports dots per inch (dpi), dots per centimeter (dpcm), and dots per pixel unit (dppx).

References:

func Dpcm

func Dpcm(value float64) Resolution

Dpcm creates a resolution value in dots per centimeter.

Example:

res := units.Dpcm(37.795)  // Equivalent to 96dpi

func Dpi

func Dpi(value float64) Resolution

Dpi creates a resolution value in dots per inch.

Example:

res := units.Dpi(96)  // Standard screen resolution

func Dppx

func Dppx(value float64) Resolution

Dppx creates a resolution value in dots per pixel unit.

Example:

res := units.Dppx(2)  // 2x "Retina" display

func (Resolution) Add

func (r Resolution) Add(other Resolution) Resolution

Add adds two resolution values with the same unit. Panics if the units are different.

func (Resolution) Div

func (r Resolution) Div(scalar float64) Resolution

Div divides the resolution by a scalar value.

func (Resolution) GreaterThan

func (r Resolution) GreaterThan(other Resolution) bool

GreaterThan returns true if this resolution is greater than the other. Panics if the units are different.

func (Resolution) IsZero

func (r Resolution) IsZero() bool

IsZero returns true if the resolution value is zero.

func (Resolution) LessThan

func (r Resolution) LessThan(other Resolution) bool

LessThan returns true if this resolution is less than the other. Panics if the units are different.

func (Resolution) Mul

func (r Resolution) Mul(scalar float64) Resolution

Mul multiplies the resolution by a scalar value.

func (Resolution) Raw

func (r Resolution) Raw() float64

Raw returns the raw numeric value of the resolution.

func (Resolution) String

func (r Resolution) String() string

String returns the string representation of the resolution.

func (Resolution) Sub

func (r Resolution) Sub(other Resolution) Resolution

Sub subtracts another resolution value with the same unit. Panics if the units are different.

func (Resolution) To

func (r Resolution) To(targetUnit ResolutionUnit) Resolution

To converts the resolution to another unit.

Example:

res := units.Dpi(96)
dppx := res.To(units.DotsPerPixel)  // Returns units.Dppx(1)

func (Resolution) ToDpcm

func (r Resolution) ToDpcm() Resolution

ToDpcm converts any resolution value to dots per centimeter.

Example:

res := units.Dpi(96)
dpcm := res.ToDpcm()  // Returns units.Dpcm(37.795)

func (Resolution) ToDpi

func (r Resolution) ToDpi() Resolution

ToDpi converts any resolution value to dots per inch.

Example:

res := units.Dppx(2)
dpi := res.ToDpi()  // Returns units.Dpi(192)

func (Resolution) ToDppx

func (r Resolution) ToDppx() Resolution

ToDppx converts any resolution value to dots per pixel unit.

Example:

res := units.Dpi(192)
dppx := res.ToDppx()  // Returns units.Dppx(2)

type ResolutionUnit

type ResolutionUnit string

ResolutionUnit represents a CSS resolution unit type.

const (
	DotsPerInch       ResolutionUnit = "dpi"  // Dots per inch
	DotsPerCentimeter ResolutionUnit = "dpcm" // Dots per centimeter
	DotsPerPixel      ResolutionUnit = "dppx" // Dots per pixel unit
)

CSS resolution units per CSS Values Level 4.

Relationship:

  • 1dppx = 96dpi
  • 1dpcm = 96dpi / 2.54 ≈ 37.795dpi
  • 1in = 2.54cm

type Time

type Time struct {
	Value float64
	Unit  TimeUnit
}

Time represents a CSS time value.

Time values are used in CSS animations, transitions, and other time-based properties. CSS supports seconds and milliseconds.

References:

func Ms

func Ms(value float64) Time

Ms creates a time value in milliseconds.

Example:

duration := units.Ms(500)  // 500 milliseconds

func Sec

func Sec(value float64) Time

Sec creates a time value in seconds.

Example:

duration := units.Sec(2.5)  // 2.5 seconds

func (Time) Add

func (t Time) Add(other Time) Time

Add adds two time values with the same unit. Panics if the units are different.

func (Time) Div

func (t Time) Div(scalar float64) Time

Div divides the time by a scalar value.

func (Time) GreaterThan

func (t Time) GreaterThan(other Time) bool

GreaterThan returns true if this time is greater than the other. Panics if the units are different.

func (Time) IsZero

func (t Time) IsZero() bool

IsZero returns true if the time value is zero.

func (Time) LessThan

func (t Time) LessThan(other Time) bool

LessThan returns true if this time is less than the other. Panics if the units are different.

func (Time) Mul

func (t Time) Mul(scalar float64) Time

Mul multiplies the time by a scalar value.

func (Time) Raw

func (t Time) Raw() float64

Raw returns the raw numeric value of the time.

func (Time) String

func (t Time) String() string

String returns the string representation of the time.

func (Time) Sub

func (t Time) Sub(other Time) Time

Sub subtracts another time value with the same unit. Panics if the units are different.

func (Time) To

func (t Time) To(targetUnit TimeUnit) Time

To converts the time to another unit.

Example:

time := units.Sec(1.5)
ms := time.To(units.Millisecond)  // Returns units.Ms(1500)

func (Time) ToMs

func (t Time) ToMs() Time

ToMs converts any time value to milliseconds.

Example:

time := units.Sec(2.5)
ms := time.ToMs()  // Returns units.Ms(2500)

func (Time) ToSec

func (t Time) ToSec() Time

ToSec converts any time value to seconds.

Example:

time := units.Ms(2500)
sec := time.ToSec()  // Returns units.Sec(2.5)

type TimeUnit

type TimeUnit string

TimeUnit represents a CSS time unit type.

const (
	Second      TimeUnit = "s"  // Seconds
	Millisecond TimeUnit = "ms" // Milliseconds
)

CSS time units per CSS Values Level 4.

Relationship:

  • 1s = 1000ms

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL