cabralpinto
cabralpinto

Reputation: 2098

CSS: make multiple divs float down and then right when end of document is reached

My code creates a set of .rectangle divs that all seem to "float down". I would like them to float down until no more fit in the container and then create one more column to the right and so on. Can I achieve this with css?

I have made a jsfiddle to demonstrate here.

Upvotes: 0

Views: 65

Answers (4)

To make the div containers to be stacked horizontally until they reach the end of outer div, your code should look like this:

.rectangle {
  background: snow;
  border: 1px solid black;
  text-align: center;
  height: 55px;
  width: 90px;
  margin: 10px;
  display: inline-block;
  /*float property?*/
}

The inline-block value is also supported my most, if not all, browsers.

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122155

You can use Flexbox and set flex-direction: column on parent and flex-wrap: wrap.

for (i = 0; i < 9; i++) {
  $("<div class='rectangle'>" + i + "</div>").appendTo("body")
}
body {
  display: flex;
  flex-direction: column;
  height: 100vh;
  flex-wrap: wrap;
  align-content: flex-start;
}

.rectangle {
  background: snow;
  border: 1px solid black;
  text-align: center;
  height: 55px;
  width: 90px;
  margin: 10px;
  /*float property?*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

G-Cyrillus
G-Cyrillus

Reputation: 106078

You can also use column :

https://jsfiddle.net/9zowa181/8/

for (i = 0; i < 9; i++) {
  $("<div class='rectangle'>" + i + "</div>").appendTo("body")
}
body {
  overflow-x: auto;
  overflow-y: hidden;
  -moz-column-width: 100px;
  column-width: 100px;
  -moz-column-fill: auto;
  column-fill: auto;
  height: 100vh;
  margin: auto;
}

.rectangle {
  background: snow;
  border: 1px solid black;
  text-align: center;
  height: 55px;
  width: 90px;
  margin: 10px 10px 0;
  display: inline-block;/* avoid boxe to be broken within 2 cols */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Facundo La Rocca
Facundo La Rocca

Reputation: 3876

Take a look at this fiddle

The trick is to use a flexbox container and apply flex-direction: column; and flex-wrap: wrap; like this:

.container{
  display: flex;
  height: 300px;
  width: 200px;
  flex-direction: column;
  flex-wrap: wrap;
}

Upvotes: 0

Related Questions