PDA

View Full Version : How do I stop floated divs from wrapping?



BoroDrummer
01 Mar 2011, 05:06 AM
I'm trying to dynamically add a set of divs to a parent div. I want the divs to display horizontally and for the parent div to scroll when there are too many to fit in the screen width. This is my code so far. I can't seem to stop the divs from wrapping... Is this even possible? Or should I use a table instead?


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<style type="text/css">
.wrap
{
background-color:Red;
width:100%;
overflow:auto;
white-space:nowrap;
}

.block
{
background-color:blue;
margin:10px;
width:auto;
float:left;
}
</style>
</head>
<body>
<div class="wrap">
<div class="block">
<p>This is a block. This is a block. This is a block. This is a block. This is a block. This is a block. This is a block. </p>
</div>
<div class="block">
<p>This is a block. This is a block. This is a block. This is a block. This is a block. This is a block. This is a block. </p>
</div>
<div class="block">
<p>This is a block. This is a block. This is a block. This is a block. This is a block. This is a block. This is a block. </p>
</div>
</div>
</body>
</html>

Wickham
01 Mar 2011, 08:01 AM
To get the .block divs to show side by side you need to add a width to the float: left; but then the white-space: nowrap makes the text extend outside the divs, so delete that:-


<style type="text/css">
.wrap
{
background-color:Red;
width:100%;
overflow:auto;
/*white-space:nowrap;*/
}

.block
{
background-color:blue;
margin:10px;
width: 200px;/*auto;*/
float:left;
}
</style>

Your .wrap div has width: 100%; so the three divs show side by side in a wide window but when the window resolution width is too small and then one or two divs will go to a lower line.