Documentation
¶
Overview ¶
Package css implements a deliberately small but real subset of CSS: a value model, a tokenizer/parser for stylesheets and declaration blocks, tag/class/ id selectors with specificity, and a cascade with inheritance over a dom tree. It targets the handful of properties Phase 0 needs — display, color, background-color, font-size, font-weight, font-family, margin, padding, width, text-align — plus a user-agent default stylesheet for common tags.
Index ¶
- Constants
- Variables
- func ImportURLs(sheet string) (urls []string, medias []string)
- func MediaApplies(media string, vw float64) bool
- type AlignContent
- type AlignItems
- type AlignSelf
- type BgImage
- type BgImageKind
- type BgPosition
- type BgRepeat
- type BgSize
- type BgSizeKind
- type BorderSide
- type BorderStyle
- type Borders
- type BoxShadow
- type BoxSizing
- type Clear
- type Color
- type ColorStop
- type Declaration
- type Display
- type Edges
- type FlexDirection
- type FlexWrap
- type Float
- type FontFamily
- type Gradient
- type GradientSampler
- type GridFlow
- type GridLine
- type Justify
- type Length
- type LineHeight
- type LinkRef
- type ListStylePosition
- type ListStyleType
- type Overflow
- type Position
- type RadialExtent
- type RadialShape
- type Rule
- type Selector
- type Style
- type StyleMap
- type TextAlign
- type TrackKind
- type TrackSize
- type WhiteSpace
Constants ¶
const DefaultViewportWidth = 1024
DefaultViewportWidth is the viewport width (CSS px) used to evaluate @media width queries when no explicit width is supplied. It matches a desktop render.
Variables ¶
var Transparent = Color{}
Transparent is the fully-transparent colour (the initial background-color).
Functions ¶
func ImportURLs ¶
ImportURLs extracts the targets of leading @import at-rules from a stylesheet, in order. Per the CSS spec @import rules must precede all other rules (except @charset), so only the leading run is honoured; the first non-@import, non-@charset, non-comment token stops the scan. Both @import "url" and @import url(...) forms are supported, with an optional trailing media query (returned via the paired media slice, "" when absent).
func MediaApplies ¶
MediaApplies reports whether a media query (from a <link media> attribute or an @import) applies at viewport width vw. It reuses the same simplified evaluation as @media blocks: an empty query always applies, "print" never does, and min-width/max-width pixel features are honoured against vw. A comma-separated media list matches if ANY component matches.
Types ¶
type AlignContent ¶
type AlignContent uint8
AlignContent distributes flex lines (or grid tracks) along the cross axis when there is spare cross-axis space (multi-line flex / align-content).
const ( // AlignContentStretch stretches lines to fill the cross axis (initial). AlignContentStretch AlignContent = iota // AlignContentStart packs lines at the cross-start edge. AlignContentStart // AlignContentEnd packs lines at the cross-end edge. AlignContentEnd // AlignContentCenter centres the lines as a group. AlignContentCenter // AlignContentSpaceBetween spreads lines with the ends flush. AlignContentSpaceBetween // AlignContentSpaceAround spreads lines with half-gaps at the ends. AlignContentSpaceAround // AlignContentSpaceEvenly spreads lines with equal gaps incl. the ends. AlignContentSpaceEvenly )
type AlignItems ¶
type AlignItems uint8
AlignItems is the cross-axis alignment (align-items). In a grid container it is also reused for the block-axis (align-items) and, via JustifyItems, the inline-axis (justify-items) alignment of items within their cells.
const ( // AlignStretch stretches items to fill the cross axis (initial value). AlignStretch AlignItems = iota // AlignFlexStart aligns items at the cross-start edge. AlignFlexStart // AlignFlexEnd aligns items at the cross-end edge. AlignFlexEnd // AlignCenterItems centres items on the cross axis. AlignCenterItems )
type AlignSelf ¶
type AlignSelf uint8
AlignSelf overrides a single item's cross-axis alignment. Auto (the initial value) defers to the container's align-items.
const ( // AlignSelfAuto uses the container's align-items value (initial). AlignSelfAuto AlignSelf = iota // AlignSelfStretch stretches this item on the cross axis. AlignSelfStretch // AlignSelfStart aligns this item at the cross-start edge. AlignSelfStart // AlignSelfEnd aligns this item at the cross-end edge. AlignSelfEnd // AlignSelfCenter centres this item on the cross axis. AlignSelfCenter )
func (AlignSelf) Resolve ¶
func (a AlignSelf) Resolve(container AlignItems) AlignItems
resolve returns the effective AlignItems for an item, falling back to the container's align-items when the item's align-self is auto.
type BgImage ¶
type BgImage struct {
Kind BgImageKind
URL string // raw url() argument (BgURL); resolved by the engine
Grad *Gradient // gradient spec (BgGradient)
}
BgImage is one background-image layer: a url() bitmap or a gradient. Layers are stored first-listed-first; the first layer paints on top (CSS order).
type BgImageKind ¶
type BgImageKind uint8
BgImageKind identifies the kind of a single background-image layer.
const ( // BgNone is an empty layer (the keyword `none`). BgNone BgImageKind = iota // BgURL is a url(...) bitmap layer. BgURL // BgGradient is a linear/radial gradient layer. BgGradient )
type BgPosition ¶
type BgPosition struct {
X, Y Length
}
BgPosition is a resolved background-position (percent/px per axis). The initial value is the top-left corner (0%, 0%).
type BgSize ¶
type BgSize struct {
Kind BgSizeKind
W Length // meaningful when SizeExplicit
H Length // meaningful when SizeExplicit; Auto keeps aspect ratio
}
BgSize is a resolved background-size value.
type BgSizeKind ¶
type BgSizeKind uint8
BgSizeKind selects how a background image is scaled.
const ( // SizeAuto uses the image's intrinsic size (gradients fill the box). SizeAuto BgSizeKind = iota // SizeCover scales to cover the whole box (may crop). SizeCover // SizeContain scales to fit inside the box (may letterbox). SizeContain // SizeExplicit uses the given width/height lengths (a length or auto each). SizeExplicit )
type BorderSide ¶
type BorderSide struct {
Width float64
Style BorderStyle
Color Color
}
BorderSide is one edge's border: its width, line style and colour.
type BorderStyle ¶
type BorderStyle uint8
BorderStyle is the subset of border-style the engine paints. Any non-none, non-hidden line style renders as a solid line (dashed/dotted/etc. collapse to solid at this fidelity).
const ( // BorderNone is the initial value: no border line (even if width > 0). BorderNone BorderStyle = iota // BorderSolid renders a solid line of the border colour. BorderSolid )
type Borders ¶
type Borders struct{ Top, Right, Bottom, Left BorderSide }
Borders is the four border edges of a box.
type BoxSizing ¶
type BoxSizing uint8
BoxSizing selects whether width/height apply to the content box or the border box.
type Color ¶
type Color struct{ R, G, B, A uint8 }
Color is an 8-bit-per-channel RGBA colour. A==0 is treated as transparent.
type ColorStop ¶
ColorStop is one gradient colour stop. Pos is the parsed position (a percent or px length); HasPos is false when the stop had no explicit position and its fraction is interpolated during normalisation.
type Declaration ¶
Declaration is a single property: value pair.
func ParseDeclarations ¶
func ParseDeclarations(body string) []Declaration
ParseDeclarations parses a declaration block body ("a: b; c: d") into declarations, lowercasing property names and trimming values.
type Display ¶
type Display uint8
Display is the subset of the display property the engine understands.
const ( // DisplayInline is the default for unknown/inline elements. DisplayInline Display = iota // DisplayBlock stacks the box vertically in block flow. DisplayBlock // DisplayNone removes the element (and subtree) from layout. DisplayNone // DisplayInlineBlock is an atomic inline-level block (laid out as a block // but participating inline; Phase 1 treats it as block for simplicity). DisplayInlineBlock // DisplayFlex is a block-level flex container. DisplayFlex // DisplayTable is a block-level table box. DisplayTable // DisplayTableRow is a table row box. DisplayTableRow // DisplayTableCell is a table cell box. DisplayTableCell // DisplayTableRowGroup is a thead/tbody/tfoot grouping box (transparent to // the table's row collection). DisplayTableRowGroup // DisplayGrid is a block-level CSS grid container. DisplayGrid )
type Edges ¶
type Edges struct{ Top, Right, Bottom, Left float64 }
Edges holds the four sides of a margin or padding box, in pixels.
type FlexDirection ¶
type FlexDirection uint8
FlexDirection is the main-axis direction of a flex container.
const ( // FlexRow lays items along the inline (horizontal) axis. FlexRow FlexDirection = iota // FlexColumn lays items along the block (vertical) axis. FlexColumn )
type FontFamily ¶
type FontFamily uint8
FontFamily is the generic font family a run is rendered with.
const ( // Sans is the default sans-serif family. Sans FontFamily = iota // Serif is the serif family. Serif // Mono is the monospace family. Mono )
type Gradient ¶
type Gradient struct {
Radial bool
// Linear direction. Corner is 0 for an explicit angle (AngleDeg), else a
// corner code 1..4 (top-right/bottom-right/bottom-left/top-left) whose angle
// depends on the box size and is resolved in the sampler.
AngleDeg float64
Corner uint8
// Radial geometry.
Shape RadialShape
Extent RadialExtent
RadiusX, RadiusY Length // meaningful when Extent==ExtentExplicit
PosX, PosY Length // centre; default 50% 50%
Stops []ColorStop
}
Gradient is a parsed linear or radial gradient.
func (*Gradient) Sampler ¶
func (g *Gradient) Sampler(w, h float64) GradientSampler
Sampler builds a GradientSampler for a box of the given size (W×H, pixels).
type GradientSampler ¶
type GradientSampler struct {
// contains filtered or unexported fields
}
GradientSampler evaluates a gradient's colour at any point of a W×H box. It is built once per box (Gradient.Sampler) with its geometry and normalised stops precomputed, then queried per pixel with At.
func (GradientSampler) At ¶
func (s GradientSampler) At(px, py float64) Color
At returns the gradient colour at box-local point (px, py).
type GridLine ¶
GridLine is one endpoint of a grid item's placement. Auto means the endpoint is chosen by auto-placement; Span means the endpoint is "span N" tracks from the opposite edge; otherwise N is a 1-based grid line number.
type Justify ¶
type Justify uint8
Justify is the main-axis distribution (justify-content).
const ( // JustifyStart packs items at the main-start edge (initial value). JustifyStart Justify = iota // JustifyEnd packs items at the main-end edge. JustifyEnd // JustifyCenter centres items on the main axis. JustifyCenter // JustifySpaceBetween distributes free space between items. JustifySpaceBetween // JustifySpaceAround distributes free space around items. JustifySpaceAround // JustifySpaceEvenly distributes free space evenly incl. the ends. JustifySpaceEvenly )
type Length ¶
type Length struct {
Px float64
Percent float64 // 0..1; only meaningful when IsPercent
IsPercent bool
Auto bool
}
Length is a resolved CSS length. Percentages are kept separately so the layout can resolve them against the containing block's width.
type LineHeight ¶
type LineHeight struct {
Px float64
Factor float64 // unitless multiplier of the element's own font-size (0 = none)
Normal bool
}
LineHeight is a computed line-height. Normal means "use the font's own line height". Otherwise it is EITHER a fixed pixel height (Px, from a length or percentage value) OR a unitless Factor of the element's own font-size.
The distinction is load-bearing for inheritance (CSS 2.1 §10.8.1): a length or percentage line-height computes to a fixed pixel value that descendants inherit unchanged, whereas a unitless number computes to the number itself and inherits AS the number, so each descendant re-multiplies by its OWN font-size. Collapsing a unitless line-height to pixels at the declaring element (as an earlier version did) leaks the ancestor's font-size onto larger/smaller descendants, making their line boxes too short and letting glyphs from adjacent lines overlap.
func (LineHeight) Resolve ¶
func (h LineHeight) Resolve(fontSize float64) (float64, bool)
Resolve returns the used line-height in pixels for an element whose computed font-size is fontSize, and whether an explicit height applies. It returns (0, false) for `normal` (defer to the font's natural metrics) and for a non-positive height. A unitless Factor is multiplied by fontSize; a fixed Px is returned unchanged.
type LinkRef ¶
type LinkRef struct {
Href string // the raw href attribute value (unresolved)
Media string // the raw media attribute value ("" when absent)
}
LinkRef is a reference to an external stylesheet declared by a <link rel="stylesheet" href="..."> element, with its media attribute.
func StylesheetLinks ¶
StylesheetLinks walks the DOM in document order and returns every <link rel="stylesheet"> href, preserving order (which fixes cascade precedence). Links whose rel does not contain the "stylesheet" token, or that carry the "alternate" token, or that have an empty href, are skipped.
type ListStylePosition ¶
type ListStylePosition uint8
ListStylePosition is where the marker sits relative to the item's content. It inherits.
const ( // ListOutside places the marker in the indent to the left of the content box // (the initial value). ListOutside ListStylePosition = iota // ListInside places the marker inside the content box, before the first line. ListInside )
type ListStyleType ¶
type ListStyleType uint8
ListStyleType is the marker style of a display:list-item box. It inherits.
const ( // ListDisc is a filled circle (the initial value / <ul> default). ListDisc ListStyleType = iota // ListCircle is a hollow (stroked) circle. ListCircle // ListSquare is a filled square. ListSquare // ListDecimal is an ascending decimal number ("1.", "2.", …) — the <ol> default. ListDecimal // ListNone paints no marker. ListNone )
type Overflow ¶ added in v0.2.0
type Overflow uint8
Overflow is the computed overflow of one axis. For the engine's headless paint every non-visible value (hidden/clip/scroll/auto) clips descendant painting to the box's padding box — there is no interactive scrolling, so a scroll/auto container renders exactly its visible window, matching the first paint a user would see. This is what keeps the universal `sr-only` / visually-hidden pattern (position:absolute;width:1px;height:1px; overflow:hidden;clip) from painting its screen-reader text at full size.
type Position ¶
type Position uint8
Position is the subset of the position property the engine understands.
const ( // PositionStatic is the initial value: the box is in normal flow with no // top/right/bottom/left offset applied. PositionStatic Position = iota // PositionRelative keeps the box in normal flow (it still reserves space) but // paints it shifted by its top/left/right/bottom offset. PositionRelative // PositionAbsolute removes the box from normal flow and positions it against // the padding box of the nearest positioned ancestor (else the initial // containing block). PositionAbsolute // PositionFixed removes the box from normal flow and positions it against the // initial containing block (the viewport). For a full-page static render it is // resolved to document coordinates so it paints once at its place. PositionFixed // PositionSticky is approximated as relative for a full-page static shot. PositionSticky )
func (Position) OutOfFlow ¶
OutOfFlow reports whether a position value takes the box out of normal flow (so it reserves no space in its parent's block/inline formatting context).
func (Position) Positioned ¶
Positioned reports whether a position value makes the box a containing block for absolutely-positioned descendants (anything other than static).
type RadialExtent ¶
type RadialExtent uint8
RadialExtent is the sizing keyword of a radial gradient's ending shape.
const ( // ExtentFarthestCorner is the default extent. ExtentFarthestCorner RadialExtent = iota // ExtentClosestSide sizes to the nearest edge. ExtentClosestSide // ExtentClosestCorner sizes to the nearest corner. ExtentClosestCorner // ExtentFarthestSide sizes to the farthest edge. ExtentFarthestSide // ExtentExplicit uses explicit RadiusX/RadiusY lengths. ExtentExplicit )
type RadialShape ¶
type RadialShape uint8
RadialShape selects a circular or elliptical radial gradient.
const ( // RadialEllipse is the default radial shape. RadialEllipse RadialShape = iota // RadialCircle forces equal radii. RadialCircle )
type Rule ¶
type Rule struct {
Selectors []Selector
Declarations []Declaration
}
Rule is a parsed style rule: a list of selectors sharing a declaration block.
func ParseStylesheet ¶
ParseStylesheet parses a full stylesheet into rules at the default viewport width. See ParseStylesheetVW to control @media evaluation.
func ParseStylesheetVW ¶
ParseStylesheetVW parses a full stylesheet into rules, evaluating @media blocks against viewport width vw: a matching @media block's inner rules are included, a non-matching one is skipped. Other at-rules (@font-face, @keyframes, @supports, @import, ...) are skipped wholesale. Malformed rules are skipped defensively.
type Selector ¶
type Selector struct {
// contains filtered or unexported fields
}
Selector is a full complex selector: a chain of compound selectors joined by combinators. parts is in source order (left to right); parts[len-1] is the key selector matched against the candidate element, and each preceding part constrains an ancestor or sibling via combs[i] (the combinator between parts[i] and parts[i+1]).
func ParseSelectorList ¶
ParseSelectorList parses a comma-separated selector list, skipping empty and unparseable entries. Commas inside functional pseudo-classes (`:is(a, b)`) are respected (not treated as list separators), and `:is()` / `:where()` / `:matches()` wrappers are expanded into plain selectors — the form modern Tailwind emits for its dark-mode and variant rules (`:is(.dark .dark\:bg-wash-dark)`).
func (Selector) Matches ¶
Matches reports whether the selector matches element n, evaluating the combinator chain from the key selector leftwards.
func (Selector) Specificity ¶
Specificity returns the (a, b, c) specificity packed into a single int, with a = id count, b = class count, c = tag count, summed over all compounds.
type Style ¶
type Style struct {
Display Display
Color Color
Background Color
FontSize float64 // px
FontWeight int // 400 = normal, 700 = bold
FontFamily FontFamily
Italic bool // font-style: italic|oblique (inherited)
Margin Edges
Padding Edges
Border Borders
Width Length // Auto by default
MinWidth Length // Auto (== none) by default
MaxWidth Length // Auto (== none) by default
Height Length // Auto by default
MinHeight Length // Auto (== none) by default
MaxHeight Length // Auto (== none) by default
BoxSizing BoxSizing
TextAlign TextAlign
WhiteSpace WhiteSpace
LineHeight LineHeight
// ListItem marks a display:list-item box (it generates a marker). It is not
// inherited. ListStyleType and ListStylePosition are inherited and select the
// marker glyph and its placement.
ListItem bool
ListStyleType ListStyleType
ListStylePosition ListStylePosition
// BorderRadius is the corner radius applied to the border box when painting
// the background and border. It is a single (uniform) radius: the common real
// case (Tailwind `rounded-*`, pills, circles) sets all four corners equal.
// Differing per-corner radii are approximated by the last-applied value
// (documented in FIDELITY.md). A px length is used as-is; a percentage
// resolves against the box's smaller side at paint time. Zero (the initial
// value) means square corners.
BorderRadius Length
// Auto-margin flags: a margin explicitly set to `auto` centres or pushes the
// box; distinct from a 0 margin.
MarginLeftAuto bool
MarginRightAuto bool
// Overflow per axis (not inherited; initial value visible). Any non-visible
// value clips descendant painting to this box's padding box.
OverflowX Overflow
OverflowY Overflow
// Positioning that affects normal flow.
Float Float
Clear Clear
// CSS position and the box-offset properties. Top/Right/Bottom/Left are Auto
// by default (the initial value of each offset). ZIndex is meaningful only
// when ZIndexAuto is false; the initial value is auto (paint in tree order).
Position Position
Top Length // Auto by default
Right Length // Auto by default
Bottom Length // Auto by default
Left Length // Auto by default
ZIndex int
ZIndexAuto bool // true == "auto" (the initial value)
// Flex container properties (meaningful when Display == DisplayFlex).
FlexDirection FlexDirection
FlexWrap FlexWrap
JustifyContent Justify
AlignItems AlignItems
AlignContent AlignContent
// Gaps between flex lines/items and between grid tracks. RowGap is the
// cross-line / block-axis gap; ColumnGap is the main-axis / inline-axis gap.
RowGap Length
ColumnGap Length
// Flex/grid item properties (meaningful for a child of a flex/grid container).
FlexGrow float64
FlexShrink float64
FlexBasis Length // Auto == "auto" (use the item's width/content)
Order int // reorders items within a line (ascending)
AlignSelf AlignSelf
// Grid container properties (meaningful when Display == DisplayGrid).
GridTemplateColumns []TrackSize
GridTemplateRows []TrackSize
GridAutoRows TrackSize
GridAutoColumns TrackSize
GridAutoFlow GridFlow
GridTemplateAreas [][]string // row-major grid of area names ("" == empty)
JustifyItems AlignItems // inline-axis alignment of items in their cell
// Grid item placement (meaningful for a child of a grid container).
GridColumnStart GridLine
GridColumnEnd GridLine
GridRowStart GridLine
GridRowEnd GridLine
GridArea string // named area this item is placed into (via grid-area)
JustifySelf AlignSelf
// CustomProps holds the element's resolved CSS custom properties (--name ->
// raw value). It is inherited from the parent and overridden by matched
// rules; var() references consult it at computed-value time. Nil until an
// element (or an ancestor) defines a custom property.
CustomProps map[string]string
// Background image layers (gradients and url() bitmaps) and their paint
// parameters. Each list is indexed per layer (first-listed paints on top);
// a shorter size/position/repeat list repeats its last value. All nil == no
// background image (only the solid Background colour paints).
BackgroundImages []BgImage
BackgroundSize []BgSize
BackgroundPosition []BgPosition
BackgroundRepeat []BgRepeat
// BoxShadows are the element's box-shadow layers (first-listed paints on top).
BoxShadows []BoxShadow
// Opacity is the element's group opacity in [0,1]; HasOpacity distinguishes a
// genuine opacity from the zero value (an unset Style is fully opaque).
Opacity float64
HasOpacity bool
}
Style is the fully-computed style of an element, after cascade + inheritance.
type StyleMap ¶
StyleMap maps each element node to its fully-computed style.
func CascadeVW ¶
CascadeVW computes a style for every element in the tree rooted at root, applying the user-agent stylesheet, author rules from every <style> element plus any externalSheets (already-fetched CSS text, e.g. <link> stylesheets), and inline style="" attributes, with proper specificity and inheritance. @media width queries are evaluated against viewport width vw.
type TextAlign ¶
type TextAlign uint8
TextAlign is the horizontal alignment of inline content in a block.
const ( // AlignLeft is the initial value. AlignLeft TextAlign = iota // AlignCenter centres each line. AlignCenter // AlignRight right-aligns each line. AlignRight // AlignCenterBlocks centres inline content like AlignCenter and additionally // centres a definite-width block/table child within its container — the legacy // behaviour of the <center> element and the align="center" attribute (browsers' // -moz-center / -webkit-center). A plain text-align:center author rule never // produces it, so standards-mode blocks are unaffected. AlignCenterBlocks )
type TrackKind ¶
type TrackKind uint8
TrackKind is the sizing function of a single grid track.
const ( // TrackAuto sizes the track to its content (initial for implicit tracks). TrackAuto TrackKind = iota // TrackPx is a fixed pixel size. TrackPx // TrackPercent is a percentage of the container's content size on that axis. TrackPercent // TrackFr is a flexible fraction of the leftover space. TrackFr // TrackMinMax is a minmax(min,max) range; Min and Max are non-nil. TrackMinMax )
type TrackSize ¶
type TrackSize struct {
Kind TrackKind
Px float64 // TrackPx
Percent float64 // TrackPercent (0..1)
Fr float64 // TrackFr
Min, Max *TrackSize // TrackMinMax bounds
}
TrackSize is one column or row sizing function of a grid template.
type WhiteSpace ¶
type WhiteSpace uint8
WhiteSpace controls collapsing of whitespace and wrapping.
const ( // WSNormal collapses runs of whitespace and wraps at the block width. WSNormal WhiteSpace = iota // WSPre preserves spaces and newlines and does not wrap (as in <pre>). WSPre )