user4779475 user4779475 - 4 months ago 16
CSS Question

Is it possible for an anchor link stay highlighted on single page website using pure css?

Is it possible to keep an anchor link highlighted on a single page using pure CSS?

I already saw a lot of tutorials about the link highlight when someone is in a designated page. But I never saw someone do what I asked... only with javascript. But I don't wanna use js because is a fancy noscript page that I want to do.



ul {
margin: auto;
word-wrap:break-word;
padding:0px;
position:fixed;
}

a {
width:30px;
}
a:link, a:visited {
text-decoration:none;
display:block;
background-color:gray;
color:#ffffff;
}
a:hover, a:active {
background-color:black;
}
.contentWrap {
top:0px;
width:300px;
bottom:0;
background-color:#FF9933;
position: absolute;
margin:auto;
left: 0;
right: 0;
}
.container {
height:1000px;
}
#one {
background-color:orange;
}
#two {
background-color:green;
}

<ul>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
</ul>

<!-Content/->
<div class='contentWrap'>
<div class='container' id='one'></div>
<div class='container' id='two'></div>
</div>
<!-Content/->




Answer

It is possible using only css with the :target pseudo-class and the general sibling selector SO docs, MDN. However, the links must come after the containers and the containers can not be in another element.

For the html, you need to remove the .contentWrap div and move the <ul> after the .container divs.

<div class='container' id='one'></div>
<div class='container' id='two'></div>

<ul>
    <li><a href='#one'>One</a></li>
    <li><a href='#two'>Two</a></li>
</ul>

For the css, you need to change the ul and .container rules. In the selector for the new rule, :target selects the container with the id that the fragment identifier links to. Then ~ selects the following ul with the descendant a with the corresponding href attribute.

ul {
    margin: auto;
    word-wrap:break-word;
    padding:0px;
    position:fixed;
    top: 0;
    left: 0;
}
.container {
    height:1000px;
    width:300px;
    margin: auto;
}

#one:target ~ ul [href='#one'],
#two:target ~ ul [href='#two'] {
    background: #ccc;
}

ul {
    margin: auto;
    word-wrap:break-word;
    padding:0px;
    position:fixed;
    top: 0;
    left: 0;
}

a {
    width:30px;
}
a:link, a:visited {
    text-decoration:none;
    display:block;
    background-color:gray;
    color:#ffffff;
}
a:hover, a:active {
    background-color:black;
}

.container {
    height:1000px;
    width:300px;
    margin: auto;
}
#one {
    background-color:orange;
}
#two {
    background-color:green;
}

#one:target ~ ul [href='#one'],
#two:target ~ ul [href='#two'] {
    background: #ccc;
}
<div class='container' id='one'></div>
<div class='container' id='two'></div>

<ul>
    <li><a href='#one'>One</a></li>
    <li><a href='#two'>Two</a></li>
</ul>

Comments