简体   繁体   中英

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

I got a div which has the width of my screen. It has overflow: scroll . In this div I have 0-n other divs which can have varying widths.

I want my div to grow with its content, so I can simply scroll horizontal. However, my div just grows in height, and its content just stacks vertically. display: inline-block doesnt work on the content.

How can I solve this Problem?

PS: It works if I set a fixed width to my div, of course this is too wide or too small most of the time.

Thanks!

Do you mean this?

If you don't want to define a width, you can use jQuery for that. How? Like this

 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>

You can use a mixture of inline-block and white-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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM