我有一个带有固定宽度的div容器,有些子元素可能比父级更大。
是否可以让所有子元素从父元素(overflow: auto
)中获取可滚动区域的整个宽度?
#container {
width: 200px;
background-color: grey;
overflow:auto;
margin:10px;
}
#container p{
display:block;
background-color: green;
white-space: nowrap;
width: 100%;
}
<div id="container">
<p>Sample Text 1</p>
<p>Sample Text 2</p>
<p>A very very very very very long Sample Text</p>
</div>
这是fiddle。向右滚动时,您可以看到子元素background-color小于内容。
答案 0 :(得分:8)
将内容包装在div中,并将其设置为display: inline-block
:
#container {
width: 200px;
background-color: grey;
overflow: auto;
margin: 10px;
}
#container>div {
display: inline-block;
}
#container p {
display: block;
background-color: green;
white-space: nowrap;
}
&#13;
<div id="container">
<div>
<p>Sample Text 1</p>
<p>Sample Text 2</p>
<p>A very very very very very long Sample Text</p>
</div>
</div>
&#13;
答案 1 :(得分:2)
您可以将子元素设置为display:table-row;
#container {
width: 200px;
background-color: grey;
overflow: auto;
}
#container p {
display: table-row;
background-color: green;
white-space: nowrap;
}
<div id="container">
<p>Sample Text 1</p>
<p>Sample Text 2</p>
<p>A very very very very very long Sample Text</p>
</div>
如果您需要额外的样式控件,请添加额外的<div>
。
#container {
width: 200px;
background-color: grey;
overflow: auto;
}
#container div {
display: table;
border-spacing: 0 10px;
}
#container p {
display: table-row;
background-color: green;
white-space: nowrap;
}
<div id="container">
<div>
<p>Sample Text 1</p>
<p>Sample Text 2</p>
<p>A very very very very very long Sample Text</p>
</div>
</div>
答案 2 :(得分:0)
你可以使用绝对位置属性来做到这一点。
#container {
width: 200px;
background-color: grey;
overflow:auto;
margin:10px;
}
#container p{
display:block;
background-color: green;
white-space: nowrap;
position:absolute;
}
&#13;