【问题标题】:How to make inner div adjust width to its child elements如何使内部 div 调整其子元素的宽度
【发布时间】:2016-04-14 04:02:01
【问题描述】:

我有一个具有宽度、高度和溢出-x 自动的容器 div。我希望能够水平滚动里面的元素。在里面我有一个容纳所有元素的内部容器。

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

这是我的小提琴。

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>

【问题讨论】:

  • 我喜欢多重height:100%;:D

标签: html css scroll width overflow


【解决方案1】:

您需要在.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>

【讨论】:

  • 要删除inline-bock元素之间的空白,请将font-size:0添加到父元素,然后再次为子元素添加font-szie - JSFiddle
猜你喜欢
  • 2015-11-27
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 2015-10-14
相关资源
最近更新 更多