简体   繁体   中英

Stopping floated divs from wrapping to a new line

I have a container that contains a number of left-floated divs, something like:

<div id="container">
    <div class="panel"></div>
    <div class="panel"></div>
    <div class="panel"></div>
</div>

<style>
    .panel {float:left; width:200px;}

</style>

In my app, the user can add more and more panels to the container dynamically, and I'd like them to always stack up on the right, and for a horiz scroll bar to appear when the user has exceeded the available space.

jsfiddle here: http://jsfiddle.net/yzTFC/6/

Floated elements are dependent upon the width of their container and do no affect the size of the container. If it is possible, do not use floated elements in this case. I would use display:inline-block with a white-space:nowrap on the parent.

http://jsfiddle.net/yzTFC/45/

Another method would be to give an insanely large width on the container but I wouldn't advise this as it is seems sloppy.

http://jsfiddle.net/yzTFC/52/

Here is a good article on how floats work: http://coding.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/

Try this:

HTML

<div id="parent-container">
    <div id="container">
        <div class="panel"></div>
        <div class="panel"></div>
        <div class="panel"></div>
        <div class="panel"></div>
        <div class="panel"></div>
        <div class="panel"></div>
    </div>
</div>​

CSS

.panel {float:left; width:200px; background-color:red; height:100px; border:solid 1px black;}

#container { width: 9999px; }

#parent-container {
    overflow: auto;
}​

Demo: http://jsfiddle.net/yzTFC/50/

My answer is similar to Ayman. I have also added another container.

HTML

<div id="wrapper">
    <div id="panel-container">
        <div class="panel"></div>
        <div class="panel"></div>
        <div class="panel"></div>
        <div class="panel"></div>
        <div class="panel"></div>
        <div class="panel"></div>
    </div>
</div>​

CSS

.panel {float: left; width:200px; background-color:red; height:100px; border:solid 1px black;}
#wrapper {width: 606px; overflow-x: scroll; overflow-y: hidden; }
#panel-container {width: 1212px;}

Where #panel-container CSS width is a multiple of the .panels within it, so it would take some scripting to achieve this. Most likely some javascript.

The #wrapper width was arbitrary, I just decided to show three panels at a time in the viewport.

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