Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - 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:

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;  
  float: left;
}

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

<p>overflow: visible</p>
<div class="container" id="container2" style="width: 300px; overflow: visible;">
  <div id="item" style="background-color: red;"></div>
  <div id="item" style="background-color: green;"></div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>
<input id="slider" type="range" max="500">
<p>overflow: hidden</p>
<div class="container" id="container1" style="width: 300px; overflow: hidden;">
  <div id="item" style="background-color: red;"></div>
  <div id="item" style="background-color: green;"></div>
</div>

<p>overflow: visible</p>
<div class="container" id="container2" style="width: 300px; overflow: visible;">
  <div id="item" style="background-color: red;"></div>
  <div id="item" style="background-color: green;"></div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...