全宽div内的水平可滚动div

时间:2017-11-18 14:03:55

标签: html css horizontal-scrolling

enter image description here 我有一个水平适合屏幕的分区,我有5个分区,我想在屏幕上显示4个分区,当我水平滚动分区时会出现1个分区。我希望滚动条只出现在div中,而不是出现在浏览器窗口中。

下面是我的非工作代码,它将h1标记放在左边,我想要它在左上角然后在它下面所有5个div

.outer {
  overflow-x: scroll;
  width: 100%;
}

.inner {
  width: 25%;
  float: left;
}
<div class="outer">
  <h1>Header Title</h1>
  <div class="inner">
  </div>
  <div class="inner">
  </div>
  <div class="inner">
  </div>
  <div class="inner">
  </div>
  <div class="inner">
  </div>
</div>

2 个答案:

答案 0 :(得分:12)

您可以使用 Flexbox 执行此操作:

.outer {
  display: flex; /* displays flex-items (children) inline */
  overflow-x: auto;
}

.inner {
  flex: 0 0 25%; /* doesn't grow nor shrink, initial width set to 25% of the parent's */
  height: 1em; /* just for demo */
}
<div class="outer">
  <div class="inner" style="background: red"></div>
  <div class="inner" style="background: green"></div>
  <div class="inner" style="background: blue"></div>
  <div class="inner" style="background: yellow"></div>
  <div class="inner" style="background: orange"></div>
</div>

使用h1元素的解决方案:

.outer {
  display: flex;
  flex-direction: column;
  overflow-x: auto;
}

.middle {
  display: flex;
  flex: 1;
}

.inner {
  flex: 0 0 25%;
  height: 1em;
}
<div class="outer">
  <h1>Header Title</h1>
  <div class="middle">
    <div class="inner" style="background:red"></div>
    <div class="inner" style="background:green"></div>
    <div class="inner" style="background:blue"></div>
    <div class="inner" style="background:yellow"></div>
    <div class="inner" style="background:orange"></div>
  </div>
</div>

答案 1 :(得分:-1)

我不确定我是否误解了你,但我认为你想要做的就是将H1超过5格,就像这样:

https://jsfiddle.net/p78L2bka/

.outer {
  display: flex;
  overflow-x: scroll;
}

.middle {
  display: flex;
  width: 100%;
}

.inner {
  flex: 0 0 25%;
  height: 100px;
}
<h1>Header Title</h1>
<div class="outer">
  <div class="middle">
    <div class="inner" style="background: red">
    1
    </div>
    <div class="inner" style="background: green">
    2
    </div>
    <div class="inner" style="background: blue">
    3
    </div>
    <div class="inner" style="background: yellow">
    4
    </div>
    <div class="inner" style="background: orange">
    5
    </div>
  </div>
</div>