Styling
A small CSS: four fixed layers, a closed set of selectors and properties, custom properties for everything a theme decides, and transitions that cannot run layout.
By the end of this chapter you can load an application stylesheet, select a widget and its parts, know which properties resolve and which are refused, swap a theme and a density at run time, and animate the properties the toolkit lets you animate.
#root { flex-direction: column; background: var(--gb-bg); color: var(--gb-text) }
#bar { height: 44px; padding: 0 16px; gap: 12px; align-items: center }
.screen { flex-direction: column; gap: 16px; padding-top: 16px }
button.danger:hover { background: var(--gb-button-danger-bg-hover) }
private final Stylesheet styles =
Stylesheet.resource(CascadeLayer.APPLICATION, Hello.class, "app.css");
@Override public List<Stylesheet> stylesheets() {
var sheets = new ArrayList<>(Controls.stylesheets(Theme.NORD_DARK));
sheets.add(styles);
return sheets;
}
Stylesheet.resource reads a file beside the class and parses it at start-up.
A malformed stylesheet is a CssSyntaxException with a position, because a
window that opens unthemed and says nothing is worse than one that refuses to
open. Stylesheet.parse(layer, text) does the same for a string.
A sheet read with Stylesheet.resource may start with @import, which reads
another sheet beside it, as its url()s are: @import "tokens.css";, or with
a media list, @import url(narrow.css) (max-width: 600px);, whose rules then
apply under that condition. The imported rules come before the importing
sheet’s own, so the importer wins a tie. An import that names a sheet that is
not there, or one already being imported, is dropped with a warning. A sheet
parsed from text has nowhere to look beside, so its imports are reported and
skipped. An @import after any other rule is ignored, as CSS ignores it.
Strict and lenient sheets
A sheet that asks for something the subset has not got is a different case from a malformed one, and what happens depends on whose sheet it is.
| Sheet | Parsed | A selector, pseudo-class or at-rule outside the subset |
|---|---|---|
the toolkit’s own (controls.css, the themes, the content sheets) | strict | refuses the sheet with a CssSyntaxException |
an application’s (Stylesheet.resource or Stylesheet.parse in any other layer) | lenient | drops that rule, with one warning naming the selector, the sheet and the line |
WARN app.css, line 42: dropping "lane::before": unsupported pseudo-element
A rule nested inside another that asks for something outside the subset,
a { &::before { … } } say, is dropped by itself with a warning, and the rest of
the rule holding it is read.
A strict sheet also refuses any timing function but the design system’s three
curves, ease-enter, ease-exit and linear, so the toolkit’s own controls
all move on them. A lenient sheet may write any curve CSS has; see
Transition and animation.
A lenient sheet keeps what it dropped in Stylesheet.dropped(), and
StyleLint reports each one as a DROPPED_RULE finding. A property the
engine has not got at all, such as float, is warned about once per
property per sheet when the sheet is read, with the first line it appears on.
A malformed sheet (an unclosed block, a declaration with no value) is refused
in both modes, which is what lets hot reload keep the
last good sheet while you type. The mode can be chosen explicitly with
Stylesheet.parse(layer, text, ParseMode.STRICT).
Run with -Dgoldberry.css.lint=true while developing and the launcher lints
your sheets each time it reads them (Logging).
The cascade: four layers
public enum CascadeLayer { TOOLKIT_BASE, THEME, APPLICATION, INLINE }
| Layer | Holds | Who writes it |
|---|---|---|
TOOLKIT_BASE | controls.css: every control’s metrics and structure, reading colours through var(--gb-*) | the toolkit, Controls.baseStylesheet() |
THEME | nord-light.css or nord-dark.css: the custom properties, plus the density and scrollbar sheets | the toolkit, Theme.NORD_DARK.load() |
APPLICATION | your stylesheets | you |
INLINE | what only a widget can compute, through Styled.restyle | a widget author |
At equal specificity a later layer wins, so an application rule beats a theme rule beats a base rule. Specificity is CSS’s: an id beats a class beats a type.
The four layers’ order cannot be argued with by a stylesheet that loads late.
Inside APPLICATION, an application may order its own rules with @layer:
@layer reset, vendor; names layers in the order they rank, @layer vendor { … } puts rules in one, and @import url(vendor.css) layer(vendor); puts a
whole sheet in one. A rule in no layer ranks above every layer, and a later
layer above an earlier one; !important turns that round. A layer ranks the
way the four layers do, after specificity: it decides between rules of equal
specificity, so a vendor’s .btn loses to your .btn whichever loads last,
but a vendor’s .btn.primary still beats your .btn, where CSS would let
yours win. @layer in a theme or in the toolkit’s sheets ranks nothing.
INLINE has no style= attribute behind it. It is the layer a widget writes
into for a value no selector can express, such as the position of the third
of five segments.
Selectors
button { } /* type */
.primary { } /* class */
#save { } /* id */
panel text { } /* descendant */
row > button { } /* child */
label + text-input { } /* the sibling just after */
heading ~ paragraph { } /* any sibling after */
field:has(> :invalid) { } /* what is below it */
checkbox:hover check-indicator { } /* a part, under a state */
:root { --gb-accent: #b48ead }
list-row:nth-child(even) { } /* where it sits among its siblings */
.steps > :last-child { }
The pseudo-classes are a closed set. A typo such as :hovered is refused in
a strict sheet and dropped with a warning in a lenient one, rather than being
a rule that never matches.
| Pseudo-class | True when | Set by |
|---|---|---|
:hover | the pointer is over the node or a descendant | the router |
:active | a press is held on the node or a descendant | the router |
:focus | the node has keyboard focus, however it got it | the router |
:focus-visible | the node has focus from the keyboard | the router |
:focus-within | the node or something under it has keyboard focus | the router |
:disabled | the widget says it is disabled | the widget |
:enabled | the widget is not disabled | the widget |
:checked | the widget says it is on | the widget |
:indeterminate | a tri-state control is mixed | the widget |
:invalid | a field or its control failed validation | the widget |
:affixed | an affix has pinned itself | the widget |
:drag-over | a compatible drag is over the node | the router |
:window-inactive | the window and its popups lack keyboard focus | the router |
:root | the root element, where a theme hangs its properties | structure |
The structural pseudo-classes say where a node sits among its parent’s children:
| Pseudo-class | True when |
|---|---|
:first-child, :last-child | it is the first, or the last, of its parent’s children |
:only-child | it is its parent’s only child |
:nth-child(An+B) | it is at position An+B, counting from 1; odd and even work |
:nth-last-child(An+B) | the same, counting from the last child |
:nth-child(An+B of S), :nth-last-child(An+B of S) | it matches the selector list S, and is at position An+B among the siblings that match it |
:first-of-type, :last-of-type, :only-of-type, :nth-of-type(An+B), :nth-last-of-type(An+B) | the same five, counted among the siblings of its own type |
The siblings are the children of the node’s parent element, which is also
what > reads. A composition widget is an element with one child, like an
unstyled <div> around one node, so a card a stateless wrapper builds is the
only child of that wrapper. When a parent’s children are added, removed or
reordered, only the children whose structural answer changed are restyled,
and a sheet with no structural pseudo-class restyles nothing.
:hover and :active reach the whole ancestor chain, which is what lets
checkbox:active check-indicator light the glyph when the label is pressed.
The router refuses to set :hover or :active on a disabled widget, which
is how a disabled control stays dull without :not(:disabled):hover.
+and~read the siblings before a node, the same children>and the structural pseudo-classes count.:has()reads the other way: `field:has(>- invalid)
is a field whose own child is invalid,card:has(:checked)a card with a checked box anywhere inside it, andheading:has(+ paragraph)a heading a paragraph follows. Its selectors may start with>,+or~, and start below the node when they do not. A:has()` inside another is refused, as in CSS.
These are the selectors that make one node’s style depend on another node.
Under a sheet that writes + or ~, a change to a node restyles its
siblings; under one that writes :has(), a change restyles the nodes above
it (and, for :has(+ …) and :has(~ …), the siblings before them) whose
type a :has() sits on. A state a widget owns, :checked say, is read before
the frame is styled, so card:has(:checked) changes in the frame the box is
checked. Sheets that write neither, which are the toolkit’s own, pay nothing
for them.
:is(), :where() and :not() take a list of selectors, each of which may
have combinators of its own: :is(button, toggle):hover,
list-row:not(.selected), :is(card > header) text. :is() matches when any
of them does and :not() when none does; each is as specific as the most
specific selector in its list. :where() is :is() with no specificity at
all, which makes it the way to write a default any rule can override. A
selector in the list that is outside the subset, :is(a[href]), drops the
rule it is in, where a browser would ignore that one entry.
A rule that counts siblings through of S restyles every child of a parent
that rebuilds, and the siblings of a child whose state changes, since which of
them match S may have moved. A sheet without one pays nothing.
:focus-within moves with the keyboard: a move between two controls in one
field leaves the field’s answer alone, so a rule on it does not flicker.
Handles.onFocusWithin tells a widget the same thing as a notification.
Not in the subset: attribute selectors, and generated content such as
::before and ::after. A widget’s properties stay out of the
cascade, so a state a stylesheet should see is a class or a pseudo-class; a
part is selected by its type name, and generated content is a widget.
A rule may hold rules, as CSS’s nesting writes them:
card {
padding: 12px;
&:hover { background: var(--gb-surface-hover) }
> header { font-weight: 600 }
.compact & { padding: 6px }
@media (max-width: 600px) { padding: 8px }
}
& is the rule it is inside. A nested selector without one is relative to it:
header means & header and > header means & > header. When the outer
rule has several selectors, & matches any of them, and is as specific as the
most specific, as :is() is. @media may sit inside a rule and holds
declarations for that rule’s selector as well as rules of its own. Order is
kept: declarations written after a nested rule come after it in the cascade.
Every nested rule is read into an ordinary one when the sheet is parsed, so
the selector structure is ready when the sheet is loaded. Nested rules can
also use @media and @supports.
:window-inactive is the window’s state rather than a node’s, so it is written
on whatever the rule is about: spinner:window-inactive or
:window-inactive .badge. A window that is covered or minimized already stops
its animations by itself; this is for motion an application would rather pause
while the user works in another window.
.attention:window-inactive { animation-play-state: paused }
Parts
A control with two surfaces a theme must style differently is two cascade nodes. The inner one is a part: it has a type name, matches pseudo-classes and takes properties, and it cannot be written in a document.
checkbox { gap: 8px }
checkbox check-indicator { border-radius: 4px }
checkbox:checked check-indicator { background: var(--gb-checkbox-bg-checked) }
toggle-track:checked toggle-thumb { transform: translate(16px) }
scroll:hover scroll-thumb.vertical { width: 10px }
check-indicator, toggle-track, toggle-thumb, slider-value,
scroll-thumb, field-message and tab-panel are parts. Each widget’s
chapter lists its own under Styling.
Two parts also answer to the pseudo-element a browser’s sheet would write for
them. A field’s value is ::placeholder while it shows the placeholder, and
so is a select’s while nothing is chosen; a field’s text-selection and a
document view’s selection-layer are ::selection:
text-input::placeholder { color: var(--gb-text-muted) }
text-input:focus::placeholder { color: transparent }
::selection { background: var(--gb-accent-bg-hover) }
A state written before the :: is the control’s. text-input::placeholder
matches the part below the text-input, which is the same node
text-input text-value.placeholder selects; a pseudo-element ends its
selector, and one inside :is() or :has() is refused, as in CSS.
::selection takes background: the highlight is drawn behind the text, and
the text keeps its colour so it stays readable.
An editable field that checks spelling can style its wavy underline with
::spelling-error. The cascade also recognizes ::grammar-error for widgets
that provide a matching part. Spell checking
Properties
The subset is closed. A property the engine does not know is ignored, and the sheet naming it warns once per property when it is read. A known property with a value it cannot read is dropped with a warning that quotes the text.
Box and layout
.toolbar {
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
align-items: center;
gap: 8px; /* or gap: 4px 8px, row then column */
padding: 8px 12px;
margin: 0 auto;
width: 100%;
min-height: 32px;
overflow: hidden;
}
.toolbar > button { flex: 1 0 120px; align-self: flex-end }
.badge { position: absolute; top: 4px; left: 4px }
flex-direction, flex-wrap, flex, flex-grow, flex-shrink,
flex-basis, justify-content, align-items, align-self,
align-content, gap, row-gap, column-gap,
padding and its four sides, margin and its four sides, width, height,
min-width, max-width, min-height, max-height, aspect-ratio,
position, inset, top, right, bottom, left, overflow and
display. The layout engine reads these properties.
flex expands as CSS says: flex: 1 is 1 1 0%, flex: auto is
1 1 auto, flex: none is 0 0 auto, and flex: 120px is 1 1 120px.
margin: auto centres on the main axis.
aspect-ratio is auto, a number, or width / height, and sizes the axis the
box does not fix.
Every box is a flex box, so display has three values. display: none takes
the node and everything under it out: nothing is laid out, painted, hit or
reachable by the keyboard, and its elements stay mounted with their state, as a
background tab’s do. display: contents takes the node’s own box away and lays
its children out as its parent’s; whatever the widget draws itself, its text
or its icon, goes with the box. display: flex is what every box is already.
block, inline and grid are dropped with a warning.
visibility: hidden leaves the box’s own drawing out and keeps its room: it is
not painted, the pointer passes through it, and the keyboard skips it.
collapse is read as hidden. pointer-events: none lets the pointer through
to whatever is under the box, which still draws. Both inherit, and both are
per box: a child that says visibility: visible or pointer-events: auto
under a parent that said otherwise is drawn, or hit, as usual.
user-select: text makes the words of a text, and of any other box that
draws words and does not handle the pointer itself, selectable: a drag selects,
a double click takes a word and a triple click the whole box, and Ctrl+C
(Cmd+C on macOS) copies when nothing focused takes the key. user-select: all
selects the whole box at a click. auto leaves a plain text unselectable,
since a label is pressed rather than selected. A rich-text takes the property
as its own selectable: text and all turn selection on, and none turns
it off. In a markdown-view or an html-view, none keeps a press from
selecting, all makes any click select the whole document, and text and
auto are the default. The highlight is --gb-selection. One selection is kept
per window: a press elsewhere clears it, and a press on a button leaves it
alone, so a Copy button can act on it. user-select inherits, and
-webkit-user-select is the same property.
z-index is auto or a whole number, and orders a box among its siblings: a
higher one is drawn later and found first by the pointer, and equal ones keep
document order. It applies to every box, positioned or not, since every box is
a flex item. It orders siblings and nothing else, so a box cannot rise above
its parent’s siblings; something that must cover the whole window is an
overlay.
Lengths are px, %, em, rem, ch, ex, the absolute units in,
cm, mm, Q, pt and pc, at 96 pixels to the inch, and the viewport
units vw, vh, vmin and vmax. ch is the advance of the digit zero and
ex the x-height, both in the face the element is drawn in. A viewport unit is
a percentage of the window; a desktop window has one size, so svh, lvh and
dvh are all vh. A sheet that writes a viewport unit is restyled when the
window is resized, and one that writes none is not.
calc(), min(), max(), clamp(), round(), mod(), rem(), abs()
and sign() are read wherever a length, a number, an angle or a time is,
nested as deep as needed, with e and pi as numbers: rotate(calc(45deg * 2)),
transition-duration: calc(var(--gb-motion-fast) * 2) and
translate(calc(-50% + 4px)) all work. Each is worked out when the style is
computed. A colour’s components are not read this way, and
rgb(calc(255 / 2) 0 0) is dropped. One that
mixes a percentage with a length, like calc(100% - 8px), is dropped with a
warning by width, margin, padding, gap and the rest of the layout
properties, because the layout engine sizes a box by a length or by a
percentage and never by both; give the parent padding instead, or a child
flex: 1. The same goes for min(), max() and clamp() over a percentage
and a length, which cannot be compared before the box is laid out.
The logical properties are read as the physical ones they are with a horizontal
writing mode. The inline axis follows direction and the block axis runs
from top to bottom. margin-inline,
margin-block, padding-inline, padding-block, inset-inline and
inset-block take a start and an end, one value being both;
margin-inline-start, padding-block-end, inset-inline-start and the
rest are one side each; inline-size, block-size and their min- and
max- forms are the width and the height.
place-content is align-content then justify-content, place-items is
align-items then justify-items, and place-self is align-self then
justify-self, one value being both. justify-items and justify-self are
read and change nothing, as CSS says for a flex item, which every box is; a
value CSS would refuse is still dropped. justify-content: stretch is the
start, as it is on any flex container.
overflow takes one value for both axes or two, across then down, and
overflow-x and overflow-y set one each: visible, clip, hidden,
scroll and auto. clip cuts the content off like hidden and nothing
can scroll it. A box is clipped on both axes when either axis is anything but
visible; CSS clips one axis only for visible beside clip.
.chip { padding-inline: 8px; margin-block: 2px 4px }
.centred { place-items: center }
.strip { overflow: hidden auto }
order places a box among its siblings: lower first, document order among
equals, 0 unless a rule says otherwise. Layout, painting and the pointer
follow it; the keyboard’s Tab order stays the order the children are written
in.
direction: rtl runs a box right to left, and its children with it, since it
inherits. A row starts at the right, margin-inline-start and the other
logical properties name the right side, and text-align: start places a line
at the right; left and right stay the sides they name. It is also the base
direction of the box’s text: which side a line starts at, and where the
punctuation and spaces between a right-to-left word and a left-to-right one
go. writing-mode is not in the subset.
.toolbar.rtl { direction: rtl }
.toolbar .primary { order: -1 } /* first, whatever the markup says */
A border takes room, outside the padding, as in CSS: a box’s content starts
inside its border and then its padding. box-sizing says what width and
height measure. Its initial value here is border-box, so a box given a
size keeps that size whatever border it has and its content gives way;
content-box adds the padding and the border to the size instead. A box
sized by its content grows by its border either way.
Math functions divide equal units to produce a number, such as
calc(24px / 8px). Multiplication requires a number on one side.
Text flow
.cell { white-space: nowrap; text-overflow: ellipsis; overflow: hidden }
.readout { text-align: end }
link { text-decoration: underline }
.misspelled { text-decoration: wavy underline var(--gb-danger) }
.log { white-space: pre-wrap; overflow-wrap: anywhere }
white-space: normal | nowrap | pre | pre-wrap | pre-line. A paragraph
never collapses spaces or newlines, so the five keywords are two behaviours:
pre-wrap and pre-line wrap as normal does, and pre stays on one line
as nowrap does. pre-line keeps runs of spaces CSS would fold into one.
overflow-wrap: normal | anywhere | break-word cuts a word wider than the
whole line between grapheme clusters; word-break: normal | break-all may cut
any word at the edge of the line. A text-area cuts its rows the same way, and
its caret, selection and scroll follow the cut. Both inherit.
text-overflow: clip | ellipsis controls what a nonwrapping line shows.
text-align accepts start, center, end, left, right and justify.
text-align: justify sets every line of a paragraph but its last flush with
both edges, sharing the room left on the line among its word gaps. A line a
newline ends is a paragraph’s last too, and so is one with no gap; those sit
at the start. text-justify: none turns it off, and auto and inter-word
both mean the word gaps. A field being edited is never respaced, so its caret
stays on the glyphs: a text-area with justify keeps its lines at the
start.
text-decoration is a shorthand for four properties, written in any order:
text-decoration-line: none | underline | line-through, one or both;text-decoration-style: solid | double | dotted | dashed | wavy;text-decoration-color, which follows the text’s colour until one is written;text-decoration-thickness: auto | from-font | <length> | <percentage>. A percentage is of the element’s font size, andautoandfrom-fontboth take the face’s own thickness.
The shorthand resets the parts it does not name, so text-decoration: underline after text-decoration: wavy red line-through draws a solid
underline in the text’s colour. text-underline-offset: auto | <length> | <percentage> is not part of it. It moves an underline’s top edge to that
distance below the baseline and leaves a line-through where it is. overline
is not drawn, and a declaration that asks for it is dropped.
A decoration reaches the text inside the element that declares it, together
with its style and colour. button.link { text-decoration: underline dotted }
draws a dotted line under the label inside the button. Dots, dashes and waves
keep their rhythm across a line written in several styles, so a bold word in
the middle of an underlined sentence does not restart the pattern.
line-clamp: <n> | none, or -webkit-line-clamp, keeps the first n lines
of a paragraph and draws an ellipsis at the end of the last one when more were
cut. The box is measured at the lines it keeps. Unlike a browser, which also
wants display: -webkit-box and overflow: hidden beside it, the property
alone does it. It does not inherit.
Text in a right-to-left script reads from the right wherever it is: a Hebrew word in an English sentence, a number in an Arabic one, a whole field of either. Each line is placed in reading order, and the caret, a click and a selection follow what is on screen; a selection across a change of direction is highlighted in a piece on each side.
A box’s text takes its base direction from direction. unicode-bidi says
otherwise:
| Value | The base direction of the box’s text |
|---|---|
normal | The box’s direction. The initial value; embed and isolate read the same, since a box’s text is always a paragraph of its own |
plaintext | Each paragraph’s first letter with a direction, and the box’s direction for a paragraph with none. text-align: start and end then follow each paragraph |
bidi-override | The box’s direction, for every character: right-to-left script is drawn left to right under ltr. isolate-override reads the same |
.message { unicode-bidi: plaintext } /* each message reads its own way */
.code { unicode-bidi: bidi-override; direction: ltr }
unicode-bidi does not inherit. In a text-input or a text-area the
arrow keys move through the text in reading order: Left moves on in a
right-to-left paragraph and back in a left-to-right one.
hyphens: none | manual | auto controls discretionary breaks in
Markdown and HTML prose.
manual is the initial value and honours soft hyphens. auto also uses
the bundled English patterns when the view’s lang selects English.
The property inherits.
Typography
.heading { font-family: Inter; font-size: 15px; font-weight: 600; line-height: 20px }
.mono { font-family: "JetBrains Mono" }
.note { font-style: italic }
font-family, font-size, font-weight, font-style, line-height, and the
font shorthand.
A weight is any number from 1 to 1000, or normal (400) or bold (700), and
CSS weight matching chooses the nearest available weight when the family
provides static faces.
font-style: oblique is refused because nothing shears a glyph.
font-family: Inter, sans-serif takes the first name and discards the rest.
Upright Inter and JetBrains Mono are variable faces, and any weight a
stylesheet writes is drawn at that weight: font-weight: 500 is a 500, and
bold a 700. The italics are separate files at 400 and 600 and draw the
nearest of the two. font-stretch (a keyword such as condensed, or a
percentage from 50% to 200%) sets the width of a face that has a width axis,
and font-variation-settings sets any axis a face has by its tag:
.display { font-variation-settings: "opsz" 32 }
.tight { font-stretch: 87.5% }
An axis a face does not have is ignored, and a value past an axis’s range is
brought back inside it. Both inherit, and font resets them.
A font-size is a length, a percentage of the parent’s size, smaller or
larger (a fifth either way from the parent’s), or one of CSS’s keywords from
xx-small to xxx-large, stepped from the root’s size, which is what medium
is. line-height is a length, a number times the size, or normal, which is
1.2 times the size.
font: [style] [weight] <size>[/<line-height>] <family> sets all five, and
puts back to their initial values the ones it does not name: the style and
the weight to normal, the line height to normal.
letter-spacing is added after every character and word-spacing to every
space, each normal or a length, which may be negative. Both inherit as the
pixels the parent computed, so 0.1em on a heading stays the heading’s tenth
in its labels. The text wraps, measures and takes the caret with the spacing it
is drawn with. A percentage is not read for either. font leaves both alone.
text-transform draws text in uppercase, lowercase or capitalize, and
inherits. It changes what is painted and never the text a widget holds, so a
field keeps its value, copies it as typed, and its caret lands where it
would. Every character is cased into exactly one character, which is what
keeps the caret true: ß stays ß in capitals.
text-shadow is a comma list of shadows under the text, the first on top,
each <x> <y> [<blur>] [<color>]; with no colour it is the text’s own. It has
no spread and no inset, as in CSS, and inherits. A shadow with no blur is the
text drawn again at its offset; a blurred one is drawn once into a picture of
its own and kept, so a label that does not change pays for its blur once.
font-feature-settings sets OpenType tags such as "tnum" 1, "liga" 0.
font-variant-numeric reads numeric variants such as tabular-nums and
oldstyle-nums. Both properties inherit and font resets them.
Colour
panel { background: var(--gb-surface); color: var(--gb-text) }
.faded { opacity: 0.5 }
.wash { background-color: rgba(136, 192, 208, 0.2) }
background, background-color, color and opacity.
A colour is a hex value (#rgb, #rgba, #rrggbb, #rrggbbaa); rgb() or
rgba(), with commas or with spaces and a slash before the alpha
(rgb(0 0 0 / 50%)); hsl(), hwb(), lab(), lch(), oklab(), oklch()
or color() in srgb, srgb-linear, display-p3 or xyz; one of the 148
named colours; transparent; currentcolor; or a var(). A colour outside
sRGB is clamped into it. currentcolor is the element’s own color, so
border: 1px solid currentcolor draws the border in the text’s colour; it is
fixed when the style is computed, so a color transition moves the text and
not the border. opacity is a number from 0 to 1 or a percentage.
opacity on a node
with children renders the subtree into a layer and composites it once, so two
overlapping children do not show through each other. A translucent leaf
keeps the cheap path.
Two colours can be made from others. color-mix() mixes two in a colour
space, OKLab when it names none, as much of each as its percentage says:
.primary:hover { background: color-mix(in oklch, var(--gb-accent), black 12%) }
.scrim { background: color-mix(in srgb, var(--gb-surface) 60%, transparent) }
A colour with no percentage takes what the other leaves of 100%, and two that
add up to less than 100% leave the mix that much transparent. A space with a
hue, oklch, lch, hsl or hwb, may say shorter, longer, increasing
or decreasing hue.
A colour function may also start from another colour and name its channels:
r g b in rgb(), h s l in hsl(), h w b in hwb(), l a b in
lab() and oklab(), l c h in lch() and oklch(), r g b or x y z in
color(), and alpha in all of them. Each is the origin’s value as a plain
number, so calc() can work on it:
.soft { background: oklch(from var(--gb-accent) calc(l + 0.15) c h) }
.ghost { border-color: rgb(from var(--gb-accent) r g b / 40%) }
Neither reads currentcolor.
Backgrounds and gradients
.glow { background: radial-gradient(circle at top, #88c0d066, transparent 60%), var(--gb-surface) }
.tint { background-image: linear-gradient(to right, #bf616a33, transparent) }
.running { background: repeating-linear-gradient(90deg, #a3be8c 0 6px, transparent 6px 12px);
animation: march 400ms linear infinite }
@keyframes march { to { background-position: 12px 0 } }
background is a comma list of layers, the first drawn on top, with the
colour in the last one. background-image sets the layers and keeps the
colour; background-color sets the colour and keeps the layers; background
resets both, and background: none is no fill at all.
A layer is linear-gradient(), radial-gradient(), conic-gradient() or
their repeating- forms:
- A linear gradient runs
toa side or a corner, or at an angle (deg,rad,grad,turn, with0up and turning clockwise). It runs to the bottom when it says nothing. - A radial gradient is a
circleor anellipse, sized byclosest-side,closest-corner,farthest-sideorfarthest-corner(the default) or by lengths, and centredata position. - A conic gradient turns clockwise round a centre, from the top or
froman angle, centredata position. Its stops are angles, or percentages of a turn. A repeating one repeats its first period round the turn. - A stop is a colour with up to two positions, each a length or a percentage. Stops are placed as CSS places them. A position alone between two stops is a hint: where the two colours are half and half.
inand a colour space, first in the list, blends the stops in that space rather than in sRGB:srgb,srgb-linear,display-p3,lab,lch,oklab,oklch,xyz,xyz-d50,xyz-d65,hslorhwb. A space with a hue takesshorter,longer,increasingordecreasing hue.
.ring { background: conic-gradient(from -90deg, var(--gb-accent) 0 72%, var(--gb-border) 0) }
.dawn { background: linear-gradient(in oklch to right, #f59e0b, #3b82f6) }
.glare { background: radial-gradient(white, 20%, transparent) }
Each layer is placed in one of the box’s rectangles and cut to another:
background-origin and background-clip, each border-box, padding-box
or content-box. The padding box is the box less its border and the content
box is the padding box less its padding, where its text starts. A layer starts inside the border and is drawn under it too; the
colour is cut to the last layer’s clip, so background-clip: padding-box
keeps a fill out from under a translucent border. Every rectangle keeps the
box’s rounded corners, tightened by the sides it is inside.
background-position, or background-position-x and -y alone, places
each layer with one to four words: lengths, percentages, left, center,
right, top and bottom, and a side with an offset from it, right 8px bottom 4px. A percentage is of the room the layer leaves, so 100% puts a
picture’s far edge on the box’s and moves a gradient, the size of its box,
not at all; only a length moves a gradient. background-size and
background-repeat size and tile a url() picture: repeat, no-repeat,
repeat-x, repeat-y, space (whole tiles, spread edge to edge) and
round (tiles stretched until a whole number fit), one for both axes or one
for each. Every one of these is a comma list matched to the layers, a short
list repeated. The background shorthand takes them all, the position and a
size as <position> / <size>, and one or two boxes: one is both the origin
and the clip, two are the origin and then the clip. It also takes scroll,
which is what a layer does anyway; there is no background-attachment
property and no fixed or local. background-position is animatable,
which is how the stripe above marches.
An image URL resolves beside the stylesheet that names it. Use
Stylesheet.resource for packaged images, or give Stylesheet.parse an image
resolver. A renderer caches resolved pictures for reuse. A missing picture
leaves the other layers and the background colour visible.
Border, outline and shadow
card { border: 1px solid var(--gb-border); border-radius: 8px; box-shadow: var(--gb-elevation-1) }
.tab { border: 1px solid var(--gb-border); border-bottom: none }
button:focus-visible { outline: 2px solid var(--gb-focus); outline-offset: 2px }
border and border-top, -right, -bottom, -left, each
<width> || <style> || <color> in any order. border-width, border-style and
border-color take one to four values, and each side has its own
-width, -style and -color. border-radius takes one to four corners,
and after a / one to four vertical radii, which make each corner a quarter
ellipse; each corner also has its own longhand, border-top-left-radius and
the rest, which takes one radius or a horizontal and a vertical one. A radius
is a length, a percentage, or a calc() of both: a percentage is of the box’s
width across and of its height down, so border-radius: 50% makes a circle
of a square box and an ellipse of any other. The inside of a border’s corner
is the outside less each side’s own width, so a corner between a thick side
and a thin one is an ellipse inside.
outline, outline-width, outline-style, outline-color and
outline-offset. An outline may be any style a border side may be, auto
being solid, and outline-style: none takes it away. box-shadow
is a comma list of shadows, the first on top, each
[inset] <x> <y> [<blur>] [<spread>] <color>.
A border takes room outside the padding, as piece 35 says. A shorthand that
names no style is solid, and the style none or
hidden is a side with no width.
dashedis dashes three widths long with gaps the same, stretched so a side starts and ends on a dash. A square corner is a dash’s end; a rounded corner is one dash shared by the two sides.dottedis round dots as wide as the side, two widths apart, with one on every corner.doubleis two lines a third of the width each, with the middle third empty.insetandoutsetare lit from the top left: aninsetside is a darker tone of its colour on the top and the left and a lighter one on the bottom and the right, andoutsetthe reverse.grooveandridgeare two bands of half the width each, lit one way outside and the other way inside.
An outline is drawn outside the box and takes no room either, so a focus ring cannot move a control by appearing. Its style is always drawn solid.
A shadow is drawn as a stack of rounded rectangles whose alphas ramp across the
blur. An outer shadow is drawn under the background and only outside the box.
An inset shadow is drawn over the background and under the border, inside the
padding box: the box’s own shape, moved by the offset and shrunk by the spread,
is the hole it is seen around, and on a rounded box it follows the inside of
the curve.
A border may also be a picture cut in nine,
border-image:#menu-panel { border-image: url("classpath:/ui/panel.png") 48 fill / 48px stretch } button { border-image: url("classpath:/ui/button.png") 12 fill / 12px } button:hover { border-image-source: url("classpath:/ui/button-hover.png") }
border-image-sliceis one to four numbers or percentages, top first, in the picture’s pixels: they cut it into four corners, four edges and a middle, andfilldraws the middle too.border-image-widthsays how wide each side’s pieces are drawn: a number of border widths (1, the default), a length, a percentage, orautofor the slice’s own size.border-image-outsetpushes the picture out past the box by lengths or border widths.border-image-repeatisstretch(the default),repeatorroundfor the edges and the middle, one value or one per axis.border-image-sourceisnoneor aurl(), read as a background picture is,@2xvariant and#xywh=fragment included. Theborder-imageshorthand is<source> <slice> / <width> / <outset> <repeat>, in any order with the slashes after the slice, and resets what it does not name.The corners are drawn at the size the width gives, so a 48-pixel corner drawn 48 wide is the picture pixel for pixel, at 200% from its
@2xvariant. The picture replaces the border’s colours, and the border’s widths still decide the layout. While the picture loads, or when it cannot be read, the border is drawn from its colours. A border image is not clipped byborder-radius. Because it is a property like any other, a state’s rule swaps the sprite, as the:hoverrule above does.
clip-path keeps part of a box and drops the rest, its children included:
inset() with optional rounded corners, circle(), ellipse(),
polygon() and path(), in the border box or in the box named after the
shape (padding-box, content-box). A box name alone clips to that box. The
pointer finds the box only inside the shape.
.avatar { clip-path: circle(50%) }
.ticket { clip-path: inset(0 12px round 6px) }
.flag { clip-path: polygon(0 0, 100% 0, 85% 50%, 100% 100%, 0 100%) }
mix-blend-mode combines a box with what is drawn under it: multiply,
screen, overlay, darken, lighten, color-dodge, color-burn,
hard-light, soft-light, difference, exclusion and plus-lighter.
isolation: isolate keeps what blends inside a box from blending with what
is outside it. A clipped, blended or isolated box is drawn as a group, like a
box with opacity; mask-image and the hue family of blend modes are not
in the subset.
filter changes how a box and everything in it look, as one picture: blur(),
brightness(), contrast(), grayscale(), hue-rotate(), invert(),
opacity(), saturate(), sepia() and drop-shadow(), applied in the order
written. A drop-shadow() follows the shape of what is drawn, its rounded
corners and its transparent parts, where box-shadow follows the box. A
blurred or shadowed box draws past its edges by about three times the radius.
.disabled-card { filter: grayscale(1) opacity(0.6) }
.sticker { filter: drop-shadow(0 2px 3px rgb(0 0 0 / 35%)) }
backdrop-filter takes the same functions and runs them over what is drawn
under the box instead, inside its border and its rounded corners. The box
itself, its background, border and children, is drawn over the result as
usual, so a translucent background tints the frost:
.toolbar {
background: rgb(236 239 244 / 35%);
border-radius: 12px;
backdrop-filter: blur(24px) saturate(110%);
}
What is under the box is everything drawn before it in the window, or in the
group it is inside: a box with opacity, filter, clip-path,
mix-blend-mode or isolation: isolate keeps its frost to what is inside the
group, and so does a box with rounded corners that clips its children. The
frost follows the box’s opacity and transform. At the window’s edge the
edge pixels are repeated, so a bar along the edge is as frosted there as in
its middle. A blur reads past the box by about three times its radius, so a
change that close to a frosted box repaints the whole box.
A video or a 3D canvas is not drawn into the window’s picture, so it cannot be frosted. Over one, a frosted box shows its own background colour at full strength, the opaque fallback a frosted surface is designed with. Without a GPU the video’s own fallback picture is what is on screen, and it is frosted. A frosted box seen through another frosted box shows without its own frost.
Under @media (prefers-reduced-transparency: reduce), give the box an opaque
background and backdrop-filter: none.
Transform
panel.turned { transform: rotate(20deg) }
panel.grown { transform: scale(1.4); transform-origin: left top }
toast.entering { transform: translate(0, 16px) }
transform with translate, translateX, translateY, scale, scaleX,
scaleY, rotate, skew, skewX, skewY and matrix, and
transform-origin.
translate, rotate and scale are properties of their own as well:
translate: 0 -2px, rotate: 90deg (or z 90deg; no other axis), scale: 0.96 or scale: 1 0.5, each none by default. They apply before
transform, translate first, then rotate, then scale, about the same origin,
and each is set and animated by itself, so a hover can lift a card that a
keyframe is turning. transform-box says what the origin and a percentage
are measured against: border-box (and stroke-box and view-box, a box
being no SVG shape) or content-box (and fill-box), inside the padding.
Layout runs first and the matrix moves the result, so a transform costs no layout pass. Hit testing maps the pointer back through the same matrix, so a scaled button responds where it is drawn.
Transition and animation
button { transition: background-color var(--gb-motion-fast) ease-enter }
button:active { transition: background-color 0ms }
@starting-style { toast { opacity: 0; transform: translate(0, 16px) } }
@keyframes pulse { from { opacity: 0.4 } to { opacity: 1 } }
skeleton { animation: pulse 1.2s linear infinite }
transition and its four longhands, transition-property, -duration,
-timing-function and -delay; animation and its eight longhands:
animation-name, -duration, -timing-function, -delay,
-iteration-count, -direction -fill-mode and -play-state. The longhands are comma
lists that pair up by position with transition-property, the shorter lists
repeated, as CSS pairs them. transition: all names every animatable property,
and a later entry for one of them wins over it. transition-property starts
out empty rather than all, so a duration on its own animates nothing until a
property is named.
The animatable properties are a closed whitelist: opacity,
background-color, background-position, border-color, border-radius,
outline-color, outline-offset, box-shadow, color, transform,
translate, rotate and scale. Every one of them is drawn, never laid out,
so a frame of motion never runs layout. border-radius moves corner by
corner; a transform transition leaves the three individual properties where
they are.
Two shadow lists move pair by pair, the shorter one
padded with transparent copies of the longer one’s shadows; an inner shadow
against an outer one swaps half-way.
transition: width 200ms is a dropped declaration with a warning naming it,
because animating a width would run layout on every frame.
The timing that applies is the one on the style being moved to, so the
two button rules above make a press snap and a release fade.
The design system’s curves are ease-enter, ease-exit and linear, and the
toolkit’s own sheets use nothing else. An application’s sheet may write any
curve CSS has: ease, ease-in, ease-out and ease-in-out as CSS defines
them, cubic-bezier(), steps() with any of its positions, step-start,
step-end and linear() with its stops. A curve may overshoot, and an
animated opacity stays between 0 and 1 when it does. A timing function that
cannot be read, cubic-bezier(2, 0, 0, 1) or steps(0), drops itself with a
warning naming it, and the rest of the declaration runs on the default
ease-enter.
Colours interpolate in OKLCH. Animated values
live in an overlay applied at paint and are never written back into the
computed style, so a transition retargeted halfway starts from where it is.
transition does not inherit.
@starting-style gives an element the style it transitions from on its
first frame. @keyframes names a sequence animation runs under the same
whitelist. Under reduced motion every transition collapses to zero and
keyframe animations do not run.
The desktop’s setting is read at start-up, and
-Dgoldberry.motion.reduced=reduce or =full overrides it.
A keyframe may name its own animation-timing-function: the curve from that
keyframe to the next, in place of the animation’s. A @keyframes block may
sit inside @media; the last block of a name whose condition holds is the one
that runs.
animation-play-state: paused stops an animation’s clock where it is, and
running starts it again from there; a paused animation asks for no frames.
A theme is chosen by swapping a stylesheet. A media query adjusts an existing sheet to the window or the desktop.
A box with a view-transition-name that layout moves or resizes is drawn
where it was, and travels to where it is now:
call-tile { view-transition-name: tile-7; transition: transform 300ms ease-out }
The name is the box’s identity, so a tile moved into another column still
travels from where it was; give each box its own. The move takes the box’s
transition for transform when it has one, and 250 ms ease otherwise.
Under reduced motion the box moves at once. A box that changes size is
stretched while it travels, and whatever is inside it moves with it.
Media queries
@media (max-width: 900px) { .sidebar { width: 200px } }
@media (prefers-color-scheme: dark) { :root { --brand: #88c0d0 } }
@media (prefers-reduced-motion: reduce) { .pulse { animation: none } }
@media screen and (min-width: 600px) and (max-width: 1200px) { }
| Feature | Asked of |
|---|---|
width, height, as min-/max- or a range like (width >= 600px) or (400px <= width <= 800px) | the window’s logical size, in px, em or rem (16px) |
aspect-ratio, as min-/max- or a range, 16/9 or one number | the window’s width over its height |
orientation: portrait | landscape | the same |
resolution, as min-/max- or a range, in dppx, x, dpi or dpcm | the window’s scale |
pointer, any-pointer: none | coarse | fine; hover, any-hover: hover | none | a mouse, until the application says renderer.input(MediaContext.Input.TOUCH) |
prefers-color-scheme: light | dark | the desktop’s theme, light where it does not say |
prefers-reduced-motion: reduce | no-preference | the renderer’s reduced-motion switch |
prefers-contrast: no-preference | more | less | custom | the desktop’s contrast switch; custom while it forces its colours |
forced-colors: none | active | Windows’ high-contrast mode |
prefers-reduced-transparency: reduce | no-preference | macOS’s reduce-transparency switch |
color-gamut: srgb | p3 | rec2020 | srgb holds: everything is drawn to an sRGB surface |
A feature written alone, (hover) or (prefers-contrast), holds unless its
value would be the one that means none. The desktop’s switches are read once,
when the application starts: the settings portal on Linux, the system
parameters on Windows, the workspace on macOS. One a desktop does not have
reads as off.
They combine with and, or, not, only and comma lists, and nest. The
media types all and screen hold and print does not. A query naming
anything else never holds and warns once; in a strict sheet it is refused.
The cascade re-runs when an answer changes: on a resize that crosses a breakpoint, when the desktop’s theme changes, and when reduced motion is switched. A resize that crosses none keeps every resolved style.
@supports holds rules that apply when its condition does: (property: value) asks whether this toolkit reads that property and would apply that
value, selector(…) whether it reads that selector, and not, and and or
combine them as CSS says. The answer is about the toolkit itself, so it is
worked out once, when the sheet is loaded: @supports (display: grid) is
false here, and a fallback written beside it is what applies. Anything else in
parentheses, font-tech() included, is false. @supports may hold @media
and may sit inside a rule.
A box can be a container, which its descendants’ rules can ask about the way
an @media rule asks about the window: container-type: inline-size answers
for its width, size for its width and height, and container-name gives it
names an @container can ask for. The size asked about is the container’s
content box, inside its border and padding.
.card { container-type: inline-size; container-name: card }
@container card (min-width: 360px) {
.card-body { flex-direction: row }
}
.card-title { font-size: clamp(14px, 5cqw, 22px) }
A query takes the features and range forms a media query has for the
window’s size: width, height, inline-size, block-size, aspect-ratio
and orientation. It asks the nearest container that answers for the axes it
reads, and does not hold before that container has been laid out. cqw,
cqh, cqi, cqb, cqmin and cqmax are a hundredth of the nearest
container’s size, and of the window’s where there is none. A frame whose
containers changed size is laid out a second time, never a third, so a
container whose size depends on its own queries settles over the next frame.
Cursor
button { cursor: pointer }
.splitter { cursor: ew-resize }
canvas { cursor: crosshair }
Every keyword CSS has: default, pointer, text, move, wait,
progress, crosshair, not-allowed, the resizes (ew-, ns-, nesw-,
nwse-, col-, row-, and the eight edges and corners from n-resize to
sw-resize), grab, grabbing, help, context-menu, cell,
vertical-text, alias, copy, no-drop, all-scroll, zoom-in,
zoom-out and none, which hides the pointer over the box. Without a picture
from the application, a shape the platform has no cursor for falls back to the
nearest one it has: grab and grabbing to move, the edges and corners to
the two-headed arrows, cell and the zooms to the crosshair, and help,
context-menu, alias and copy to the arrow.
The cursor rides on the painted box and inherits down the stack of rectangles under the pointer, not the element tree.
Custom properties and var()
:root { --gb-accent: #b48ead; --gb-scroll-line: 40px }
#revenue { --gb-chart-1: #b48ead }
.hint { color: var(--gb-text-placeholder, #4c566a) }
A custom property is declared on any node and inherits. var(--name) reads
it, with an optional fallback after a comma. Every colour a control draws
comes through a --gb-* token, so an application rule that redefines one on
:root restyles every control that reads it, and one that redefines it on
#revenue restyles one chart. The tokens that exist are listed in
The design system.
Inheritance
color, the font properties, line-height, white-space, text-align,
text-decoration, overflow-wrap and word-break pass down the element
tree. The layout properties,
background, opacity, transform, transition and the border do not.
ComputedStyle.INITIAL has black text on purpose, so a window with no
stylesheet looks like one. Set color on your root, as the showcase does with
#root { color: var(--gb-text) }. A control that says nothing still reads
right because controls.css sets color on it.
Every property also takes inherit, initial and unset. inherit copies the
parent’s value, even of a property that does not inherit: padding: inherit
copies the parent’s four sides. initial is the property’s initial value,
and unset is inherit for a property that inherits and initial for one
that does not. all takes the three and applies them to every property at
once. revert rolls a property back to what the toolkit’s own sheets give it,
as if the theme and the application had said nothing about it, and
revert-layer to what the layers below the declaration’s give it. With
nothing to roll back to, either is unset.
Restyle versus repaint
A repaint redraws what changed. A restyle throws every resolved style away,
re-reads Application.stylesheets() and rebuilds the renderer. The second is
much more expensive, and almost nothing needs it: a theme and a density, and
very little else.
@Bind(value = "app.theme", restyle = true) private String themeName = "dark";
A field declared restyle = true asks for a restyle when it is assigned, and
the toolkit calls Host.restyle() for you. Everything else that changes a
value asks for a repaint by itself. An application outside the model system
calls host.restyle() directly.
A restyle is not a full recompute of every node. Each element caches its resolved style and re-resolves only when the resolver changed, when the style it inherits changed, or when a pseudo-class or a rebuild invalidated its subtree.
Themes, density and scrollbars
@Override public List<Stylesheet> stylesheets() {
var sheets = new ArrayList<>(Controls.stylesheets(
settings.theme(), // Theme.NORD_LIGHT or Theme.NORD_DARK
settings.density(), // Density.REGULAR or Density.COMPACT
settings.scrollbars()
)); // Scrollbars.OVERLAY or Scrollbars.ALWAYS
sheets.add(styles);
return sheets;
}
Controls.stylesheets(theme), (theme, density) and
(theme, density, scrollbars) return the base sheet, the theme, and whatever
the other two add, in cascade order. Theme.NORD_LIGHT and Theme.NORD_DARK
are the two themes that ship, and a theme is a custom-property layer: the
base rules never name a colour.
Density.COMPACT is a handful of tokens on :root, and every control is 28 tall
instead of 32 with nothing in your tree mentioning a height.
Density.REGULAR ships no stylesheet at all, because regular is what the
toolkit already is.
Scrollbars.ALWAYS reserves a 12 px gutter beside scrolling content.
Following the desktop
@Override public void start(Host host) {
host.systemTheme().ifPresent(this::follow);
host.onSystemThemeChanged(this::follow);
}
private void follow(SystemTheme theme) {
actions.pickTheme(theme == SystemTheme.DARK ? "dark" : "light"); // a restyle = true field
}
host.systemTheme() answers LIGHT, DARK, or empty where the desktop has
no such setting, and empty is a different answer from light.
The toolkit chooses nothing with the answer. A Linux build without the desktop bus
headers cannot ask at all, and says so through
Goldberry.capabilities().contains(Capability.SYSTEM_THEME).
Text scale
The renderer scales text between 90% and 150% without scaling the boxes, which
is the condition every control is built to survive.
The switch is WidgetRenderer.textScale(double), on the renderer an
application builds itself. The launcher does not expose it.
An application sets the scale its windows open at with textScale(), and
changes it while running with host.textScale(1.25): every window draws its
text at the new size from the next frame. The value is clamped to 0.9–1.5.
Offscreen.of(w, h).textScale(1.5) renders a tree at a scale for a test.
Read more
- Sizing with CSS: the layout half, in the Layout part