首页 > 解决方案 > 使用文本装饰下划线为文本添加下划线 - CSS

问题描述

以下是我的 HTML/CSS 代码,我在其中尝试在不使用本机text-decoration: underline属性的情况下在文本下方添加下划线。但不知何故,这段代码不起作用。任何指针我在这里做错了什么

HTML 代码 -

<span>
  <a class="test">Add Underline To Text</a>
</span>

CSS 代码 -

.test {
  position: relative;
  text-decoration: none;
}

.test:hover {
  width: 100%:
}

.test:after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -7px;
  height: 4px;
  background-color: green;
  width: 0;
  transition: width .25s;
}

Codepen 链接 - https://codepen.io/anon/pen/VEBNyx

标签: htmlcsssass

解决方案


您想在悬停链接width时添加吗?然后你需要写. 不只是。:after.testtest:hover:after { }test:hover

即使:after是伪元素,如果要更改其样式,也必须选择它

见下文

.test {
  position: relative;
  text-decoration: none;
}

.test:hover:after {
  width: 100%;
}

.test:after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -7px;
  height: 4px;
  background-color: green;
  width: 0;
  transition: width .25s;
}
<span>
  <a class="test">Add Underline To Text</a>
</span>


推荐阅读