首页 > 解决方案 > 尝试对标题中的两个不同单词进行悬停效果

问题描述

我是新来的,所以请放轻松,因为我正在学习。基本上我有一个标题,其中包含一些文本,如下所示:

<section id="hero">
<header><span id="first">Dwayne <> </span><span id="last">Rill Jr.</span></header>
<hr>
<p>Aspiring Designer & Developer</p>
<button id="cta-works">Take a look at my work</button>
</section>

我想制作一个适用于名字和姓氏的悬停效果,并且实际上在两个元素之间切换颜色(名字颜色是白色并变成青色,第二个名字颜色是青色并变成白色)。

#hero  {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 90vh;
  background-color: #0b0c10;
  color: white;
  text-transform: uppercase;
  font-weight: 200;
  cursor: default;
}

#first {
  color: #66fcf1;
}

#first:hover {
  color: white;
}

#last {
  color: white;
}

#last:hover {
  color: #66fcf1;
}

我尝试使用两个单独的跨度来让它工作,但它只会在我滚动“第一个”而不是“第二个”时改变颜色。我想把它弄到当你翻过标题的任一侧时它会翻转颜色的位置。任何帮助,将不胜感激!

标签: css

解决方案


您可以将悬停添加到header

#hero {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 90vh;
  background-color: #0b0c10;
  color: white;
  text-transform: uppercase;
  font-weight: 200;
  cursor: default;
}

#first {
  color: #66fcf1;
}

header:hover #first {
  color: white;
}

#last {
  color: white;
}

header:hover #last {
  color: #66fcf1;
}
<section id="hero">
  <header><span id="first">Dwayne </span><span id="last">Rill Jr.</span></header>
  <hr>
  <p>Aspiring Designer & Developer</p>
  <button id="cta-works">Take a look at my work</button>
</section>

您不能将其与 span 元素一起使用的原因是您必须使用兄弟选择器 ( #first:hover ~ #last),但这只会选择元素之后的兄弟姐妹,因此您无法#first使用#last( #last:hover ~ #first) 进行选择。


推荐阅读