如何使内部 div 调整其子元素的宽度

How to make inner div adjust width to its child elements

我有一个容器 div,其宽度、高度和 overflow-x auto。我希望能够水平滚动里面的元素。在里面我有一个内部容器可以容纳所有元素。

如果我给内部 div 一个固定宽度,在本例中为 3000 像素,它可以工作,但我希望它动态调整其宽度。我怎样才能做到这一点?

这是我的fiddle。

https://jsfiddle.net/95yb8k1f/

<div class="outer" style="width:100%; height:500px;overflow-x:auto;">
    <div class="inner" style="height:100%; width:3000px;">
       <div class="item" style="height:100%; width:300px; float:left;">
       <div class="item" style="height:100%; width:300px; float:left;">
       <div class="item" style="height:100%; width:300px; float:left;">
       <div class="item" style="height:100%; width:300px; float:left;">
   </div>
</div>

您需要在 .inner 上使用 white-space:nowrap; 并在 .item

上使用 display: inline-block;

div.outer {
  width:100%;
  height:400px;
  overflow-x:scroll;
  overflow-y: hidden;
}

div.inner {
  position:relative;
  height:100%;
  white-space:nowrap; 
}

div.item {
  width:300px;
  height:100%;
  display: inline-block;
}

div.item:nth-child(2n+1){
  background:blue;
}

div.item:nth-child(2n+2){
  background:green;
}
<div class="outer">
  <div class="inner">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
</div>