我有一个使用html和CSS的示例,链接如下:https://js.do/sun21170/inner-width-not-taking-whole-of-outer-width
问题是,带有绿色背景的内部div没有采用外部div的整个滚动宽度。
问:除了将内部div的宽度设置为150%左右之外,是否有一些CSS可以用于使内部div样式应用于外部div的整个滚动宽度?
我使用的示例代码如下。

<div class="outerDiv">
    <div class="innerDiv">
      This is inner div This is inner div This is inner div This is inner div This is inner div This is inner div This is inner div
    </div>
</div>

<style>
.outerDiv {
   max-width:500px;
   border:2px solid purple;
   overflow:auto;
   height: 100px;
}
.innerDiv {
   border:1px dashed red;
   background-color: lightgreen;
   white-space:nowrap;
   width:100%;
}
</style>

最佳答案

是的,只需将.innerDiv设置为display: inline-block;。这样,.innerDiv的行为就像一个内联元素,如果您不指定width,它总是和它的内容一样宽。
下面是一个工作示例:

.outerDiv {
   max-width:500px;
   border:2px solid purple;
   overflow:auto;
   height: 100px;
}
.innerDiv {
   display: inline-block; /* ← this does the trick */
   border:1px dashed red;
   background-color: lightgreen;
   white-space:nowrap;
   /* width: 100%; ← this has to be removed */
}

<div class="outerDiv">
    <div class="innerDiv">
      This is inner div This is inner div This is inner div This is inner div This is inner div This is inner div This is inner div
    </div>
</div>

10-05 20:41