Reputation: 14406
Is there anyway possible to auto fit the width of an <li> tag to the width of the text it contains using CSS?
I'm designing a website that uses a custom CMS (and I don't have access to the code), so I'm limited in options as far as design goes.
Javascript solutions that would work on an <li> tag without having to edit any of the list properties directly would work as well.
Upvotes: 7
Views: 37702
Reputation: 96
Adding display: inline;
CSS to the <ul>
block has worked great for me, with no undesired effects.
Upvotes: 1
Reputation: 53823
EDIT: Unfortunatly the following solution is displayed differently in different browsers.
In order to not let any other element float aside the list I used this:
ul {
white-space: pre-line;
margin: -25px 0 0; /* to compensate the pre-line down-shift */
}
ul li {
display: inline-block;
}
The only CSS solution that worked well for me.
Upvotes: 2
Reputation: 7330
The <li>
is a block-level element, so defaults to be as wide as it can be.
To get it to "shrinkwrap" to the size of the contents, try floating it:
li {
float:left;
clear:left;
}
That may do what you are looking for.
If you want the <li>
s to sit alongside each other you can try:
ul {
clear: left; /* I like to put the clear on the <ul> */
}
li {
float: left;
}
OR
li {
display: inline
}
Making it inline
takes away its block-level status, so it acts like a <span>
or any other inline element.
Upvotes: 19
Reputation: 1130
None of the previous answers work correctly for me, so I used the following approach:
Upvotes: 1
Reputation: 32179
You can use em's rather than pixels to specify the width of your element. An em is roughly equivalent to the width of the letter "m" in the default font. Play with multiples of the number of characters in your li until you have an em width that is visualy appealing.
Upvotes: 0
Reputation: 91734
As @willoller already said, the li element is a block level element, but apart from floating it, you can also use:
li {
display: inline;
}
Upvotes: 9
Reputation: 817
If have the id of the <li> tag you could use JavaScript to get how many characters there were and then multiply that by the font size, then set the li width to that number.
Upvotes: 0
Reputation: 36832
On standard compliant browsers, use min-width
instead of width
. On IE 6, width
does what you describe.
Upvotes: 1