Luke
Luke

Reputation: 5708

Properly expanding an element with a scroll bar to fit child content width

Say I have a <ul> with the following css:

position:relative;
border: solid;
border-radius:2px;
height:350px;
overflow:auto;
padding-left: 2px;
display:inline-block;
list-style-type:none;

When I add <li> elements to the <ul> as its children, the div expands horizontally in order to fit the width of the child nodes.

However, the scroll bar takes up space within the div.

When enough children are added to require the scroll bar, the widest text nodes wrap the last word.

The only way I have found to fix this behavior is to set the <ul>s white-space property to nowrap, but that just makes the text flow past the boundary, rather than expanding the boundary itself and creates an ugly horizontal scroll bar.

Demo

ul {
  position: relative;
  border: solid;
  border-radius: 2px;
  height: 150px;
  overflow: auto;
  padding-left: 2px;
  display: inline-block;
  list-style-type: none;
  /*Uncomment below to see the effect of adding nowrap*/
  /*white-space: nowrap;*/
}
<ul>
  <li>short</li>
  <li>short</li>
  <li>short</li>
  <li>short</li>
  <li>short</li>
  <li>short</li>
  <li>short</li>
  <li>LONG STUFF-STUFF</li>
  <li>short</li>
  <li>short</li>
  <li>short</li>
  <li>short</li>
  <li>short</li>
</ul>

jsFiddle of the same snippet, in case you prefer to work with that: https://jsfiddle.net/Lg0s231g/1/

Upvotes: 2

Views: 1417

Answers (1)

Rokin
Rokin

Reputation: 2127

Your <ul> element is already shrinking to fit, as it's set to inline-block. You just have to add extra room for the scrollbar.

Add:

overflow-x: clip;
padding-right: 20px;
white-space: nowrap;

Here is JSFiddle

Upvotes: 1

Related Questions