sona
sona

Reputation: 109

How to apply a underline style to piece of text

Whenever hover, I want to apply a underline style to part of string.

ex) enter image description here

Here is a my code.

HTML

<a class="test">
  <i>1</i><span>23</span>
</a>

CSS

.test:hover span{
   border-bottom: 1px solid #999999
 }

But, I don't want to use span tag like following code.

ex)

HTML

<a class="test"><i>1</i>23</a>

CSS

.test:hover{
   border-bottom: 1px solid #999999
}
.test:hover i{
  border-bottom: none !important;
}

But,It is not working. How can I solve that?

Upvotes: 1

Views: 103

Answers (3)

Paulie_D
Paulie_D

Reputation: 115047

Since text nodes aren't elements that cannot be selected with CSS or have borders.

Once solution is to use a pseduo-element on the preceding <i> that is positioned to the bottom and right of that element, like so:

a {
  text-decoration: none;
  font-size: 72px;
  overflow: hidden;
  display: inline-block;
}
a i {
  position: relative;
}
a i::after {
  content: '';
  width: 100px;
  /* some arbitrary large size */
  height: 2px;
  background: red;
  position: absolute;
  top: 100%;
  left: 100%;
}
<a class="test"><i>1</i>23</a>

Upvotes: 0

Hidden Hobbes
Hidden Hobbes

Reputation: 14173

.test:hover i {border-bottom: 1px solid transparent;} does not work because it basically acts as a window through to the line applied to the containing element by .test:hover {border-bottom: 1px solid #999999;}.

One way you could get around this issue is to instead set the line to match the background colour so it masks the line made by .test:hover. This does presume that the background is a solid colour, if it is a gradient or image this method will not be suitable.

.test:hover {
  border-bottom: 1px solid #999999;
}
.test:hover i {
  border-bottom: 1px solid #FFFFFF;
}
<a class="test"><i>1</i>23</a>

Upvotes: 2

Kyle Erwin
Kyle Erwin

Reputation: 9

You would do this. Either in your inline style or CSS file

text-decoration: underline;

Upvotes: 0

Related Questions