Getting a CSS element to automatically resize to content width, and at the same time be centered
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 #06开发者_StackOverflow社区0;
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.
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');
});
精彩评论