当父级太小时,防止div包装 [英] Prevent divs from wrapping when parent is too small

查看:128
本文介绍了当父级太小时,防止div包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何阻止此父div中的div包装而不是仅仅被切断?

How can I stop the divs inside of this parent div from wrapping instead of just being cut off?

代码:

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>

jsfiddle

正如您所看到的,当我更改父div的大小时,div包含在内。搜索后,我找到了两个解决方案。其中一个需要通过使用绝对定位的div来设置容器的宽度。另一个使用 white-space:none ,但没有运气。

As you can see, as I change the size of the parent div, the divs inside wrap. After searching, I found two solutions. One of them required a set width for the container, by using absolute positioned divs. The other used white-space: none, but no luck.

推荐答案

而不是浮动考虑内联块,你将能够使用 with-space 技巧:

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>

这篇关于当父级太小时,防止div包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆