Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a valid <li> link

I'm trying to make an unordered list where the list items are links, not just the text inside them. But this is not valid. When checking my code with https://validator.w3.org/check I receive the message

Element a not allowed as child of element ul in this context.

This is the code:

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test</title>
    <style>
        ul {
            list-style:none;
        }
        a {
            text-decoration:none;
            color: #212121;
            font-size: 1em;
            font-family: Arial, Helvetica, sans-serif;
        }
        #container {
            padding:20px;
        }

        .valid {
            background-color:blanchedalmond;
        }

        .invalid {
            background-color:aquamarine;
        }

        .nav-item {
            width:120px;
            height:34px;
            margin:4px;
            line-height:34px;
            text-align:center;
            border: solid 1px #212121;
        }
    </style>
</head>
<body>

    <div id="container">
        <ul>
            <li class="valid nav-item"><a href="index.html">valid</a></li>
            <a href="index.html"><li class="invalid nav-item">invalid</li></a>
        </ul>
    </div>
</body>
</html>

The invalid arrangement of <a><li></li></a> is what I want to achieve behavior-wise with the entire <li> element being selectable as a link.

If I want to maintain valid code what is the best way to achieve a selectable <li>?

like image 847
ryanr Avatar asked Jun 18 '15 10:06

ryanr


2 Answers

This format is invalid

<a href="index.html"><li class="invalid nav-item">invalid</li></a>

Valid format is

 <li class="invalid nav-item"><a href="index.html">valid</a></li>

As for your concern anchor filling up the space of li, little css trick will solve it.

a {
 text-decoration: none;
 display: block;
 width: 100%;
 height: 100%;
}
like image 149
Muhammet Avatar answered Oct 16 '22 12:10

Muhammet


There are two way you can get the li text clickable

1) Add onlclick event the the li like <li onclick='window.location.href="Your Link"'>Your Text</li>

2) Add a tag inside the li and add css to a tag as bellow

<li><a href='your link'>Your Text</a></li>

li a{
    display:block;
}

Second option cover inside area of li

like image 8
Mitul Avatar answered Oct 16 '22 12:10

Mitul