Element CSS
Write scoped styles on their owning element, with grammar, permissions, storage, and cascade behavior.
Watch the video
Chapters and transcript Captions are included.
Styling an element needs that no dedicated setting can say, such as a decorative ::after arrow, a transform, an
inner element's color, a state or a media rule, is kept on that element as its own small stylesheet. It is visible,
editable, resettable and saved with the page in Developer mode › Advanced › CSS. Nothing about it lives in the
theme, post meta or options.
Files: includes/element-css.php (server: parser, checks, canonical form, capability gate, public output, migration
helpers), assets/element-css.js (the same parser for the browser, plus the editor's view and routing),
assets/editor.js (the CSS section, the live stylesheet, the theme-rule list, save serialization).
Tests: tests/element-css-cases.json (cases both parsers must agree on byte for byte),
tests/element-css-unit.mjs (node), tests/element-css-test.php (native WordPress),
tests/element-css-native-browser.mjs (a real site in Chromium).
Saved markup#
<a class="btn" href="/join/" data-ke-css="&::after{content:"\2192 ";margin-left:.4em}@media (max-width:767px){&::after{display:none}}">Join</a>
- One attribute,
data-ke-css, on the element it styles. Its value is canonical element CSS (grammar below), escaped as any attribute value is. Always write<,>,&and"as entities: WordPress's kses splits tags on a literal>, so a child combinator left raw would cut the tag apart.WP_HTML_Tag_Processor::set_attribute()and the editor do this; the server also re-escapes every value before kses as a backstop. - Duplicating an element duplicates its CSS. Drafts, revisions, History, shared header/footer parts and linked sections carry it with the markup. Identical CSS on several elements shares one rule set; no ids are needed.
- Linked sections (
data-ce-component): CSS on the section, a field or a repeated item follows the instance. CSS on a node the template owns can't be carried into a newer template, so that instance renders exactly as saved instead. - Dedicated settings keep their own storage and stay authoritative: the inline
stylefor Desktop, anddata-ke-hover,data-ke-focus,data-ke-tablet(-hover|-focus),data-ke-phone(-hover|-focus)for states and screen sizes (see DEVELOPER.md). Element CSS never repeats a property a setting holds in the same context (see Apply, below).
Public output#
cantata_edit_render() (pages, parts, revisions and previews) prints, after the responsive settings' stylesheet:
<style data-ke-css>[data-ce-k="3f9a0c1d2b7e"]:not(#ke-css)::after{content:"\2192 ";margin-left:.4em}@media (max-width:767px){...}</style>
and adds a render-only data-ce-k (12 hex of the SHA-256 of the canonical CSS) to each styled element. data-ce-* is
never stored: both sanitizers strip it, and the editor removes the server's copy when editing starts and draws its own.
Each region rendered (the page, each shared part) has its own <style data-ke-css>.
Cascade: the settings win (inline style; data-ke-* rules are !important). Element CSS beats theme rules: its scope
[data-ce-k=…]:not(#ke-css) has specificity (1,1,0) before anything the author adds. A theme rule with !important
still wins unless element CSS uses !important too.
An element whose own id is literally ke-css would not match its scope; don't use that id.
Grammar#
Validated in the browser on Apply and again in PHP on every save, draft, publish, part, AI and HTML-field path.
- A sheet is rules and
@mediablocks (one level). No other at-rules (@import,@font-face,@keyframes,@layer…). - Every selector contains
&(the element) exactly once, at the start of its compound (&,&.is-open,&:hover), never inside a functional pseudo-class. What is styled is always the element or inside it:- right after
&only descendant () and child (>) combinators:& + x,& ~ x,.ctx & + x,&:hover ~ pare refused (they would style the element's siblings); - once the selector is inside the element, sibling combinators are allowed:
& .jet-filter + .jet-filter,& > li ~ li,& h2 + p span(a sibling of something inside the element shares its parent, which is the element or inside it). A selector without&,div&, or&in:is()/:not()/:where()/:has()is refused.
- right after
- Context before
&only conditions the match:.card:hover &,body.home &,.nav > &,.page:has(.banner) &. - Simple selectors: type,
*,.class,#id,[attr],[attr="v"](= ~= |= ^= $= *=, optionali/s). Pseudo-classes: hover, focus, focus-visible, focus-within, active, visited, link, any-link, checked, disabled, enabled, required, optional, target, empty, first/last/only-child, first/last/only-of-type, placeholder-shown, open, nth-child / nth-last-child / nth-of-type / nth-last-of-type (2,odd,even,3n+1). Functional pseudo-classes, which only decide whether a compound matches and never choose what is styled::is(),:not(),:where(): comma lists of complex selectors with any combinators, as CSS has them (:is(.e-n-tab-title > .e-n-tab-title-text, .e-n-tab-title)keeps its specificity, unlike splitting it);:has(): comma lists of relative selectors, which may start with>,+or~(&:has(:hover) .title,&:has(> img),& .card:has(+ .card)); a:has()inside another:has()is refused, as in CSS;- no
&and no pseudo-element inside any of them; they nest at most 16 deep (a deeper selector is refused with a normal error before any stack limit; the parser is recursive descent over a bounded input, the same in PHP and JS). One trailing pseudo-element: ::before, ::after, ::marker, ::placeholder, ::selection, ::first-line, ::first-letter, ::file-selector-button (:before/:afterbecome::before/::after). No CSS escapes in selectors.
@media:[screen|print|all] and (feature:value) and …, comma lists. Features: width, min/max-width, min/max-height (px, em, rem), hover, any-hover, pointer, any-pointer, orientation, prefers-reduced-motion, prefers-color-scheme, prefers-contrast. The editor's screen sizes are(max-width:1024px)(Tablets) and(max-width:767px)(Phones).- Declarations: any property
[a-z-]+or custom property--name, exceptbehavior,-ms-behavior,-moz-binding. Values may use any ordinary tokens and functions,!important, and quoted strings (with\hexescapes, for icons). Refused:<,>,{,}, backquote or a backslash outside strings;javascript:,vbscript:,expression(;image(),image-set(),-webkit-image-set(),src(),element()(strings or elements as images); quoted strings inside functions other thanattr(),counter(),counters(),format(),local(). url(): relative, root-relative,http:/https:, ordata:image/(png|gif|jpeg|webp|avif|svg+xml). No",<,>or backslash inside (percent-encode them); not//hostwithout a scheme.- Comments are allowed while editing and not stored.
- Limits: 16 KB canonical per element (32 KB of text with comments), 200 rules, 100 declarations a rule, 20 selectors a rule, functional pseudo-classes nested 16 deep.
What the server checks is shape and safety, not meaning: PHP does not know whether color: bogus is a color. The
editor asks the browser (CSS.supports) on Apply (see below); anything else that writes data-ke-css (migrations,
the AI API, the HTML field) gets the structural and security checks only, and should check meaning in a browser itself.
Canonical form (stored; JS and PHP write it byte for byte the same): selector{prop:value;prop:value!important},
no optional whitespace (single spaces where a value or selector needs them, none around , or inside brackets),
combinators unspaced (&>span, & .a+.b, :has(>img), :is(.a>.b,.c)), strings double-quoted with <, > written as \3c , \3e and every hex
escape ending in its space ("\2192 "), url("…") quoted, media as @media (max-width:767px){…}, rules in the order
written, property names lower case (custom properties keep their case), values otherwise as typed.
Who can change it#
Changing element CSS needs unfiltered_html (filter cantata_edit_element_css_cap), the same permission as the HTML
field. Others see the CSS section read-only, with the reason. On save, an account without it may keep or delete
element CSS exactly as stored (and duplicate an element that has it) but a new or changed value refuses the whole save
with a 403 and nothing is written. Invalid element CSS refuses the whole save with a 400 and its first error, never
dropped while the rest saves. Outside the editor (wp-admin, the REST posts endpoint), saves that WordPress filters with
kses keep only element CSS this post already had (content, Kindly draft, or one of its last 50 revisions).
The editor (Developer › Advanced › CSS)#
- The text shows everything that styles the element: its settings first (
/* Settings */: inline style as& {}, Hover/Focus as&:hover {}, Tablets/Phones inside their@media), then/* This element's own CSS */. - Apply CSS (or Ctrl/Cmd+Enter) checks everything first. Any error, with its line, and nothing is applied. A
The browser checks meaning too: a declaration a setting would own with a value the browser doesn't accept
(
color: bogus) fails Apply with its reason and nothing changes, instead of a setting that silently isn't there. Other declarations the browser doesn't accept are kept as written (another browser's fallback, a vendor prefix) and reported byroute()inunsupportedwith their kind (vendororunknown); custom properties are always accepted. How the editor words or blocks theunknownones is the editor's choice (editor.js). This is the current browser's judgment only: another browser may accept less or more. Then each declaration goes to its owner:- in
&with no media: properties the controls own (VISUAL_PROPS) and properties already in the inline style go to the inline style; - in
&:hover,&:focus, or&/&:hover/&:focusinside exactly(max-width:1024px)or(max-width:767px):VISUAL_PROPSgo to the matchingdata-ke-*; - everything else, and any value a setting can't hold (a
data:picture, a value the controls refuse), is element CSS. A setting's property written with!importantin a context (for example to beat a theme rule that uses!important, which no setting can) stays element CSS there, every declaration of it in that context, and Apply says so; an inline!importantalready on the element stays inline. The theme rule list flags rules that use!important, and Copy as override keeps their!important. The result replaces the inline style, everydata-ke-*anddata-ke-csstogether, so nothing is left in two places. One Apply is one Undo step.
- in
- Reset text shows the element as it is now. Remove its own CSS clears
data-ke-cssonly (settings keep their resets). - Theme rules for this element lists each rule in the page's readable stylesheets whose selector picks the element
in any state or for its pseudo-elements: the selector, file (or
<style id>),@media/@supports/@layer/@container, the state, whether it applies at the current window width, and its declarations. Copy as override puts the declarations into the text under&with the same state and pseudo-element (an ancestor's state is kept as context,.card:hover &::after) inside the same@media, to change and apply. Cross-origin sheets that can't be read are counted. - Custom styles reviews (Style's look and Advanced) list "Custom CSS: n rules" with a way to it.
- While editing, a stylesheet in
<head>(#ce-element-css-live, never saved) draws element CSS keyed by an editor-onlydata-ce-css;&:hover/&:focusalso show while Style previews that state.
Migration helpers (PHP)#
cantata_edit_element_css_parse( string $css ): array->ok, canonicalcss,errors([ line, message ]),rules.cantata_edit_element_css_normalize( string $css ): string-> canonical, or''when invalid or empty.cantata_edit_element_css_merge( string $existing, string $add ): string|WP_Error-> both, canonical,$addlast.cantata_edit_element_css_values( string $html ): array->[ [ 'tag', 'value' ] ]in document order.cantata_edit_render_element_css( string $html ): string-> what visitors get.wp kindly css check <file|->prints{ ok, css, rules, errors }(exit 1 when invalid). Read-only.
Recipe: find the element in the stored HTML (page post_content and _cantata_edit_draft, part content and drafts)
with WP_HTML_Tag_Processor, set_attribute( 'data-ke-css', $merged ), and write it with wp_slash() (WordPress
unslashes post content, which would eat the backslash of "\2192 "). Check the rendered page matches before removing
the bespoke theme rule. Prefer a dedicated setting (inline style, data-ke-*, classes/looks) whenever one covers the
property; element CSS is for the rest.
Conditional cascade ownership#
When a self rule uses a condition native settings cannot represent, such as @media(max-width:900px) or &:active, Apply keeps every competing newly routed declaration in the element's Advanced CSS in source order. This includes related shorthand and longhand families. Promoting only the base declaration into inline style, or a supported state into the native important layer, would disable the conditional rule. Unrelated declarations still use native settings. Descendant and pseudo-element rules keep their separate owners.
An existing inline or native state setting keeps its current precedence. Callers of KindlyElementCss.route supply inlineProps and stateProps (state suffix to existing property names) from the current element to distinguish those existing settings from newly imported CSS. The editor supplies both automatically. This does not add custom breakpoints to native settings or add !important to CSS exceptions. Native controls remain available for an intentional subsequent override; the combined Advanced CSS view makes both owners inspectable.
Regression: tests/element-css-unit.mjs covers dependency routing, shorthand families and composition fixpoints. tests/element-css-cascade-browser.mjs uses an isolated WordPress fixture, native REST draft/publish/reload, and Chromium computed styles across widths, hover and reduced motion. It removes its synthetic page and revisions.
Competing property families include cross-prefix CSS relationships: font also sets line-height, logical dimensions depend on writing-mode, and grid-gap/grid-row-gap/grid-column-gap are aliases of the current gap properties. Their newly imported competing declarations stay together in Advanced CSS when a custom condition cannot use native settings. Existing native settings retain their prior precedence; Reset those settings deliberately if the intended change is to move that precedence into scoped conditional CSS.