position-visibility

Avatar of Juan Diego Rodríguez
Juan Diego Rodríguez

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费积分!

position-visibility 属性提供某些条件来隐藏 锚点定位元素 于视口。

.target {
  position: absolute;
  position-anchor: --my-anchor;
  position-visibility: no-overflow;
}

position-visibility 属性对普通元素没有任何影响。这是因为它属于 CSS 锚点定位模块的一部分,该模块是一组许多共同定位元素的功能,我们可能称之为“目标”到另一个称为“锚点”的元素。

语法

position-visibility: always | [ anchors-valid || anchors-visible || no-overflow ]
  • 初始值:anchors-visible 1
  • 应用于:绝对定位元素
  • 继承:
  • 百分比:n/a
  • 计算值:按指定
  • 规范顺序:按语法
  • 动画类型:离散

1 规范指出默认值为anchors-visible,但在撰写本文时,浏览器支持always作为默认值。

  • always该属性无效,因此无论其锚点或自身是否溢出其容器,目标都将显示。
  • no-overflow如果在应用position-try-options上定义的定位选项后,目标元素仍然溢出其容器,则目标将被强制隐藏。
  • anchors-visible如果锚点(而非目标)已完全溢出其容器或其他元素覆盖它,则目标将被强制隐藏。

根据规范,存在一个anchors-valid值,如果其锚点属性(position-anchor)或锚点函数(anchor()anchor-size())未解析为有效的锚点元素,则隐藏元素;也就是说,如果它找不到匹配的anchor-name。但是,在撰写本文时,还没有浏览器实现它。

用法

锚点定位元素(或简称为目标)不可避免地会遇到定位问题。由于屏幕调整大小、动画、相邻元素,以及主要是溢出,它不会始终定位良好,最糟糕的情况是完全被遮挡。尽管我们尽最大努力通过position-try-optionsposition-try-order更改其位置,但仍然会有一些情况最好先隐藏它,然后再在令人讨厌的站点上显示它。

在这些情况下,我们可以使用position-visibility属性来定义一些条件,当满足这些条件时,将强制隐藏目标元素。根据规范,强制隐藏元素使其行为就像它及其所有后代的visibility都设置为hidden一样,而不管它们的实际可见性值如何。

让我们设置一个演示,我们可以使用它来查看不同属性如何影响事物。首先,我们可以布置.anchor.target元素

<div class="anchor">anchor</div>
<div class="target">target</div>

我们将使用锚点定位的魔力将它们链接在一起

.anchor {
  anchor-name: --my-anchor;
}

.target {
  position: absolute;
  position-anchor: --my-anchor;
}

现在,我们可以通过将inset-area属性设置为top将我们的目标定位到锚点之上。

.target {
  position: absolute;
  position-anchor: --my-anchor;
  inset-area: top;
}

最后,我们将锚点放置在中心,并使主体更大,以便我们可以四处滚动。

body {
  display: flex;
  align-items: center;
  justify-content: center;

  height: 250vh;
}

这是我们工作的基础。现在让我们将position-visibibility属性添加到组合中,并尝试不同的值。

always

根据规范anchors-visibleposition-visibility属性的默认值,但always是浏览器已实现并实际支持的值,至少在撰写本文时是如此。使用always.target不会隐藏,无论其.anchor是否溢出其容器或.target元素本身是否溢出。

Example of position-visibility: always. The target's isn't hidden regardless of its overflow

no-overflow

no-overflow值会隐藏.target,只要它开始溢出其包含块外部。

Example of position-visibility: no-overflow. The target is hidden when it overflows

anchors-visible

anchors-visible属性隐藏.target元素,如果其.anchor完全溢出其包含块或被其他元素完全覆盖。

Example of position-visibility: anchors-visible. The target is hidden if the anchor is hidden

演示

规范

position-visibility属性在CSS 锚点定位模块级别 1 规范中定义,在撰写本文时,该规范目前处于工作草案状态。这意味着从现在到该功能成为正式的候选推荐以供实施之间,可能会发生很多变化。

浏览器支持

Data on support for the css-anchor-positioning feature across the major browsers from caniuse.com

更多信息和教程