简体   繁体   中英

Make inline-block shrink to contents on overflow

I have an inline-block container, with several other inline-block elements like so: 正在工作

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: 由于不工作

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: 如我所愿

JSFiddle

        #container {
            background: blue;
            display: inline-block;
        }

        .box {
            background: red;
            display: inline-block;
            width: 100px;
            height: 100px;
        }

Oh, and the container can't be a fixed width :(

I believe what you are looking for is something like this , which resizes the container only if another box can fit/not fit depending on the window size. This functionality is not currently possible in pure CSS as far as I know because CSS can't scale down in segments (the full width of the box) based on dynamic content

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;
}

and the pure 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

Here is a jQuery version for those who are interested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM