Skip to content Skip to sidebar Skip to footer

Prevent Divs From Wrapping When Parent Is Too Small

How can I stop the divs inside of this parent div from wrapping instead of just being cut off? Code: jsfiddle As you can see, as I change the size of the parent div, the divs ins

Solution 1:

Instead of float consider inline-block and you will be able to use the with-space trick:

var slider = document.getElementById("slider"),
  cont1 = document.getElementById("container1"),
  cont2 = document.getElementById("container2");

slider.addEventListener("input", function() {
  cont1.style.width = slider.value + "px";
  cont2.style.width = slider.value + "px";
}, false);
#item {
  width: 100px;
  height: 100px;
  display: inline-block;
}

.container {
  height: 100px;
  background-color: #ccc;
  white-space: nowrap;
  font-size: 0; /*to avoid white-space between inline-block*/
}
<p>use slider to change width of the container</p><inputid="slider"type="range"max="500"><p>overflow: hidden</p><divclass="container"id="container1"style="width: 300px; overflow: hidden;"><divid="item"style="background-color: red;"></div><divid="item"style="background-color: green;"></div></div><p>overflow: visible</p><divclass="container"id="container2"style="width: 300px; overflow: visible;"><divid="item"style="background-color: red;"></div><divid="item"style="background-color: green;"></div></div>

Solution 2:

If I understand your intent correctly, you want the grey slider to 'fade into' the green square, leaving the green square where it is.

For this, you'll want to combine overflow: hidden in conjunction with position: absolute:

var slider = document.getElementById("slider");
var cont1 = document.getElementById("container1");

slider.addEventListener("input", function() {
  cont1.style.width = slider.value + "px";
}, false);
#green {
  position: absolute;
  left: calc(100px + 8px); /* Red offset + body margin */
}

.item {
  width: 100px;
  height: 100px;
  float: left;
}

.container {
  height: 100px;
  background-color: #ccc;
}
<p>use slider to change width of the container</p><inputid="slider"type="range"max="500"><divclass="container"id="container1"style="width: 300px; overflow: hidden;"><divclass="item"style="background-color: red;"></div><divid="green"class="item"style="background-color: green;"></div></div>

Note that your provided code also has duplicate #item IDs, which is invalid markup. I've changed these to classes in my above example.

Post a Comment for "Prevent Divs From Wrapping When Parent Is Too Small"