I am creating navigation menu. I want to use css so that anchor tag is wrapped around li element but anchor tags are inside li element.
Here is html
<ul> <li><a href="">Uutiset</a></li> <li><a href="">Foorumi</a></li> <li><a href="">Kauppa</a></li> <li><a href="">Messut</a></li> <li><a href="">Asiakaspalvelu</a></li> <li><a href="">Nakoislehti</a></li> <li><a href="">Nae meidat</a></li>
</ul>here is my less css
ul { list-style-type: none; padding: 0; margin: 0; li { padding: 2% 4%; border: 1px solid green; a { text-decoration: none; display: block; } }
} 5 Answers
The only legal element allowed inside a <ul> is an <li>. You cannot have an anchor wrapped around the <li>. This holds true in HTML5, where an anchor can wrap around other block level elements.
What you have in CSS is nearly there, just add:
a { text-decoration: none; display: block; width: 100%; height: 100%;
}And your anchor shall fill the entire space of the <li>.
Update for 2022: wrapping your li tags with anchors is now totally acceptable.
Dont use padding in li , use line-height for the anchor text instead. This will make it cover full height of li element .
Here, have a look at this Example
Putting anchor tags, or any tags, around list-items is perfectly valid at the time of writing this in 2022. Though it may be considered unusual or bad practice.
From the specs:
Any element whose computed value of 'display' is 'list-item' has a list owner, which is determined as follows:
If the element is not being rendered, return null; the element has no list owner.
Let ancestor be the element's parent.
If the element has an ol, ul, or menu ancestor, set ancestor to the closest such ancestor element.
The "owner" of the <li> tag is not determined by its direct parent, but by the closest ol, ul, or menu ancestor.
No problems should arise, accessibility or otherwise, from putting other tags around it. As long as it is inside a ol, ul or menu at some level, it will find its owner. It's the only way you would make the entire <li> container including the bullet or number clickable.
<ol> <li> <a href="">This is fine.</a> </li> <a href=""> <li>This link is the entire container.</li> </a> <a href=""> <div> <div> <div> <li>This has four parents before the <ol.></li> </div> </div> </div> </a>
</ol> You can't make a li clickable, but what you can do is expanding the a-link to the size of the li as suggested here:
Try this, give the padding to anchor instead of li. It is not possible to keep outside li. Do style your anchor instead of li. Let li act just like a wrapper.
ul { list-style-type: none; padding: 0; margin: 0; li { a { padding: 2% 4%; border: 1px solid green; text-decoration: none; display: block; } }
}