Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I constrain a <ul>'s width to the width of the widest item?

Tags:

html

css

Given the following markup:

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

Both the uls and the lis 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 lis (or perhaps the uls) width to the width of the widest item?

like image 328
Jacob Carpenter Avatar asked Oct 31 '08 00:10

Jacob Carpenter


People also ask

How do you increase the width of an UL?

You just put width property to ul element.

How do you prevent padding from increasing width?

To avoid the width or height getting increased or decreased when using CSS properties like margin , padding , etc, we can use the CSS property called box-sizing and set its value to border-box on the element in CSS.

How do I set the width of a div to its content?

Using inline-block property: Use display: inline-block property to set a div size according to its content.

How do you auto adjust width in CSS?

Using width, max-width and margin: auto; Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins: This <div> element has a width of 500px, and margin set to auto.

What does width 100% do in CSS?

It seems like this should be one of the easiest things to understand in CSS. If you want a block-level element to fill any remaining space inside of its parent, then it's simple — just add width: 100% in your CSS declaration for that element, and your problem is solved.

What should be the value of the width attribute so that the width of the element adjusts itself to the current width of its parent element?

The table width should be 100% so that the width of a table adjusts to the current width of the browser window.


1 Answers

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.

like image 156
buti-oxa Avatar answered Sep 20 '22 13:09

buti-oxa