Search code examples
htmlcsscomputer-science

change color of anchor tag on click using CSS


I have an anchor tag Home this displays homepage and another one Books this display books page. Now when I click on Home link I want it to change it's color and keep the same color until I click on the other link. Similarly, when I click on Books link I want it to change this color and keep the same color until I click other link.

I can do it using JavaScript but I want to know how I can achieve it using CSS only?

I tried with a:active but it doesn't work.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Literata:opsz,wght@7..72,300&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <title>Bookstore</title>
</head>
<body>
    <div class="container">
            <ul>
                <li><a href="home.html">Home</a></li>
                <li><a href="books.html">Books</a></li>
            </ul>
        </div>
      
    
</body>
</html>

Solution

  • You can do it like that, Use focus, But if using only that the styling will be lost once another element gains focus, So add a class to your a like in my example link then use it in CSS like the demo below:

    a {
      color: black;
      text-decoration: none;
      font-size: 20px;
    }
    
    a:focus {
      color: red;
    }
    
    :link {
      color: red;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Literata:opsz,wght@7..72,300&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="styles.css">
        <title>Bookstore</title>
    </head>
    <body>
        <div class="container">
                <ul>
                    <li><a href="#" class="link">Home</a></li>
                    <li><a href="#" class="link">Books</a></li>
                </ul>
            </div>
          
        
    </body>
    </html>