Reputation: 573
I have an unordered list with a lot of list items. Some of the list items are links, some are not. I want to add padding to the list items so the appearance is consistent regardless of whether it is a link or not, i.e. I do not want to add padding to the anchor, but to the list and for the anchor to wrap around the link AND padding.
Despite using display:block
on hover the background color is only around the text inside the link. It ignores the padding. Is there a way to get the link to include the padding (without putting padding on the link)?
ul li {
float: left;
line-height: 5em;
padding: 0 2em;
}
a:link {
display: block;
}
a:visited {
display: block;
}
a:hover {
display: block;
background-color: rgb(245, 245, 245);
}
a:active {
display: block;
background-color: rgb(245, 245, 245);
}
<ul>
<li><a href="1.html">Item 1</a>
</li>
<li><a href="2.html">Item 2</a>
</li>
<li>Item 3</li>
<li>Item 4</li>
<li><a href="5.html">Item 5</a>
</li>
</ul>
Upvotes: 1
Views: 1187
Reputation: 1
Here you go, my comments should explain everything but feel free to ask.
<ul>
<li><a href="1.html">Item 1</a></li>
<li><a href="2.html">Item 2</a></li>
<li>Item 3</li>
<li>Item 4</li>
<li><a href="5.html">Item 5</a></li>
</ul>
ul{
list-style-type: none; /* Feel free to remove this, just easier without bullets */
}
ul li {
float: left;
line-height: 5em; /* Should be the same as height */
padding: 0 2em;
position: relative; /* Make sure a & a:before can stay contained */
height: 5em; /* Should be same as line-height */
white-space: nowrap; /* Ensure that your items don't wrap and mess up width */
z-index: -1; /* So that a:before is able to trigger with :hover */
}
a{
position: relative; /* Make sure a:before can stay contained */
display: block; /* Ensures that a can expand to full size of container */
}
a:before{
content: ""; /* Necessary for :before element to be created */
position: absolute; /* Vital - allows positioning */
top: 0;
right: -2em; /* Minus same padding as li has */
bottom: 0;
left: -2em; /* Minus same padding as li has */
z-index: -1; /* Makes sure :before doesn't go above anchor text */
}
a:hover:before,
a:active:before {
background-color:rgb(245,245,245);
}
Upvotes: 0
Reputation: 42370
You can use the hover
the li
instead of the a
to correct the background-color
applied on hover
by using:
li:hover a {
display: block;
}
li:hover {
background-color: rgb(245, 245, 245);
}
instead of:
a:hover {
display:block;
background-color:rgb(245,245,245);
}
See demo below:
ul li {
float: left;
line-height: 5em;
padding: 0 2em;
}
a:link {
display: block;
}
a:visited {
display: block;
}
li:hover a {
display: block;
}
li:hover {
background-color: rgb(245, 245, 245);
}
a:active {
display: block;
background-color: rgb(245, 245, 245);
}
<ul>
<li><a href="1.html">Item 1</a>
</li>
<li><a href="2.html">Item 2</a>
</li>
<li>Item 3</li>
<li>Item 4</li>
<li><a href="5.html">Item 5</a>
</li>
</ul>
Upvotes: 2