CSS - 仅限且布局友好的 Reveal Focus 来自 Fluent Design System

CSS-only and layout friendly Reveal Focus from Fluent Design System

Reveal focus docs其:

但是,正如文档

Reveal focus increases the size of the focus visual, which might cause issues with your UI layout. In some cases, you'll want to customize the Reveal focus effect to optimize it for your app.

您将如何以上述方式创建不影响 UI 的效果?

我的 Reveal 焦点组件:

  1. 显示发光是box-shadow
  2. 主要焦点视觉是 outline
  3. 次要焦点视觉是 border
  4. 背景

但似乎有些不对劲,我不太明白。是 box-shadow,间距(如 margin,如您所见,我没有设置任何间距),还是其他东西?如果您希望它看起来像下面的 gif 中的样子,您会如何修复它?

body {
  background-color: #000;
  padding: 5px 100px;
}
.tile {
  display: inline-block;
  height: 82px;
  background-color: #555555;
}
.x1 { width: 19%; }
.x2 { width: 38%; }

.reveal-focus {
  border: 1px solid transparent;
  outline: 2px solid transparent;
}

.reveal-focus:focus {
  outline-color: #61B250;
  box-shadow: 0 0 15px 3px #61B250;
}
<a href="#" class="tile reveal-focus x1"></a>
<a href="#" class="tile reveal-focus x1"></a>
<a href="#" class="tile reveal-focus x1"></a>
<a href="#" class="tile reveal-focus x2"></a>
<a href="#" class="tile reveal-focus x2"></a>
<a href="#" class="tile reveal-focus x1"></a>
<a href="#" class="tile reveal-focus x1"></a>
<a href="#" class="tile reveal-focus x1"></a>

阴影被放置在出现在聚焦元素之前的元素之上,但在它之后的元素之下。您需要将 position: relative 添加到所有元素,并将 z-index: 1 添加到重点元素。

为确保这不会干扰任何其他堆叠,请将 position: relative; z-index: 0 应用于容器。这确保它有自己的堆栈上下文。

您显示的 GIF 似乎也有轻微的动画效果,在淡化为正常之前,辉光更强烈了一会儿。这可以通过 animation.

非常简单地实现

body {
  background-color: #000;
  padding: 5px 100px;
}
.tile {
  display: inline-block;
  height: 82px;
  background-color: #555555;
}
.x1 { width: 19%; }
.x2 { width: 38%; }

.reveal-focus {
  border: 1px solid transparent;
  outline: 2px solid transparent;
  position: relative;
}

.reveal-focus:focus {
  border-color: #000;
  outline-color: #61B250;
  box-shadow: 0 0 15px 3px #61B250;
  animation: glowfade 0.4s linear;
  z-index: 1;
}

@keyframes glowfade {
  from {box-shadow: 0 0 30px 6px #61B250;}
  to {box-shadow: 0 0 15px 3px #61B250;}
}
<a href="#" class="tile reveal-focus x1"></a>
<a href="#" class="tile reveal-focus x1"></a>
<a href="#" class="tile reveal-focus x1"></a>
<a href="#" class="tile reveal-focus x2"></a>
<a href="#" class="tile reveal-focus x2"></a>
<a href="#" class="tile reveal-focus x1"></a>
<a href="#" class="tile reveal-focus x1"></a>
<a href="#" class="tile reveal-focus x1"></a>

根据需要调整值。