我正在尝试显示大量需要水平滚动的数据。
我注意到身体不会自动调整到孩子的宽度。这成为一个问题,因为某些其他元素需要样式化,应自动调整大小以匹配超出视口的元素。
不幸的是,它停在身体的宽度。你会认为身体也会调整大小以匹配其孩子的宽度,但事实并非如此。
如何使身体和/或其他元素自动调整?这发生在chrome,firefox,edge和ie11中
请参阅fiddle和代码:
body {
border: 1px solid red;
padding: 1rem;
}
#extra-long {
background-color: salmon;
width: 200vw;
}
#other-element {
background-color: cornflowerblue;
}
<div id="extra-long">This extends beyond the view port</div>
<div id="other-element">This should automatically extend beyond the viewport, but it doesn't</div>
不幸的是,它停在身体的宽度。你会认为身体也会调整大小以匹配其孩子的宽度,但事实并非如此。
这就是块元素默认工作的方式 - 填充视口宽度。你需要的是一个内联元素,它只扩展其内容。
您可以使用inline-block
获得所需的行为 - 请参阅下面的演示:
body {
border: 1px solid red;
padding: 1rem;
display: inline-block; /* added */
}
#extra-long {
background-color: salmon;
width: 200vw;
}
#other-element {
background-color: cornflowerblue;
}
<div id="extra-long">This extends beyond the view port</div>
<div id="other-element">This should automatically extend beyond the viewport, but it doesn't</div>
您可以使用列内联灵活容器获得相同的效果 - 请参阅下面的演示:
body {
border: 1px solid red;
padding: 1rem;
display: inline-flex; /* added */
flex-direction: column; /* added */
}
#extra-long {
background-color: salmon;
width: 200vw;
}
#other-element {
background-color: cornflowerblue;
}
<div id="extra-long">This extends beyond the view port</div>
<div id="other-element">This should automatically extend beyond the viewport, but it doesn't</div>
你也可以使用width: min-content
,但请注意,最后有一个意想不到的body
边缘修剪 - 见下面的演示:
body {
border: 1px solid red;
padding: 1rem;
width: min-content; /* added */
}
#extra-long {
background-color: salmon;
width: 200vw;
}
#other-element {
background-color: cornflowerblue;
}
<div id="extra-long">This extends beyond the view port</div>
<div id="other-element">This should automatically extend beyond the viewport, but it doesn't</div>
也许这是body
元素的默认行为。您可以添加此规则。
body {
min-width: min-content;
}
body
将自动调整内容以满足其他元素
你可以通过在“#extra-long”中添加小css来管理这个,如下所示:
<style>
#extra-long{
white-space: nowrap;
}
</style>
通过添加上面的CSS,您的文本将始终在一行中,我自动滚动。
您没有为第二个div提供宽度,只是背景颜色:
#other-element {
background-color: cornflowerblue;
width: 200vw;
}