Html 如何使父 div 自动调整到其子 div 的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15102480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:56:01  来源:igfitidea点击:

How to make a parent div auto size to the width of its children divs

htmlcss

提问by bradley4

I'm trying to make the parent div only as wide as the child div's. Auto width is making the parent div fit the entire screen. The children divs will be different widths depending on their content so I need the parent div to adjust accordingly.

我试图让父 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>

回答by Madbreaks

Your interior <div>elements should likely both be float:left. Divs size to 100% the size of their container width automatically. Try using display:inline-blockinstead of width:autoon the container div. Or possibly float:leftthe container and also apply overflow:auto. Depends on what you're after exactly.

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

回答by Explosion Pills

The parent div (I assume the outermost div) is display: blockand will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-blockis probably what you are going for:

父 div(我假设最外面的 div)是display: block并且将填充其容器(在本例中为主体)的所有可用区域。使用不同的显示类型——inline-block可能是你想要的:

http://jsfiddle.net/a78xy/

http://jsfiddle.net/a78xy/