Dellirium Dellirium - 1 year ago 91
Javascript Question

Div with dynamic width sized to dynamic number of divs that float top

I have an issue trying to force the CSS to work the way I want it to. Below you will find a 2 pictures and a description of what the behaviour should be like. All the CSS and content is dynamically created so any form of "flexibility" is doable, though if possible, should be avoided.

The RED div has dynamical width (width:auto) and needs to be filled with a bunch of BLACK divs. The number of black divs is random, or rather depends on a case-to-case basis.

Picture1 and Picture2 show how the menu should expand in case the amount of black divs is taking more space then one height (which is fixed to 720px). In case a thrid column was to be needed, it once again should be expanded towards left.

I've searched around and found this CSS:

#redDiv {
-moz-column-count: 2;
-moz-column-gap: 50%;
-webkit-column-count: 2;
-webkit-column-gap: 50%;
column-count: 3;
column-gap: 50%;

however there are three issues there:

  • First one, the amount of columns needs to be fixed this way, and I need it to dynamically suit the content that fills it.

  • Secondly, I do not think that this is meant to be done with dynamical width divs, mainly because gap and width have no meaning there.

  • Lastly, even if I do use the javascript to determin the number of columns, the table expands to the right and I need it to expand to the left, because it is docked to the right side of the screen with some controls being there.

EDIT: (js fiddle) UPDATED


<div id="rightdocked">
<div id="RedDiv">
<div class="blackdivs"></div>
<div class="blackdivs"></div>
<div class="blackdivs"></div>
<div class="blackdivs"></div>
<div class="blackdivs"></div>


.blackdivs {
position: relative;
margin-top: 0px;
margin-bottom: 20px;
width: 300px;
height: 40px;
border: solid 2px black;
background-color: white;

.blackdivs:first-of-type {
background-color: green;

#RedDiv {
max-height: 180px;
width: auto;
z-index: 9;
background-color: lightgreen;
position: relative;
float: left;
background-color: white;
border: 2px red solid;

#rightdocked {
position: relative;
width: auto;
height: 300px;
float: right

Any suggestions?

anu anu
Answer Source

Here is some code to get you started. I guess this is the behavior you wanted. I have kept max-height to 120px for demo, you can change it to 720px. Just keep on pressing add box button to add inner divs.

$('#addBoxButton').click(function() {
  $('.outer').append('<div class="inner">innner</div>');
.outer {
  border: 1px solid red;
  max-height: 120px;
  width: inherit;
  display: flex;
  flex-wrap: wrap-reverse;
  flex-direction: column;
.inner {
  border: 1px solid black;
  width: 50px;
  height: 20px;
  margin: 5px
<script src=""></script>
<div class='outer'>
<input id="addBoxButton" type="button" value="add box" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download