披萨时间悬停

Avatar of Chris Coyier
Chris Coyier

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

悬停大师 Jenn Lukas 给我发送了一个指向 PizzaTime.com 的链接。我们一致认为 1) 这些悬停效果非常棒!以及 2) 在像 PizzaTime.com 这样的域名下居然有一个高质量的网站,这一点非常酷——Jenn 在随机输入域名时希望能够找到一个网站。

他们有一组导航框,看起来像这样

然后它们会经历一个整洁的多步骤过渡过程,最终变成红色

图标所在的红色方块会左右扩展以填充父级框,然后上下扩展。文本和边框会更改颜色,以便在扩展的红色框上保持可见。

HTML 代码

我们将使用这个

<a href="#0" class="pizza-link">
  <span class="icon maki-embassy"></span>
  <h3>Find a Store</h3>
  <p>We've got a location near you! As far as Bellingham and Lewiston and Yakima and South to Olympia.</p>
</a>

如果您还没有收到通知,现在将任何内容包装在锚点标签中都很酷,因此很容易将整个框变成链接。在我们的例子中,我们将使用该锚点来设置实际框的样式。

仅用于此演示,我使用了 We Love Icon Fonts 并选择了一些随机图标来使用。该站点让您使用具有预定类的跨度来显示图标。如果我要将此概念投入生产,在这种情况下,我可能会改用伪元素,因为这些图标不包含任何内容值。或者,如果我使用跨度系统,我会使用 data-icon 属性和 aria-hidden 应用它。阅读更多。

CSS 代码

这是 Sass 中嵌套的一个不错的用例。我们在这里处理的所有内容都与 .pizza-time 链接相关,因此让我们只嵌套在该链接下。一些无聊的 CSS 已移除……

.pizza-link {
  display: block;
  float: left;
  /* yadda yadda yadda */
  h3 {
    border-bottom: 1px solid #eee;
    /* relative positioning keeps it on top of :before */
    position: relative;
  }
  p {
    /* relative positioning keeps it on top of :before */
    position: relative;
  }
  h3, p {
    /* "ease" and "all" are implied */
    @include transition(0.2s);
  }
  .icon {
    position: absolute;
    color: white;
    /* position in middle on top */
  }
  &:before {
    content: "";
    background: #D62121;
    /* position in middle on top */
    /* BELOW icon and other content */
    /* :before makes this easier than :after */
    position: absolute;
    width: 50px;
    height: 50px;
    top: 20px;
    left: 50%;
    margin-left: -25px;
    @include transition(
      /* FIRST STEP */
      width 0.2s,
      left 0.2s,
      margin-left 0.2s,
      /* SECOND STEP */
      top 0.2s 0.2s,
      height 0.2s 0.2s
    );
  }
  &:hover, &:active {
    h3 {
      color: white;
      border-bottom-color: #E14646;
    }
    p {
      color: white;
    }
    &:before {
      width: 230px;
      left: 0;
      top: 0;
      margin-left: 0;
      /* hacky, but the parent element */
      /* doesn't have explicit height */
      /* so can't use 100% */
      height: 320px;
    }
  }
}

三个值得注意的要点

  1. “红色框”是一个伪元素。过去我会在这里使用 span 或其他东西,但现在我们可以 对伪元素进行过渡,所以不妨试试。
  2. 因为“红色框”是一个绝对定位的 :before,所以我们只需要对内部的其他内容设置 position: relative,它就会按照自然的文档堆叠顺序位于红色框的顶部。
  3. 我们通过用逗号分隔所有要过渡的值来使过渡“多步骤”。水平相关的属性放在前面:widthleftmargin-left。然后垂直相关的属性放在“后面”:topheight。通过指定一个等于第一步值的持续时间的延迟值,它们将在“第一步”属性之后按顺序发生。

演示

Check out this Pen!

我想我们现在都意识到大多数触摸屏没有悬停状态。也许这些设备的用户将看不到我们的小巧精致的悬停效果。没关系。它们是链接。它们仍然有效。