Using CSS to make the size of a list item relative to the size of the text within it

StackOverflow https://stackoverflow.com/questions/22965029

  •  30-06-2023
  •  | 
  •  

I am trying to put together a relatively simple website using HTML and CSS, both of which I have dabbled with in the past, but I still only have a fairly basic understanding of the kind of level of power CSS in particular gives you over design elements.

For my site I want to have a menu bar across the top of the page, for which I am using an unordered list set as an inline block:

    <div id='navigation'>
        <ul>
            <li>Home</li>
            <li><a href='about.html'>About Me</a></li>
            <li><a href='blog.html'>Blog</a></li>
            <li><a href='contact.html'>Contact</a></li>
        </ul>
    </div> <!-- End of navigation div -->

#navigation ul {
list-style-type: none;
margin: 0;
padding: 0;
padding-top: 5px;
background-color: red;

}

#navigation li {
display: inline-block;

margin-left: 3px;
padding-top: 5px;

width: 100px;
text-align: center;

background-color: yellow;
}

Note that the garish coloration is so that I can keep an eye on all of the different sizes as I am coding!

When the list items have their yellow background the link bar looks well spaced out, but as soon as I set the colour to be the same as that of the background of the ul, the fact that each li contains a different number of characters causes each link to appear to be unevenly spaced.

I was just wondering if there is a way to style the list items so that the spacing between each link is relative to the size of the text contained within?

Many thanks!

有帮助吗?

解决方案

Yes you can:

HTML

<div class="nav">
    <ul>
        <li><a href="#">Presenting</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Telecoms</a></li>
        <li><a href="#">Working With Us</a></li>
        <li><a href="#">Contact Us</a></li>
    </ul>
</div>

CSS

.nav{
    display:table;
    width:100%;
}
.nav ul{
    display:table-row;
    margin:0;
    padding:0;
    list-style:none;
}
.nav ul li{
    display:table-cell;
}
.nav ul a{
    padding:5px 14px;
    display:block;
}

It will justify your li to the whole width of div. Try my example on your code

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top