wrongusername
wrongusername

Reputation: 18918

How can I wrap divs?

Basically, I want the inner divs outside the outer div to wrap according to the width of the outer div, which in turn expands and contracts according to the width of the browser window, like so:

.---------------------.
|                     | <-- Browser Window
| .-----------------. |
| |  ,-,  ,-,  ,-,  | |
| |  |X|  |X|  |X|  | |
| |  `-`  `-`  `-`  | |
| |                 | |
| |  ,-,  ,-,  ,-,  | |
| |  |X|  |X|  |X|  | |
| |  `-`  `-`  `-`  | |
| `-----------------` |
|                     |
`---------------------`

.-------------------------------.
|                               | <-- Browser Window enlarged
| .---------------------------. |
| |  ,-,  ,-,  ,-,  ,-,  ,-,  | |
| |  |X|  |X|  |X|  |X|  |X| <----- Inner divs wrap around accordingly, as if
| |  `-`  `-`  `-`  `-`  `-`  | |     they are text
| |                           | |
| |  ,-,                      | |
| |  |X|                      | |
| |  `-`                      | |
| `---------------------------` |
|                               |
`-------------------------------`

What would be the best (as in simplest in terms of developer time) way to make this happen?

Upvotes: 18

Views: 35154

Answers (4)

Not sure why hasn't anyone mentioned flex-wrap CSS property:

display: flex;
flex-wrap: wrap;
flex-direction: row;

For my case this does exactly what the OP asked. And it lets me use flexbox, too.

Upvotes: 3

Lukas
Lukas

Reputation: 7734

Set for this blocks - display: inline-block, and for main container some width...

  .div {
     display: inline-block;
  }

http://jsfiddle.net/guh5Z/1/

Upvotes: 25

Jon Newmuis
Jon Newmuis

Reputation: 26492

You can just apply float: left to each of the inner divs. See the following jsFiddle as an example (try resizing the result pane to see the behavior):

jsFiddle (Live): http://jsfiddle.net/guh5Z/

Source Code:

<html>
<head>
    <style type="text/css">
        #outer {
            width: 90%;
            height: 90%;
            margin: 5%;
            overflow: auto;
            background-color: red;
        }

        .inner {
            float: left;
            width: 150px;
            height: 150px;
            margin: 20px;
            background-color: blue;
        }
    </style>
<body>
    <div id="outer">
        <div class="inner">X</div>
        <div class="inner">X</div>
        <div class="inner">X</div>
        <div class="inner">X</div>
        <div class="inner">X</div>
        <div class="inner">X</div>
    </div>
</body>
</html>

Upvotes: 5

user1115538
user1115538

Reputation:

You could use <ul> instead if you'll put text instead. Something like this :

CSS:

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  width: 100px;
  height: 120px;
  border: 1px solid;
  float: left;
  margin: 5px;
}

HTML:

<ul>
  <li>Random text here</li>
  <li>Random text here</li>
</ul>

I hope that helps

Upvotes: 2

Related Questions