如何使父div自动大小为其子div的宽度

bra*_*ey4 66 html css

我试图让父div只和子div一样宽.自动宽度使父div适合整个屏幕.子div将根据其内容的宽度不同,所以我需要父div来相应调整.

<div style='width:auto;'>
  <div style="width: 135px; float: left;">
    <h4 style="padding-right: 5px; padding-left: 15px;">Column1</h4>
    <dl style="padding-right: 5px; padding-left: 15px; margin-top: -8px; overflow-x: hidden;">
      <dd style="white-space: nowrap;">1</dd>
      <dd style="white-space: nowrap;">2</dd>
    </dl>

    <h4 style="padding-right: 5px; padding-left: 15px;">Column1</h4>
    <dl style="padding-right: 5px; padding-left: 15px; margin-top: -8px; overflow-x: hidden;">
      <dd style="white-space: nowrap;">1</dd>
      <dd style="white-space: nowrap;">2</dd>
    </dl>
  </div>

  <div style="width: 135px; float: right;">
    <h4 style="padding-right: 5px; padding-left: 10px;">Column2</h4>
    <dl style="padding-right: 5px; padding-left: 15px; margin-top: -8px; overflow-x: hidden;">
      <dd style="white-space: nowrap;">1</dd>
      <dd style="white-space: nowrap;">2</dd>
      <dd style="white-space: nowrap;">3</dd>
    </dl>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Mad*_*aks 76

你的内部<div>元素应该都是float:left.将尺寸划分为容器宽度的100%自动.尝试使用display:inline-block而不是width:auto容器div.或者可能float:left是容器也适用overflow:auto.取决于你究竟追求的是什么.

  • @Madbreaks 我知道。这就是为什么我正在寻找一个 hack 来做到这一点。js方式是可用的,但我无法找出纯css方式。无论如何,感谢您的关注。 (2认同)

小智 53

这是让父 div 继承其子宽度的最简单方法。

.container-fluid {
  border: 1px solid black;
  /*the needed css class to make your parent div responsive to it's children's max-width
  */
  width: max-content
}
.wrapper {
  border: 1px solid red;
  width: 300px
}
Run Code Online (Sandbox Code Playgroud)
<div class="container-fluid">
  <div class="wrapper">xxx</div>
</div>
Run Code Online (Sandbox Code Playgroud)

我希望有人觉得这很有用


Exp*_*lls 20

父div(我假设最外面的div)是display: block并且将填充它的容器的所有可用区域(在这种情况下,身体).使用不同的显示类型 - inline-block可能是你想要的:

http://jsfiddle.net/a78xy/