簡體   English   中英

如何使 div 與其內容的大小相同,而內容沒有換行符?

[英]How to make a div the size of its content, while the content has no line-break?

我有一個與我的屏幕一樣寬的div 它有overflow: scroll 在這個 div 中,我有0-n其他 div,它們可以具有不同的寬度。

我希望我的 div 隨着它的內容增長,所以我可以簡單地水平滾動。 然而,我的 div 只是在高度上增長,它的內容只是垂直堆疊。 display: inline-block對內容不起作用。

我怎么解決這個問題?

PS:如果我為我的 div 設置一個固定的寬度,它會起作用,當然大多數時候這太寬或太小了。

謝謝!

你是這個意思嗎?

如果您不想定義寬度,則可以使用 jQuery。 如何? 像這樣

 var width = $('.child').width();; $('.inner .child').each(function() { width += $(this).width(); }); $('.inner').css('width', width)
 .child{ width:200px; height:100px; background:yellow; border:1px solid #000; display:inline-block; } .parent{ overflow-x:auto; width:100%; border:1px solid red; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div class="parent"> <div class="inner"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div> </div> </body>

您可以混合使用inline-blockwhite-space:nowrap

 .parent { white-space:nowrap; /* make children all on one line */ width:100%; overflow:auto; } .child { display: inline-block; /* make inline block so obeys parent's white space */ white-space: normal; /* reset white space for children */ }
 <div class="parent"> <div class="child">lots of text and stuff</div> <div class="child">lots of text and stuff</div> <div class="child">lots of text and stuff</div> <div class="child">lots of text and stuff</div> <div class="child">lots of text and stuff</div> <div class="child">lots of text and stuff</div> <div class="child">lots of text and stuff</div> </div>

暫無
暫無

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

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