1

Assume the following HTML5 document:

<!doctype html>
<html>
 <head><title>try</title>
 </head>
 <body>
  <h1>testing</h1>
  <ul id='ul_id'>
   <li id='li1_id'>one</li>
   <li id='li2_id'>somelongertwo</li>
  </ul>
</body></html>

what would be the CSS3 stylesheet so that the width of <ul id='ul_id'> element would be the smallest to fit, so would be here the width of <li id='li2_id'> plus its bullet, since the second list item is the widest item of the <ul id='ul_id'> element?

I don't want the width of my <ul id='ul_id'> to be as wide as the containing <body>

The context and motivation of this question is my optimizing (nearly minimizing) width of jqueryui menu question.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547

2 Answers2

2

What would be the CSS3 stylesheet so that the width of <ul id='ul_id'> element would be the smallest to fit

You could change the display of the ul element to inline-block.

In doing so, it will have a "shrink-to-fit" width based on the size of the children elements.

Based on section 10.3.9 of the relevant spec for inline-block elements in normal flow:

If width is auto, the used value is the shrink-to-fit width as for floating elements.

#ul_id {
  display: inline-block;
  background-color: #f00;
}
<ul id='ul_id'>
  <li id='li1_id'>one</li>
  <li id='li2_id'>somelongertwo</li>
</ul>

Alternatively, setting the display to table would result in similar behavior.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
1
#ul_id {
   display: inline-block;
}

or

#ul_id {
   float: left;
}
#ul_id:after {
   clear: both;
}

One of these two should work as expected. Width resize to fit container is caused by display: block behaviour which is default for ul element.

Aki
  • 2,818
  • 1
  • 15
  • 23