Saraph
Saraph

Reputation: 1002

Adjust <li> width to its content's width

I have following CSS code:

nav li {
    display: inline-block;
    text-align: center;
}

nav li a {
    display: block;
    width: 100%;
    height: 100%;
}

nav li :hover {
    background-color: var(--main-color);
    color: white;
}

Which makes elements in my navbar look like this:

without padding/margin/manual width

But there's actually 4 items, not 6. I'll add some padding in <li>:

padding/margin

But when I hover over the first item, I have this ugly white space from both sides of it. Margin does exactly the same thing. Let's remove margin/padding and set <li> width manually to 120px:

manual width

First two items are now formatted somehow acceptably, but items a and b take visually far too much space than necessary. What I aim for would be something like this (made in image editor):

ideal

In other words, I'd like my <li> elements to have their width adjusted to their content with extra padding, while child <a> elements still take up 100% of <li> space. Any ideas?

Upvotes: 1

Views: 3685

Answers (2)

MayThrow
MayThrow

Reputation: 2201

Try using table layout

body {margin:0}
nav ul {
  padding:0;
  margin:0;
  width: 100%;
  display: table;
}
nav li {
    display: table-cell;
    text-align: center;
}

nav li a {
    background: #fafafa;
    display: block;
    width: 100%;
    box-sizing: border-box;
    padding: 10px;/*or whatever*/
}

nav li :hover {
    background-color: brown;
    color: white;
}
<nav>
<ul>
  <li><a href="#">Item</a></li>
  <li><a href="#">Very long item</a></li>
  <li><a href="#">a</a></li>
  <li><a href="#">b</a></li>
</ul>
</nav>

Upvotes: 0

Himmel
Himmel

Reputation: 3709

Edit

I've updated updated the JSFiddle that you've posted.


You need to change your a element to not have display:block (should be inline instead). Also, you don't need to specify width and height of 100%. Just make your padding: 15px for the a, and you'll have equal, well-spaced hover padding.

I adapted your code above and put it into a codepen, see here:

http://codepen.io/himmel/pen/BNJZoL

Here is how I changed your CSS:

nav li {
    display: inline-block;
    text-align: center;
}

nav li a {
        padding-left: 15px; ** add padding to both sides
        padding-right: 15px;
        display: inline;
}

nav li :hover {
    background-color: brown;
    color: white;
}

Upvotes: 1

Related Questions