Getting a CSS element to automatically resize to content width, and at the same time be centered

主宰稳场 提交于 2019-12-03 02:04:56

Have you tried keeping it inline-block, and putting it inside a block-level element that’s set to text-align: center?

E.g.

HTML

<div id="boxContainerContainer">
    <div id="boxContainer">
        <div id="box1"></div>
        <div id="box2"></div>
        <div id="box3"></div>
    </div>
</div>

CSS

#boxContainerContainer {
    background: #fdd;
    text-align: center;
}

#boxContainer {
    display:inline-block;
    border:thick dotted #060;
    margin: 0px auto 10px auto;
    text-align: left;
}

#box1,
#box2,
#box3 {
    width: 50px;
    height: 50px;
    background: #999;
    display: inline-block;
}

Seems to work as you describe: http://jsfiddle.net/pauldwaite/pYaKB/

Unfortunately, this cannot be achieved through CSS solely I don't think. You could always use JavaScript to center the div once you know its width (i.e. after the boxes have been appended) for example:

$(document).ready(function() {
    var itemWidth = $('#boxContainer').width();
    var availWidth = $(screen).width();
    var difference = availWidth - itemWidth;
    $('#boxContainer').css('margin: 0 ' + Math.round(difference / 2) + 'px');
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!