簡體   English   中英

如何使父div自動調整其子div的寬度

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

我正在嘗試使父 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>

你的內部<div>元素應該都是float:left 將尺寸划分為容器寬度的100%自動。 嘗試在容器div上使用display:inline-block而不是width:auto 或者可能float:left容器並應用overflow:auto 取決於你究竟追求的是什么。

父div(我假設最外面的div)是display: block ,它將填充其容器的所有可用區域(在本例中為body)。 使用不同的顯示類型 - inline-block可能是你想要的:

http://jsfiddle.net/a78xy/

我為此苦苦掙扎,正在設置我的父組件的寬度。 偶然發現了 CSS width: fit-content ;

這是一個例子:

 .outerContainer { width: 300px; height: 300px; background: gray; }.innerContainer { width: fit-content; border: 3px solid red; }.item { width: 200px; height: 200px; padding: 10px; background: blue; }
 <div class="outerContainer"> <div class="innerContainer"> <div class="item"> </div> </div> </div>

在示例中, innerContainer div(紅色背景的那個)適合item容器的內容。 outerContainer div 用於顯示對比度。

這是使您的父 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 }
 <div class="container-fluid"> <div class="wrapper">xxx</div> </div>

我希望有人覺得這很有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM