Start · Sprachen · JavaScript · Referenz · CSSPositionTryRule

CSSPositionTryRule

Schnittstelle

Stellt eine <code>@position-try</code>-At-Regel im CSSOM dar, also eine benannte Ausweich-Position für per CSS Anchor Positioning verankerte Elemente.

seit JavaScript Chrome/Edge 125+, Safari 26+; Firefox: noch nicht Kategorie: webapi

Signatur

interface CSSPositionTryRule extends CSSRule

Beschreibung

CSSPositionTryRule gehört zum CSS Anchor Positioning-Modul. Eine @position-try --name { … }-Regel legt eine alternative Positionierung fest (z. B. „oberhalb statt unterhalb des Ankers“). Der Browser nutzt sie, wenn ein verankertes Element (Tooltip, Popover, Dropdown) mit der Standardposition aus dem Viewport oder seinem Containing Block ragen würde. Welche Alternativen geprüft werden, steht in der Eigenschaft position-try-fallbacks.

Im CSSOM taucht jede solche Regel als CSSPositionTryRule in CSSStyleSheet.cssRules auf. Das Interface erbt von CSSRule und bringt zwei eigene, nur lesbare Eigenschaften mit:

  • name: Der dashed-ident-Name der Regel als string, z. B. "--custom-bottom".
  • style: Ein CSSPositionTryDescriptors-Objekt mit den Deklarationen der Regel. Die Eigenschaft selbst kann man nicht neu zuweisen, die einzelnen Deskriptoren darin aber schon ändern, zum Beispiel rule.style.positionArea = "top".

In der Praxis braucht man das Interface, um Ausweich-Positionen per Skript zu prüfen, zur Laufzeit anzupassen (etwa Abstände abhängig von Nutzereinstellungen) oder neue Regeln mit insertRule() anzulegen. Zum Deklarieren reicht normales CSS. Das Interface ist nur für dynamische Änderungen nötig.

Parameter

Name Typ Default Beschreibung
$name string Eigenschaft, nur lesbar. Name der Regel (dashed-ident, z. B. --above). Diesen Namen verwendet man in position-try-fallbacks.
$style CSSPositionTryDescriptors Eigenschaft, nur lesbar (der Inhalt ist änderbar). Enthält die erlaubten Deskriptoren, z. B. top, left, margin, width, positionAnchor, positionArea, alignSelf.

Rückgabewert

Typ
CSSPositionTryRule
Beschreibung
Instanzen legt der Browser selbst an, wenn er das Stylesheet einliest. Einen öffentlichen Konstruktor gibt es nicht. Man erhält die Objekte über CSSStyleSheet.cssRules.

Beispiele

Alle @position-try-Regeln eines Stylesheets auflisten

// CSS im Dokument:
// @position-try --tooltip-top { position-area: top; margin-bottom: 8px; }
// .tooltip { position-anchor: --btn; position-area: bottom; position-try-fallbacks: --tooltip-top; }

const tryRules = [...document.styleSheets]
  .flatMap((sheet) => {
    try {
      return [...sheet.cssRules];
    } catch {
      return []; // fremde (Cross-Origin-)Stylesheets überspringen
    }
  })
  .filter((rule) => rule instanceof CSSPositionTryRule);

for (const rule of tryRules) {
  console.log(rule.name, rule.style.positionArea, rule.style.marginBottom);
}
--tooltip-top top 8px

Neue Ausweich-Position per insertRule anlegen

const style = document.createElement('style');
document.head.append(style);
const sheet = style.sheet;

const index = sheet.insertRule(`
  @position-try --menu-left {
    position-area: left span-bottom;
    margin-right: 4px;
  }
`);

const rule = sheet.cssRules[index];
console.log(rule instanceof CSSPositionTryRule); // true
console.log(rule.name);
console.log(rule.cssText);
true --menu-left @position-try --menu-left { position-area: left span-bottom; margin-right: 4px; }

Abstand der Ausweich-Position zur Laufzeit anpassen

const findTryRule = (name) => {
  for (const sheet of document.styleSheets) {
    let rules;
    try { rules = sheet.cssRules; } catch { continue; }
    for (const rule of rules) {
      if (rule instanceof CSSPositionTryRule && rule.name === name) return rule;
    }
  }
  return null;
};

const rule = findTryRule('--tooltip-top');
if (rule) {
  // Kompaktmodus: Abstand verringern
  rule.style.marginBottom = '2px';
  console.log(rule.style.marginBottom);
}
2px

Feature-Erkennung vor der Nutzung

const supportsPositionTry =
  typeof CSSPositionTryRule !== 'undefined' &&
  CSS.supports('position-try-fallbacks', 'flip-block');

if (!supportsPositionTry) {
  // Ausweichlösung, z. B. per JavaScript positionieren (Floating UI o. Ä.)
  console.log('Anchor-Positioning-Fallbacks nicht verfügbar');
}

// Wichtig · Fallstricke

  • Browser-Unterstützung: In Chromium-Browsern ab Version 125 verfügbar, Safari folgt ab Version 26. Firefox unterstützt die Funktion noch nicht standardmäßig. Vorher per Feature-Erkennung prüfen (typeof CSSPositionTryRule bzw. CSS.supports()).
  • Nur bestimmte Deskriptoren sind erlaubt: Inset-Eigenschaften (top, inset-block-start …), margin, Größen (width, max-height …), Selbst-Ausrichtung (align-self, justify-self), position-anchor und position-area. Andere Eigenschaften wie color werden verworfen und tauchen im style-Objekt nicht auf.
  • !important ist innerhalb von @position-try ungültig. Solche Deklarationen werden ignoriert.
  • CSSRule.type liefert für diese Regel 0, weil es für neuere Regeltypen keine Typkonstante mehr gibt. Stattdessen instanceof CSSPositionTryRule verwenden.
  • Wer cssRules von Cross-Origin-Stylesheets ohne CORS-Freigabe liest, bekommt einen SecurityError. Den Zugriff daher in try/catch kapseln.
  • Ändert man den Namen, müssen die Verweise in position-try-fallbacks mitgezogen werden. name ist aber nur lesbar. Zum Umbenennen muss man die Regel löschen und neu einfügen.