tags:

views:

4180

answers:

3
+4  Q: 

HTML UL width

Given the following markup:

<ul>
   <li>apple</li>
   <li class="highlight">orange</li>
   <li>pear</li>
</ul>

Both the ul's and the li's widths appear to be 100%. If I apply a background-color to the list item, the highlight stretches the full width of the page.

I only want the background highlight to stretch as wide as the widest item (with maybe some padding). How do I constrain the li's (or perhaps the ul's) width to the width of the widest item?

+1  A: 

Can you do it like this?

<ul>
   <li>apple</li>
   <li><span class="highlight">orange</span></li>
   <li>pear</li>
</ul>
BoltBait
exactly what I was going to say.
nickf
+8  A: 

Adding ul {float: left;} style will force your list into preferred width, which is what you want.

Problem is, you should make sure next element goes below the list, as it did before. Clearing should take care of that.

buti-oxa
A: 

Exactly as BoltBait said, wrap your text in an inline element, such as span and give that the class.

<ul>
    <li>apple</li>
    <li><span class="highlight">orange</span></li>
    <li>pear</li>
</ul>

My extra 2 cents is that if you don't have access to change the HTML, you can do it using Javascript. In jQuery:

$('li.highlight').wrapInner("<span></span>");

and use the CSS:

li.highlight span { background-color: #f0f; }


edit: after re-reading your question, can you clarify: do you want the highlight to only go as wide as the element which is highlighted, or as wide as the widest element in the list? eg:

    - short
    - items ********************
    - here
    - and then a really long one

...where the asterisks represent the highlighting. If so, then buti-oxa's answer is the easiest way. just be careful with clearing your floats.

nickf