简体   繁体   中英

CSS changing border color of block level element on hover for just the text

Consider the following:

<ul>
 <li><a href="somelink" class="navlink"><span>Link 1</span></a></li>
 <li><a href="somelink" class="navlink"><span>Link 2</span></a></li>
 <li><a href="somelink" class="navlink"><span>Link 3</span></a></li>
</ul>

And the stylesheet behind this (simplified):

li {width: 150px;}
a {display:block; text-decoration:none;}
a.navlink span {border-bottom: 1px solid red;}
a.navlink:hover {border-color: magenta;}

As you will see the link which surrounds the text has been expanded to cover the whole box. However only the actual text itself has a border underneath it, to prevent the border appearing across the whole box. What I am trying to achieve is that when you hover over anywhere inside the a (so the whole box), the border color changes.

I can get it so that the border color changes if you just hover over the text, and if I change the border-color line above to something like background-color: magenta; it also works. However I think because the border has been assigned to the span, and not the navlink class, I don't think the hover is working.

Any help would be appreciated!

li {width: 150px;}
a {display:block; text-decoration:none;}
a.navlink span {border-bottom: 1px solid red;}
a.navlink span:hover {border: 1px solid magenta;}

Demo

Change your a.navlink:hover {border-color: magenta;} to a.navlink span:hover {border: 1px solid magenta;}

LIke this

demo

css

li {
    width: 150px;
}
a {
    display: block;
    text-decoration: none;
}
a.navlink span {
    border-bottom: 1px solid red;
}
a.navlink span:hover {
    border-color: magenta;

}

I think you mean like this. So when you hover over any of the <a> it will change the border on the <span> thats inside <a> . Check it out.

HTML:

<ul>
    <li><a href="somelink" class="navlink"><span>Link 1</span></a></li>
    <li><a href="somelink" class="navlink"><span>Link 2</span></a></li>
    <li><a href="somelink" class="navlink"><span>Link 3</span></a></li>
</ul>

CSS:

li {
    width: 150px;
}
a {
    display: block;
    width: 100%;
    height: 100%;
    text-decoration: none;
}
.navlink span {
    border-bottom: 1px solid blue;
}
.navlink:hover > span {
    border-bottom: 1px solid red;
}

DEMO HERE


Your version fixed:

DEMO HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM