我有一个内联块容器,还有其他几个内联块元素,如下所示:
容器是蓝色背景,红色是元素。一切都工作正常,直到有太多的元素和内联块必须扩展:
内联块容器扩展到主体的整个宽度,但我希望它缩小到它的内容宽度。纯CSS可以实现吗?有点像:
#container {
background: blue;
display: inline-block;
}
.box {
background: red;
display: inline-block;
width: 100px;
height: 100px;
}
哦,容器不能是固定的宽度:(
答案 0 :(得分:3)
我相信你要找的东西是like this,只有当另一个盒子适合/不适合时才会调整容器大小,具体取决于窗口大小。据我所知,此功能目前在纯CSS中是不可能的,因为CSS无法根据动态内容缩小细分(框的整个宽度)
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';
}
Here is a version if there is another container around the boxes