w3c / csswg-drafts

CSS Working Group Editor Drafts
https://drafts.csswg.org/
Other
4.35k stars 641 forks source link

[css-anchor-position] Make anchor-center work without position-anchor #10366

Open yisibl opened 1 month ago

yisibl commented 1 month ago
  1. Open

    data:text/html;charset=UTF-8, <style>
    .anchor { anchor-name: --foo; width: 100px; height: 50px; display: block; margin: 30px auto;} 
    .anchored{position: absolute; left: anchor(--foo 50%); top: anchor(--foo bottom); 
    justify-self: anchor-center; background: green; padding: .5em 2em;}</style>
    <button class="anchor">anchor</button>
    <div class="anchored">anchored</div>
  2. The green element is not horizontally centered with respect to the button.

We must add position-anchor: --foo for anchor-center to take effect. This is often confusing to the user because <anchor-element> is already defined on the left.

Can we change the status quo?

tabatkins commented 1 month ago

Not generally, no. An author can refer to multiple different anchor elements on the same positioned element, so inference from "they've only mentioned one anchor name so far" is fragile.

Learning to reach for position-anchor early is a good reflex anyway, as when you are only using a single anchor it makes your other properties since you can omit the anchor name:

.anchored {
 position: absolute;
 position-anchor: --foo;
 left: anchor(50%);
 top: anchor(bottom);
 justify-self: anchor-center;
}

Tho note that these styles create overflow - the inset-modified containing block's left edge is right at the anchor's center, so by anchor-centering you are by definition overflowing the IMCB. You probably just wanted to write this instead, which also means you'll be setting position-anchor anyway:

.anchored {
 position: absolute;
 position-anchor: --foo;
 inset-area: bottom;
}
kizu commented 1 month ago

What if the anchor-center could have an optional functional form? Like justify-self: anchor-center(--foo)? Having an implicit default as position-anchor is good, but if we could allow using an explicit anchor name, it could lead to more flexible styles.