I have an inline-block container, with several other inline-block elements like so:
![As working](https://i.stack.imgur.com/wkWsD.png)
The container is the blue background, the red the elements. Everything is working fine until there's too many elements and the inline-block has to expand:
![As not working](https://i.stack.imgur.com/uuxIG.png)
The inline-block container expands to the entire width of the body, but I want it to shrink to the width of it's contents. Is this possible with pure CSS? Kinda like this:
![As I want it to work](https://i.stack.imgur.com/NwIKD.png)
JSFiddle http://jsfiddle.net/eRHnp/
#container {
background: blue;
display: inline-block;
}
.box {
background: red;
display: inline-block;
width: 100px;
height: 100px;
}
哦,容器不能是固定宽度:(
我相信你正在寻找的东西像这样 http://jsfiddle.net/Zeaklous/yXxD6/48/,仅当另一个盒子可以容纳/不容纳(具体取决于窗口大小)时,才会调整容器的大小。据我所知,这个功能目前在纯 CSS 中是不可能的,因为 CSS 无法根据动态内容分段缩小(框的整个宽度)
The CSS
#container {
background:blue;
text-align: left;
font-size:0;
display: inline-block;
padding-left:5px;
padding-bottom:5px;
/* for ie6/7: */
*display: inline;
zoom:1;
}
.box {
display:inline-block;
background:red;
height:50px;
margin-top:5px;
margin-right:5px;
width: 100px;
height: 100px;
}
和纯javascript
var boxAmount = 0;
var newWidth = 0;
setNewWidth();
window.onresize = function () {
setNewWidth();
};
function setNewWidth() {
var outerContainer = document.getElementsByTagName('body')[0];
var outerWidth = outerContainer.offsetWidth;
var box = document.getElementsByClassName('box');
var boxWidth = box[0].offsetWidth;
var innerContainer = document.getElementById('container');
var containerPadding = parseInt(window.getComputedStyle(innerContainer, null).getPropertyValue('padding-left'), 10)
+ parseInt(window.getComputedStyle(innerContainer, null).getPropertyValue('padding-right'), 10);
boxAmount = (outerWidth - containerPadding) / (boxWidth + containerPadding);
boxAmount = Math.floor(boxAmount);
if (boxAmount <= box.length) {
newWidth = boxAmount * boxWidth + boxAmount * 5;
}
innerContainer.style.width = newWidth + 'px';
}
如果盒子周围有另一个容器,这是一个版本 http://jsfiddle.net/Zeaklous/yXxD6/50/
这是一个 jQuery 版本 http://jsfiddle.net/Zeaklous/yXxD6/49/对于那些有兴趣的人
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)