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

人盡茶涼 提交于 2019-12-03 11:42:23

问题


I have a CSS element, with a border around it, that could have one or multiple boxes in it, so the width of the entire div changes depending on how many boxes are present inside of it. However, I want this whole div to be centered on the screen.

Usually, to center things, I just use:

margin-left: auto;
margin-right: auto;

But, this time, I have to either float the element or make it inline-block so the size of the div will be resized to the content, and if I do that, the margin-left and margin-right auto does not work, it always just stays on the left side of the screen.

Currently I have:

#boxContainer {
    display:inline-block;
    clear:both;
    border:thick dotted #060;
    margin: 0px auto 10px auto;
}

I also tried with float: left instead of display: inline-block.

Does anyone know of a good way to both center a div and allow it to be resized to content simultaneously? Any help would be greatly appreciated.


回答1:


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/




回答2:


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


来源:https://stackoverflow.com/questions/5343778/getting-a-css-element-to-automatically-resize-to-content-width-and-at-the-same

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!