MayurKode
MayurKode

Reputation: 135

dynamically increasing width of li based on text value

I have a <ul> in which there are some <li>.I want width of li to increase based on value of text ?

sample code :

<ul class="navTopstories">
    <li>Onsafsf sdsfsfs fsdsdfsdf</li>
    <li>two</li>
    <li>Three</li>      
</ul>

css :

.navTopstories li,.navWorld li{
    width: 80px;
    background-color: #333;
    color: white;
    text-align: center;
    padding-top: 5px;
    padding-bottom: 5px;
    border-bottom: 1px solid white;
}

Upvotes: 0

Views: 489

Answers (2)

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14891

By default an LI is a block element, meaning it will take up as much width as possible. Specifying the width property is restricting the box model to just 80px. To make the box only as wide as the content you need to change the LI to an inline element:

.navTopstories li,.navWorld li{
    width: 80px;

into

.navTopstories li,.navWorld li{
    display: inline;

This will make the LI flexible and fit the content, however it will also bump the LI against each other as the browser now thinks they are words in a sentence. To get around this, we add another element to the mix, the after pseudo-element:

.navTopstories li:after, .navWorld li:after {
    content: " ";
    display: block;
    height:1em;
}

This creates a new block element after the LI element that is taking up as much width as possible (100%) which breaks the LI on either side of it onto two lines. You need content:" " to make the pseudo element work, and I've added the height to show some white space between the LI so you can see that they are separated.

And here's a JSFiddle :)

http://jsfiddle.net/7LtQN/2/

Happy Coding :)

Upvotes: 1

Zentoaku
Zentoaku

Reputation: 767

Delete:

width: 80px;

and/or set on ul/li:

width: auto;

Upvotes: 0

Related Questions