css 悬停时更改按钮颜色

时间:2021-07-07 15:18:26

标签: html css

当按钮悬停时,我试图将文本颜色从白色更改为黑色,并且代码中的所有内容都很好,只是文本颜色不会改变。有人知道我该怎么做吗?

.main__btn {
  font-size: 1.2rem;
  background: rgba(0, 0, 0, 0);
  padding: 15px 50px;
  border-radius: none;
  border-color: #fff;
  margin-top: 2rem;
  cursor: pointer;
  position: relative;
  transition: all 0.35s;
  outline: none;
}

.main__btn a {
  position: relative;
  z-index: 2;
  color: #fff;
  text-decoration: none;
}

.main__btn:after {
  position: absolute;
  content: '';
  top: 0;
  left: 0;
  width: 0;
  height: 100%;
  background: #ffffff;
  transition: all 0.35s;
  border-radius: 4px;
}

.main__btn:hover {
  color: #000;
}

.main__btn:hover:after {
  width: 100%;
}
<button class="main__btn" id="button1"><a href="#">button1</a></button>

2 个答案:

答案 0 :(得分:1)

您希望更改锚点 (color) 标签上的 a,而不是 button

.main__btn:hover a {
  color: #000;
}

由于您在上面的锚标记上设置了 color: #fff;,防止继承 color.main__btn:hover

答案 1 :(得分:0)

锚标签的颜色是白色。对父级应用 color:#000 不会改变其颜色。

相反,将 color:#000 应用于锚点。

.main__btn {
  font-size: 1.2rem;
  background: rgba(0, 0, 0, 0);
  padding: 15px 50px;
  border-radius: none;
  border-color: #fff;
  margin-top: 2rem;
  cursor: pointer;
  position: relative;
  transition: all 0.35s;
  outline: none;
}

.main__btn a {
  position: relative;
  z-index: 2;
  color: #fff;
  text-decoration: none;
}

.main__btn:after {
  position: absolute;
  content: '';
  top: 0;
  left: 0;
  width: 0;
  height: 100%;
  background: #ffffff;
  transition: all 0.35s;
  border-radius: 4px;
}

.main__btn:hover a{
  color: #000;
}

.main__btn:hover:after {
  width: 100%;
}
<button class="main__btn" id="button1"><a href="#">button1</a></button>

但是请注意,在按钮中使用锚点是无效的 HTML。- Roy

相关问题