为什么父元素的宽度不会自动扩展到子元素的宽度?(涉及IT技术)

3
我试图显示需要水平滚动的大量数据。
我的注意力被吸引到一个问题上,即body不会自动调整为其子元素的宽度。这是一个问题,因为一些其他元素需要样式,这些样式应该自动调整以匹配超出视口的元素。
不幸的是,它停留在body的宽度处。你会认为body也会调整为与其子元素相匹配的宽度,但事实并非如此。
我该如何使body和/或其他元素自动调整大小?这在chrome、firefox、edge和ie11中都会出现。
请参见fiddle和代码: 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>

4个回答

3
不幸的是,它只停留在body的宽度上。你会认为body也会调整大小以匹配其子元素的宽度,但实际上并不会。这就是默认情况下块状元素的工作方式 - 填充视口宽度。你需要的是一个内联元素,它只扩展其内容所需的空间。
您可以使用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>


1
抱歉回复晚了,被其他项目分心了。这太棒了!谢谢。 - Dave Maison

1
也许这是 body 元素的默认行为。您可以添加此规则。
body {
    min-width: min-content;
}

body 会自动调整以适应其他元素的内容


0

你可以通过在"#extra-long"中添加以下小的CSS来进行管理:

<style>
#extra-long{
white-space: nowrap;
}
</style>

通过添加以上 CSS,您的文本将始终在单行中,并自动滚动。


问题不在于文本换行,而在于容器的宽度。它会自动停在主体边缘,同时允许子元素溢出。 - Dave Maison

0
您还没有为第二个 div 提供宽度,只有背景颜色:
    #other-element {
  background-color: cornflowerblue;
  width: 200vw;
}

这会带来一个问题,即宽度只能是200vw,而不能自动扩展到内容的宽度。 - Dave Maison

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接