How to center an image horizontally in CSS
It’s possible to center some text in the paragraph by using text-align
CSS property. Also, you aren’t limited only by the paragraph, it’s possible to center the text inside any other container, for example, inside div
, h1
, blockquote
etc. Just set text-align
property to center
and you’ll get the text centered.
Fortunately, you can use such approach for images to align them by center, also! Just set text-align
with a center
value for the image’s parent element and you’ll get it centered horizontally.
1 2 3 |
<div class="image-container"> <img src="image.png"> </div> |
1 2 3 4 5 6 7 |
.image-container { text-align: center; } .image-container img { display: inline-block; } |
Notice that you cannot align an image by center if you’re using float
property with left
or right
values for the image. Also, text-align
property doesn’t take an affect if the image has display
other then inline
or inline-block
which is a default display
for images in the most of browsers.
Check out this Pen!
Try it here http://codepen.io/starikovs/pen/iqxms.
By the way, to center an image vertically you can use the described in the article vertical align block element inside block element.