Styling
What works and what does not
There is no CSS engine. Each style is translated property by property into GPUI's own style
object, and GPUI lays everything out with flexbox (or a simple grid) in pixels. <style> blocks
work for class rules, which are translated the same way.
<div class="btn" style="padding: 8px 16px; border-radius: 8px">Click</div>
<style>
.btn {
background-color: #111111;
color: #ededed;
}
.btn:hover {
background-color: #1c1c1c;
}
</style>
What works
- Inline
styleandstyle:directives. Box shorthands (padding: 8px 16px,margin,border-width,border-radius,gap,inset) expand to GPUI's longhands. <style>rules made of classes, at most one tag, and:hover,:activeor:focus-visible:.btn,.btn.primary,.a, .b,div,div.card. They're scoped per component, like Svelte's DOM output. The rule with more classes wins; with equal classes, a rule with a tag beats one without; after that, the later rule wins. Inlinestylebeats every plain class rule, but a class:hover,:activeor:focus-visiblerule still applies on top of it while the element is in that state.class:directives and dynamic class strings restyle live.hover="...",active="..."andfocus-visible="..."attributes, for hover, press and keyboard-focus styles set directly on the element.@mediablocks over the window'swidth,heightandorientation, restyled as the window is resized (see Media queries).var(--token)andvar(--token, fallback)in class rules and inline styles, on any property. Values come from a:root { --token: #fff; }rule in any component's<style>, or fromset_css_vars({ token: '#fff' }), which makes a theme switch one call (see Theming with CSS variables).- Any CSS colour syntax: hex,
rgb(),hsl(), named colours. display: flex | gridand the flexbox properties,position: absolute,overflow: hidden | scroll | auto,opacity,cursor,white-space,text-overflow,font-size,font-family,font-weight,text-align,text-decorationandvisibility: hidden.
What doesn't work
- Units other than
pxandrem(em,vh,vw), and%orautoanywhere exceptwidth,height,min-*andmax-*. These are dropped with a warning, somargin: 0 autocan't center anything. - Shorthands GPUI has no field for:
flex: 1(useflex-grow: 1withflex-basis: 0, which is whatflex: 1means),border: 1px solid #fff(useborder-widthandborder-color),font: 12px Menlo,backgroundwith anything but a single colour, andbox-shadow. Abackground: linear-gradient(...)paints nothing but still blocks clicks to what is behind it. - Unitless
line-height:line-height: 1.5means 1.5 px, so give it a unit. - A bare number on a property that takes a word or a colour (
color: 123456,background: 0) is dropped with a warning. !importantis ignored: the declaration applies as if it were not there, so it can't make a class rule beat inlinestyle. The one place it counts is on a variable in a:rootrule, which it puts aboveset_css_vars.display: nonehas no effect. Use{#if}, orvisibility: hiddento keep the box.- Any other selector: combinators (descendant,
>,+,~), pseudo-classes besides:hover,:activeand:focus-visible, pseudo-elements,:global, attribute selectors, nesting, and every at-rule but@media(see Media queries). The compiler refuses them with a warning.:root, also written:global(:root), is accepted for the variables it declares (see Theming with CSS variables). transform,transition,z-index,letter-spacingandfont-styleare ignored, mostly without a warning.- Only text properties inherit from a parent (colour, font,
line-height,text-align,white-space,text-overflow,line-clamp,text-decoration), plususer-selectandselection-color. An<svg>gets its parent'scolorfrom the renderer, but not the parent's:hovercolour. - Whitespace in the text of your markup collapses as it does in HTML, so a sentence wrapped over
several indented lines is drawn with single spaces (from the next release, 0.6.0; before it the
line break and the indentation are drawn too). The compiler does this, and only for text written
in the template: a string that comes from an expression (
{message}) is drawn as written, line breaks included, as is the text inside<pre>and<textarea>. A no-break space is kept, as in HTML.<svelte:options preserveWhitespace />turns the collapsing off for a component, whose text is then drawn exactly as written.white-space: preandpre-wrapdo not exist. - Assume the rest of CSS is missing too.
Working, standard CSS semantics
Values are logical pixels unless noted, and rem is 16 px, GPUI's fixed rem size. Only the listed
keywords are recognised.
- Layout:
display: flex | grid;flex-direction: row | column;flex-wrap: wrap | wrap-reverse | nowrap;flex-grow,flex-shrink,flex-basis;gap,row-gap,column-gap. - Alignment:
align-items: center | start | end | stretch | baseline;align-self: center | start | end | stretch | baseline;align-content: center | start | end | space-between | space-around | space-evenly | stretch | normal;justify-content: center | start | end | space-between | space-around | space-evenly. Theflex-prefixed forms work too. - Sizing:
width,height,min-width,min-height,max-width,max-heightin px,%orauto;aspect-ratioas a number or16 / 9. - Spacing:
padding,marginand their four sides, with 1 to 4 value shorthands. - Position:
position: relative | absolute;top,right,bottom,left;inset. - Overflow:
overflow,overflow-x,overflow-yashidden | scroll | auto.autois treated asscroll, and the two behave the same. - Paint:
background-color(orbackgroundwith a single colour),color,border-colorin any CSS colour syntax;opacity;border-widthand its four sides;border-radiusand its four corners, with 1 to 4 value shorthands;border-style: solid | dashed;outline-width,outline-color,outline-offset. - Text:
font-size;font-family, passed through as written, so give one family name;font-weight(100–900,normal,bold);text-align: left | center | right | start;line-heightin px or rem;white-space: nowrap | normal;text-overflow: ellipsis;text-decoration: underline | line-through | none. - Visibility:
visibility: hiddenpaints nothing, keeps the layout box and leaves the tab order. - Interaction:
cursorasdefault,auto,pointer,text,vertical-text,grab,grabbing,move,all-scroll,crosshair,not-allowed,no-drop, the*-resizefamily,copy,aliasandcontext-menu(moveandall-scrollshow the closed hand;help,wait,progress,cell,zoom-inandzoom-outare ignored);pointer-events: none | auto;user-select: none | text | auto;:hover,:activeand:focus-visiblerules in<style>, the last applying after keyboard focus only, like CSS.
Working, non-standard CSS semantics
These are accepted, but they mean something different from what CSS would.
- Unitless numbers are pixels:
padding: 12,font-size: 18. max-content,min-contentandfit-content(...)onwidth/height/min-*/max-*read asauto.grid-template-columns: 3andgrid-template-rows: 2take a number: the count of equal tracks.grid-column-minandgrid-row-min(min-content | max-content) are GPUI's own properties for each track's minimum.justify-contentandalign-contenttakebetween,aroundandevenlyas aliases forspace-between,space-aroundandspace-evenly.position: fixedlays out exactly likeabsolute.text-overflow: ellipsis-starttruncates from the left.line-clamp: Nworks unprefixed, with nodisplay: -webkit-boxneeded.font-weightalso takesthin,extralight,light,medium,semibold,extrabold,black(the hyphenated spellings too) and any number from 1 to 1000. A name GPUI doesn't know, such asbolder, falls back to 400.hover="..."andactive="..."are attributes that take the same CSS text asstyleand apply while the pointer is over, or pressing, the element. They're an inline form of:hoverand:active:<div style="color: #a1a1a1" hover="color: #ededed">equals.x { color: #a1a1a1 }plus.x:hover { color: #ededed }. When both exist, the attribute wins.focus-visible="..."is the same for:focus-visible.scrollbar-colormakes GPUI paint a thumb on anoverflow: scrollcontainer or a<virtual-list>, andscrollbar-width(in px, default 6) sizes it. There is no track, so of the standardthumb trackpair only the first colour applies. Without a colour GPUI paints no scrollbar at all, and the thumb never takes the pointer.- A scroll area inside another one needs
pointer-events: auto. GPUI scrolls every scroll container under the pointer on each wheel event, inner and outer at once, so a list inside a scrolling page moves a little while the page carries it away. An explicitpointer-events: automakes the inner one occlude what is behind it, so only it takes the wheel (there is no handing over to the page at its ends, asoverscroll-behavior: containwould do). Behind it, hover and clicks stop too. keyboard-focus-dim: falsekeeps an element at full opacity when the window has the dim on (render(App, { keyboardFocusDim: true }), see the guide's focus section).selection-colorsets the colour of the text-selection highlight, the job CSS gives to::selection.- Mouse events never bubble, and an element that paints a background or is
position: absoluteblocks clicks to whatever is behind it. Puthitbox="self"on the clickable element, and clicks on its badges, icons and images pass straight through to it. Descendants that take input keep their own hitbox: a child with its own handler (other thanonlayout,onscrollchange,onmotioncompleteandonhighlight, which take no pointer), focusable elements (tabindexorautofocus), scroll containers, and the input-taking elements (button,input,textarea,code,diff,markdown,virtual-list,anchored). Apointer-eventsyou set yourself still wins. onclickis the primary button alone, as in the DOM. A right or middle click isonauxclick, wheree.isRightClicktells the two apart ande.x/e.yare window coordinates, so a menu rendered through<Portal>can be placed right at them. macOS's ctrl+click arrives as an ordinaryonclickwithe.modifiers.ctrlset, so a handler that wants the platform's secondary click checks for it.hitbox="self"shields aux clicks like any other.- Animation goes through the
motion={{ initial, animate, transition }}prop, which animatesleft,top,right,bottom,width,height,opacityandborderRadiusnatively, with durations in seconds.
Theming with CSS variables
Class rules are compiled ahead of time, but a var() in one resolves at runtime. Declare the
variables in a :root rule, in any component's <style>, and every component reads them, as in a
browser:
<div class="card">
<text class="badge">new</text>
</div>
<style>
:root {
--surface: #111111;
--ink: #ededed;
--border: #242424;
}
.card {
background-color: var(--surface);
color: var(--ink);
border-width: 1px;
border-color: var(--border);
}
.card:hover {
border-color: var(--ink);
}
.badge {
padding: var(--badge-pad, 2px 6px);
}
</style>
var() works on any property, pixel-only ones included, and inside inline style= too.
var(--name, fallback) uses the fallback while the variable is unset. Without a fallback, the
declaration is dropped and a warning names the variable once.
A :root rule follows the browser's rules wherever a window can:
- The variables exist once the component's file is imported, mounted or not. Where two files declare the same one, the file imported later wins, and a component's own rule wins over those of the components it imports.
- A variable may read another (
--accent-ink: var(--accent)). One that reads an unset variable with no fallback, or that is part of a cycle, counts as unset itself. @mediaaround the rule works as around any other (see Media queries), so@media (max-width: 700px) { :root { --gap: 8px; } }changes--gapas the window is resized.:global(:root)means the same.- Under
render_hot, an edit to the rule shows on save, like any other style.
What a browser would honour and a window can't is refused when the component compiles, with a warning naming the file:
- A property that is not a variable (
:root { color: red; }). In a browser it styles<html>, and a window has no element above your app's own root, so style that one or passrootStyle. :rootwith anything attached (:root.dark,:root:hover), and@mediaqueries a window has no answer for, such asprefers-color-scheme. Switch a palette withset_css_varsinstead.- A variable declared on any other selector (
.card { --pad: 4px; }). A browser scopes it to that element and its descendants; here every variable is global, and one written in an inlinestyleis ignored.
Switching a theme
set_css_vars() sets variables from JS, so a palette is one object and a theme switch is one call:
<script>
import { set_css_vars } from 'gpuix-svelte';
const LIGHT = { surface: '#ffffff', ink: '#171717', border: '#e5e5e5' };
const DARK = { surface: '#111111', ink: '#ededed', border: '#242424' };
let { dark } = $props();
$effect(() => set_css_vars(dark ? DARK : LIGHT));
</script>
It restyles only the elements that use a variable, all in one frame, and a call that changes
nothing does nothing. Keys work with or without the --. Setting the palette from an $effect
like the one above is fine: the check for unset variables runs after your effects have, so one the
effect sets is never reported.
A value set this way wins over a :root rule's, because the DOM build writes it to
<html>'s inline style, which a browser ranks above a rule. Setting it to null (or '') takes
it away again, and the :root value, if there is one, shows through. So a :root rule can hold
the defaults and set_css_vars only what a theme changes. A variable declared !important in
:root is the exception, there as in a browser: set_css_vars can't override it.
Media queries
Nothing native evaluates CSS, so @media is answered by gpuix-svelte from the window's size. A
block applies while its query holds, nests like any other at-rule (inner blocks need every query on
the way down), and keeps its place in the source order, so a rule under @media wins over an
equal rule written before it and loses to one written after it, as in a browser:
<style>
.cards { display: flex; flex-direction: row; gap: 16px; }
@media (max-width: 700px) {
.cards { flex-direction: column; gap: 8px; }
}
@media (min-width: 1200px) and (orientation: landscape) {
.cards { gap: 24px; }
}
</style>
What a query may say:
widthandheight, asmin-width: 600px,max-width: 599px,width: 600px, or the range syntax (width >= 600px,600px <= width < 900px), inpx,remorem(both 16 px) or a unitless0.orientation: portrait | landscape(a square window is portrait).andbetween features, a comma between alternatives,notoronlyin front, and the media typesscreenandall;printand the other types never match.
Anything else (prefers-color-scheme, hover, pointer, a vw length, or) has no answer in a
window. As in a browser, such an alternative in a comma list never matches while the others still
count; a block none of whose alternatives can be answered is refused with a warning. In the DOM
build the same block is CSS the browser evaluates. A query no size can change is settled when the
component compiles: @media screen applies as if it were not there, @media print drops its
rules. The window is read through the one poll window_size uses, every 100 ms while any element
depends on a query, and the dependent elements are restyled only when a query's answer changes.
media_query('(max-width: 700px)') in the Guide answers the same
question from JavaScript.
Seeing it for yourself
The repository's styling playground renders each style string
next to what GPUI made of it, in three groups: reads like CSS, looks like CSS but is not, and
GPUI-only. It is one ordinary component,
StylingPlayground.svelte, so copy it
into a project made with npm create gpuix-svelte and point app.ts at it, or run
npm run demo:styling in a clone of the repository.