div的背景不会滚动内容

时间:2017-01-05 16:57:35

标签: html css listbox flexbox overflow

我有以下html片段,形成一个X-Y可滚动列表框

* {
  font-family: "consolas";
}
.listbox {
  border: 1px solid black;
  padding: 4px;
  width: 150px;
  height: 200px;
  display: flex;
  flex-direction: column;
}
.caption {
  font-weight: bold;
  background-color: #aaf;
  padding: 10px;
}
.content {
  flex-grow: 1;
  overflow: scroll;
}
.item {
  background-color: #ddd;
  padding: 2px;
  padding-left: 6px;
  margin-top: 4px;
  white-space: nowrap;
}
<div class="listbox">
  <div class="caption">Caption</div>
  <div class="content">
    <div class="item">One</div>
    <div class="item">Two</div>
    <div class="item">Three (this has a longer bit)</div>
    <div class="item">Four</div>
    <div class="item">Five</div>
    <div class="item">Six</div>
    <div class="item">Seven</div>
    <div class="item">Eight (so does this)</div>
    <div class="item">Nine</div>
    <div class="item">Ten</div>
  </div>
</div>

它工作正常,有一个问题,当用户从左向右滚动时,div的背景似乎被遗忘。就好像实际的div只会拉伸其父级的宽度,滚动/溢出的东西会以某种方式“伪造”。

为什么会这样?

如何解决问题?我想要的行为是所有项目看起来与最大项目的宽度相同。

1 个答案:

答案 0 :(得分:1)

尝试在将其设置为<div class="items">的项目周围添加容器display:inline-block

.items {
  display: inline-block;
}

* {
  font-family: "consolas";
}
.listbox {
  border: 1px solid black;
  padding: 4px;
  width: 150px;
  height: 200px;
  display: flex;
  flex-direction: column;
}
.caption {
  font-weight: bold;
  background-color: #aaf;
  padding: 10px;
}
.content {
  flex-grow: 1;
  overflow: scroll;
}
.items {
  display: inline-block;
}
.item {
  background-color: #ddd;
  padding: 2px;
  padding-left: 6px;
  margin-top: 4px;
  white-space: nowrap;
}
<div class="listbox">
  <div class="caption">Caption</div>
  <div class="content">
    <div class="items">
      <div class="item">One</div>
      <div class="item">Two</div>
      <div class="item">Three (this has a longer bit)</div>
      <div class="item">Four</div>
      <div class="item">Five</div>
      <div class="item">Six</div>
      <div class="item">Seven</div>
      <div class="item">Eight (so does this)</div>
      <div class="item">Nine</div>
      <div class="item">Ten</div>
    </div>
  </div>
</div>

说明:默认情况下,块级元素占用容器的100%宽度不超过该值,但是如果可用,则内联块将扩展为内容长度,例如:在一个可滚动的容器中。

同时应用.items {min-width: 100%;},以防您希望背景增加全宽,即使每行中文字较少。