API
css.positionTry
Named @position-try fallbacks for anchor positioning.
export type positionTry = <const T extends PositionTry>(rule: T) => CSSVariableKey;
export const positionTry: positionTry;positionTry() creates an @position-try rule and returns its name. The rule describes a fallback position for an anchor-positioned element, and the element uses it through the positionTryFallbacks property when it does not fit where it is. The rule is defined next to the styles that use it and referenced by name, instead of being written in a global stylesheet.
Only properties that place the element are allowed:
positionAnchorandpositionArea- Insets:
inset,top,left,insetInlineand the other inset properties - Margins:
marginand its longhands - Sizing:
width,height,inlineSize,blockSizeand theirminandmaxforms - Self-alignment:
alignSelf,justifySelfandplaceSelf
Any other property is a type error, and no-unknown-css-properties reports it in the editor.
Example
A menu opens below its trigger. When there is no room below, it moves to the right of the trigger with a shorter height:
import * as css from '@plumeria/core'
const right = css.positionTry({
positionArea: 'right',
maxHeight: 200,
marginTop: 0,
marginLeft: 8,
});
const styles = css.create({
menu: {
position: 'absolute',
positionAnchor: '--trigger',
positionArea: 'bottom',
maxHeight: 320,
marginTop: 8,
overflow: 'auto',
positionTryFallbacks: right,
},
});@position-try --pt-xucneogw {
position-area: right;
max-height: 200px;
margin-top: 0px;
margin-left: 8px;
}
.xobmrwib { position: absolute; }
.x54fk64s { position-anchor: --trigger; }
.xa1mxswp { position-area: bottom; }
.xit236su { max-height: 320px; }
.xxb8i1k0:not(#\#):not(#\#) { margin-top: 8px; }
.x87fkz9f { overflow: auto; }
.xlst8ed0:not(#\#) { position-try-fallbacks: --pt-xucneogw; }Moving to the opposite side is already covered by keywords: positionTryFallbacks: 'flip-block' moves the menu above its trigger and swaps its margins as well. Use positionTry() when the fallback changes more than the side, such as the size or the alignment. Names and keywords can be listed together, and the browser tries them in order.
Usage in another file
A definition can be exported and imported like any other value:
import * as css from '@plumeria/core'
export const right = css.positionTry({
positionArea: 'right',
maxHeight: 200,
marginTop: 0,
marginLeft: 8,
});import * as css from '@plumeria/core'
import { right } from './fallbacks'
const styles = css.create({
menu: {
positionTryFallbacks: right,
},
});An @position-try rule is emitted only when its name is used in css.create, so a definition nothing uses adds nothing to the stylesheet.