在菜单项悬停时创建菱形

create a diamond shape on hover of menu item

我有一个菜单项,当鼠标悬停在它上面时,它会下拉一个橙色框。

.menu > li > a:hover:after {
    position: absolute;
    left: 0px;
    border-style: solid;
    border-color: transparent;
}

不过我想实现的是下拉框下方有菱形的效果。

我在这里看到一个 post 链接了这个 [网站][4] 并且我尝试使用 diamond:after 方法,但是结果很糟糕。需要编辑的css部分我已经注释掉了,方便快速参考。如果有人可以提供帮助。

1) 在您的 CSS 中没有 :after 伪元素 (.menu > li > a:hover:after {/* your css */}) 的声明。 例如:

.menu > li > a:hover:after {
    content: ""; /* empty content */
    position: absolute;
    bottom: -50px; /* position 50px below the bottom of the menu link */
    left: 0px;
    border-style: solid;
    border-color: transparent;
    border-width: 0px 60px; /* diamond has 60px to the left and to the right of the midpoint, so the menu item should be 120px width */
    border-top: 50px solid #FF6E0D;
}

此方法要求您指定菜单项的宽度,因为您希望菱形横跨 link 的整个底部。 (使用 left/right border-width。)

2) 要使用此方法,您应该将 position: relative; 添加到 .menu > li > a 声明中,因为 :after 伪元素需要它来定位自己。

您可以为此使用一个伪元素,'move' 它在悬停时:

div {
  height: 50px;
  width: 100px;
  background: orange;
  margin: 0 auto;
  text-align: center;
  position: relative;
}
div:before {
  content: "";
  position: absolute;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-top: 50px solid orange;
  top: 0;
  left: 0;
  transition: all 0.6s;
  z-index:-1;
}
div:hover:before {
  top: 100%;
}
<div>Option</div>

我使用了 :after 伪元素来添加箭头。虽然过渡效果看起来不太好,因为两者都是单独制作动画的。如果你想让它顺利,你必须在那里挖一点。但这至少让箭头出现在正确的位置,这看起来确实是您问题的重要部分。然后你只需使用 hover 伪元素将显示设置为块。

.menu > li > a:after {
  content: "";
  position: absolute;
  display: none;
  top: 160px;
  left: 0px;
  width: 0;
  height: 0;
  border-left: 62px solid transparent;
  border-right: 62px solid transparent;
  border-top: 60px solid #FF6E0D;
}

.menu > li > a:hover:after {
  display: block;
}