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?
You just put width property to ul element.
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.
Using inline-block property: Use display: inline-block property to set a div size according to its content.
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.
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.
The table width should be 100% so that the width of a table adjusts to the current width of the browser window.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With