1

I have the following code:

img {
  display: block;
  margin: 0 auto;
}
 <h2>Center an Image</h2>
<p>To center an image, use margin: auto; and make it into a block element:</p>

<img src="paris.jpg" alt="Paris" style="width:40%">
<img src="paris.jpg" alt="Paris" style="width:40%">
<img src="paris.jpg" alt="Paris" style="width:40%">

But I have this problem -

If i do as you see in the code: I am loosing the center effect and the all images are going left.

The only possibility I know - is to do display the images as "block" instead of "inline-block" - but that is make them one above the other and I want them to be close to each one.

Pete
  • 57,112
  • 28
  • 117
  • 166
wef erv
  • 13
  • 3

2 Answers2

2

You can center images by wrapping them in another div and giving this wrapper text-align:center (if you want them as inline-block elements):

img {display:inline-block;}
.wrapper {text-align:center;}
<div class="wrapper">
  <img src="http://placehold.it/350x150" alt="Paris" style="width:40%">
  <img src="http://placehold.it/350x150" alt="Paris" style="width:40%">
  <img src="http://placehold.it/350x150" alt="Paris" style="width:40%">
</div>
Pete
  • 57,112
  • 28
  • 117
  • 166
  • 1
    +1, Just here to mention that this will result in a space between the elements which you can read about [here](http://stackoverflow.com/questions/16678929/display-inline-block-what-is-that-space) – mhyassin Sep 06 '16 at 13:41
  • Its working! thanks. ill mark your messege. interesting - i didnt know it. i thought that "text-align" is just for text... is there some explanation? – wef erv Sep 06 '16 at 13:42
  • 1
    @weferv text-align is for any inline displayed element even "inline-block" ;) – mhyassin Sep 06 '16 at 13:42
  • @weferv, inline elements are treat like text - that's also why you get the spaces in between them as mhyassin points out (like words in a sentence) – Pete Sep 06 '16 at 13:44
0

You should use a DIV container around the image tags and give it a width and margin:0 auto instead of the images. put those on display: inline-block.

From a JSFIDDLE

.wrapper {
  border: 1px solid grey;
  width: 80%;
  margin: 0 auto;
  text-align: center;
}
img {
  display: inline-block;
}
<div class=wrapper>
  <img src="https://static.pexels.com/photos/3247/nature-forest-industry-rails.jpg" alt="Paris" style="width:20%">
  <img src="http://www.planwallpaper.com/static/images/4-Nature-Wallpapers-2014-1_ukaavUI.jpg" alt="Paris" style="width:20%">
  <img src="http://1.bp.blogspot.com/-FlpE6jqIzQg/UmAq6fFgejI/AAAAAAAADko/ulj3pT0dIlg/s1600/best-nature-desktop-hd-wallpaper.jpg" alt="Paris" style="width:20%">
</div>
chirag
  • 1,761
  • 1
  • 17
  • 33