pery mimon
pery mimon

Reputation: 8335

How to use CSS anchor-position to attach children to his parent

I have the following HTML structure:

<button id="button-1">
     Button content
     <span class="tooltip">Tooltip</span>
</button>

I want to position the .tooltip above the button using anchor-position as shown below:

button {
    anchor-scope: --button;
    anchor-name: --button;
}

.tooltip {
    position: absolute;
    position-anchor: --button;
    position-area: top;
}

However, because the .tooltip is inside the , it doesn't seem to recognize the anchor properties. I couldn't find any restrictions regarding this in the documentation, so my question is: How can I bypass this limitation and use the parent (button) as the anchor for the tooltip?

For context, here's a working snippet:

body{
 padding: 3em;
}

button {
 position: relative;
 anchor-scope:--button;
 anchor-name:--button;
 width: 10em;
 height: 3em;
 border-radius: .4em;
    
 &::after{
  display:block;
  position: absolute;
  content:attr(aria-label);
  background: black;
  color:white;
  margin-bottom: 5px;
  white-space: pre;
  padding: 0.3em;
  border-radius: .3em;
 }
}

#button-1::after{
 bottom: 100%;
 left: 50%;
 transform: translateX(-50%);
}
#button-2:after{
 position-anchor: --button;
 position-area: top;
}
<button id="button-1" aria-label="Should be above (old transform)">
    Button
</button>


<button id="button-2" aria-label="Should be above(using anchor)">
    Button
</button>

Upvotes: 0

Views: 46

Answers (1)

Temani Afif
Temani Afif

Reputation: 273540

You have to remove position: relative in this situation (and no need for scoping)

body {
  padding: 3em;
}

button {
  anchor-name: --button;
  width: 10em;
  height: 3em;
  border-radius: .4em;

  &::after {
    position: absolute;
    content: attr(aria-label);
    background: black;
    color: white;
    margin-bottom: 5px;
    white-space: pre;
    padding: 0.3em;
    border-radius: .3em;
  }
}

#button-2:after {
  position-anchor: --button;
  position-area: top;
}
<button id="button-2" aria-label="Should be above(using anchor)">
    Button
</button>

Upvotes: 3

Related Questions