Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.
Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
With flexbox it is very easy to style the div horizontally and vertically centered. To align the div vertically centered, use the property align-items: center . For the vertical centering I usually use "line-height" (line-height == height).
Every solution posted here assumes that you know the dimensions of your img
, which is not a common scenario. Also, planting the dimensions into the solution is painful.
Simply set:
/* for the img inside your div */
display: block;
margin-left: auto;
margin-right: auto;
or
/* for the img inside your div */
display: block;
margin: 0 auto;
That's all.
Note, that you'll also have to set an initial min-width
for your outer div
.
text-align: center will only work for horizontal centering. For it to be in the complete center, vertical and horizontal you can do the following :
div
{
position: relative;
}
div img
{
position: absolute;
top: 50%;
left: 50%;
margin-left: [-50% of your image's width];
margin-top: [-50% of your image's height];
}
A very simple and elegant solution to this is provided by W3C. Simply use the margin:0 auto declaration as follows:
.top_image img { margin:0 auto; }
More information and examples from W3C.
<div class="outer">
<div class="inner">
<img src="http://1.bp.blogspot.com/_74so2YIdYpM/TEd09Hqrm6I/AAAAAAAAApY/rwGCm5_Tawg/s320/tall+copy.jpg" alt="tall image" />
</div>
</div>
<hr />
<div class="outer">
<div class="inner">
<img src="http://www.5150studios.com.au/wp-content/uploads/2012/04/wide.jpg" alt="wide image" />
</div>
</div>
CSS
img
{
max-width: 100%;
max-height: 100%;
display: block;
margin: auto auto;
}
.outer
{
border: 1px solid #888;
width: 100px;
height: 100px;
}
.inner
{
display:table-cell;
height: 100px;
width: 100px;
vertical-align: middle;
}
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