如何使用flexbox和宽度有限的容器将背景扩展到右侧?
跨度是必须包含背景颜色的标记,而不是父标记。 (因为每个跨度的颜色可能不同)
我知道显示table
和table-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;
答案 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
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;
答案 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>