多行背景模仿下划线文字

问题描述 投票:0回答:1

我创建了一种悬停效果,对于单行文本效果非常好。不幸的是,当文本是多行时它不起作用。我明白这是因为它向段落添加了背景,其中包含整个文本,但我不知道如何修改它来修复它?是否可以仅更改

.underline
类?我将它用作一个单独的类,我希望它适用于现有网站中的不同元素,并且该段落是单行还是多行取决于屏幕大小,因此修改 html 并不是真正的答案。你能帮忙吗?

div {
border-right: black 1px solid;
padding: 2px;
width: 150px;
}

.underline {
  cursor: pointer
  position: relative;
  text-decoration: none;
  background: linear-gradient(
                  to right,
                  green 0%, /* Green */
                  green 75%, /* Green */
                  red 75%, /* Red */
                  red /* Red */
  ) no-repeat 0 100%;
  background-size: 0 2px;
  transition: background-size 400ms;
}


.underline:hover {
    background-size: 100% 2px;
  }
<div class="container">
 <p class="underline">This text</p>
 <p class="underline">This another, multiline text</p>
 </div>

css
1个回答
0
投票

严格无需编辑 HTML,即可设置

display: inline
:

div {
  border-right: black 1px solid;
  padding: 2px;
  width: 150px;
}

.underline {
  display: inline;
  cursor: pointer;
  position: relative;
  text-decoration: none;
  background: linear-gradient(
    to right,
    green 0%, /* Green */
    green 75%, /* Green */
    red 75%, /* Red */
    red/* Red */
  ) no-repeat 0 100%;
  background-size: 0 2px;
  transition: background-size 400ms;
}

.underline:hover {
  background-size: 100% 2px;
}
<div class="container">
  <p class="underline">This text</p>
  <p class="underline">This another, multiline text</p>
</div>

尽管这意味着会发生其他布局副作用。为了避免这种情况,您可以稍微调整 HTML,但仍然不知道文本是否是多行:

div {
  border-right: black 1px solid;
  padding: 2px;
  width: 150px;
}

.underline {
  cursor: pointer;
  position: relative;
  text-decoration: none;
  background: linear-gradient(
    to right,
    green 0%, /* Green */
    green 75%, /* Green */
    red 75%, /* Red */
    red/* Red */
  ) no-repeat 0 100%;
  background-size: 0 2px;
  transition: background-size 400ms;
}

.underline:hover {
  background-size: 100% 2px;
}
<div class="container">
  <p><span class="underline">This text</span></p>
  <p><span class="underline">This another, multiline text</span></p>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.