在滚动的flexbox容器上扩展背景

时间:2017-01-28 12:50:03

标签: html css flexbox scrollbar overflow

如何使用flexbox和宽度有限的容器将背景扩展到右侧?

跨度是必须包含背景颜色的标记,而不是父标记。 (因为每个跨度的颜色可能不同)

我知道显示tabletable-row修复了它,但它给我带来了填充和边框的其他问题,因此我想使用flexbox模型。

还有另一个要求,背景应延伸到最宽的范围,因此所有跨度应具有相同的宽度并将背景扩展到相同的位置。



pre {
  width: 300px;
}

code {
  display: flex;
  flex-direction: column;
  overflow: auto;
}

span {
  background-color: #ddd;
}

<pre>
  <code>
    <span>sadfasdsad asd adsads  das ads dasdasdas  dasd as das</span>
    <span>sadfdas das adsdsad sa dasda s adsasdsad asd adsads  das ads dasdas</span>
  </code>
</pre>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

如果你稍微重新排列CSS规则/属性,它将起作用

pre {
  width: 300px;
  display: flex;
  overflow: auto;
}
code {
  display: flex;
  flex-direction: column;
}
span {
  background-color: #ddd;
}
span ~ span {
  background-color: #aaa;
}
<pre>
  <code>
      <span>sadfasdsad asd adsads  das ads dasdasdas  dasd as das</span>
      <span>sadfdas das adsdsad sa dasda s adsasdsad asd adsads  das ads dasdas</span>
  </code>
</pre>

更新

可以通过删除标记中的换行符/空格来修复IE11 / Edge中可能出现的不需要的额外间距(可能还有一些)

<pre>
  <code><span>sadfasdsad asd adsads  das ads dasdasdas  dasd as das</span><span>sadfdas das adsdsad sa dasda s adsasdsad asd adsads  das ads dasdas</span></code>
</pre>

另一种选择是将pre / code更改为div(在Chrome,Firefox,Edge,IE11上成功测试)

div.pre {
  width: 300px;
  display: flex;
  overflow: auto;
}
div.code {
  display: flex;
  flex-direction: column;
  white-space: nowrap;
}
span {
  background-color: #ddd;
}
span ~ span {
  background-color: #aaa;
}
<div class="pre">
  <div class="code">
      <span>sadfasdsad asd adsads  das ads dasdasdas  dasd as das</span>
      <span>sadfdas das adsdsad sa dasda s adsasdsad asd adsads  das ads dasdas</span>
  </div>
</div>

答案 1 :(得分:0)

margin:auto添加到span

&#13;
&#13;
pre {
  width: 300px;
}

code {
  display: flex;
  flex-direction: column;
  overflow: auto;
}

span {
  background-color: #ddd;
  margin: auto;
}
&#13;
<pre>
  <code>
    <span>sadfasdsad asd adsads  das ads dasdasdas  dasd as das</span>
    <span>sadfdas das adsdsad sa dasda s adsasdsad asd adsads  das ads dasdas</span>
  </code>
</pre>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

align-items:flex-start将为您提供帮助

code {
  display: flex;
  flex-direction: column;
  align-items:flex-start;
  width: 300px;
  overflow: auto;
}

span {
  background-color: #ddd;
}
<pre>
  <code>
    <span>sadfasdsad asd adsads  das ads dasdasdas  dasd as das</span>
    <span>sadfdas das adsdsad sa dasda s adsasdsad asd adsads  das ads dasdas</span>
  </code>
</pre>