2

仅使用 CSS,是否可以获得以下示例http://jsfiddle.net/LdJ7t/,而无需事先明确知道子元素的宽度?

期望的最终结果:

  • 父元素可滚动到子元素
  • 子元素的宽度设置为内容

可滚动到子内容的父元素

#Parent {
    width: 100px;
    height:200px;
    background: #ccc;
    overflow:auto;
    padding: .5em;
    margin: .5em;
}

#Child {
    width:300px;
    height:100px;
    background:yellow;
}​

<div id="Parent">
    <div id="Child">
        This is a test. This is a test.
    </div>
</div>​

看起来display:inline-block;几乎可以工作:http: //jsfiddle.net/LdJ7t/1/

我认为这是可能的。我只是找不到解决方案。

4

1 回答 1

5

您的inline-block解决方案是正确的 - 如果您将较长的文字或图像放入,则会出现滚动条。默认情况下,文本在空白处被破坏。

如果您不希望文本在空白处中断,您可以white-space: nowrap;像这里一样添加到子 div:http: //jsfiddle.net/LdJ7t/2/

于 2012-12-22T00:00:53.083 回答