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.
Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.
One way you can achieve this is setting display: inline-block; on the div . It is by default a block element, which will always fill the width it can fill (unless specifying width of course).
For proportional resizing purposes, it makes matters extremely simple: Define the width of an element as a percentage (eg: 100%) of the parent's width, then define the element's padding-top (or -bottom) as a percentage so that the height is the aspect ratio you need. And that's it!
Width: autoThe initial width of block-level elements like <div> or <p> is auto , which makes them take the full horizontal space of their containing block. When an element has auto as a value for width, it can have margin, padding, and border without becoming bigger than its parent element.
Have you tried keeping it inline-block, and putting it inside a block-level element that’s set to text-align: center
?
E.g.
<div id="boxContainerContainer">
<div id="boxContainer">
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
</div>
</div>
#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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With