2

I want to put three images at the center of a page. In the following code, when I use float, the image jumps out of the parent div with class "centered". Is there any way that I can keep the child div inside the parent div?

HTML:

<div class="centered">
  <div id="M">
    <img src="images/M.png">
    <img src="images/M.png">
    <img src="images/M.png">
  </div>
</div>

CSS:

.centered {
    margin-left: auto;
    margin-right: auto;
    border: 3px solid #73AD21;
    width: 1500px;
}

.centered img {
    display: block;
}

#M {
    float:left;
}
Rounin
  • 27,134
  • 9
  • 83
  • 108
user2326844
  • 321
  • 2
  • 8
  • 20
  • 2
    Possible duplicate of [Using :after to clear floating elements](http://stackoverflow.com/questions/10699343/using-after-to-clear-floating-elements) – A. Wolff Feb 06 '16 at 13:33
  • 1
    https://jsfiddle.net/4muaq1f7/ – A. Wolff Feb 06 '16 at 13:33
  • I want to put 3 pictures side by side – user2326844 Feb 06 '16 at 13:37
  • I've updated your question because in your original question you said _I want to put **an image** at the center of the page_ and then your code below included a single image. Centering a row of 3 pictures side by side is quite a different question from centering a single image. – Rounin Feb 06 '16 at 14:08
  • @Rounin - yes, thanks for your edit. – user2326844 Feb 06 '16 at 14:11

2 Answers2

3

you have to add sudo element just after your .centered div to clear the float after it.

.centered:after{
   content: "";
   display:table;
   clear:both;
}
Peter Wilson
  • 4,150
  • 3
  • 35
  • 62
1

If you want to center the image, give it a width and a left and right margin of auto:

img {
display: block;
width: 100px;
height: 100px;
margin: 12px auto;
background-color: rgb(255,0,0);
}
<img />

If you want to center the image inside a 1500px wide div.centered with a 3px green border, do the same:

img {
display: block;
width: 100px;
height: 100px;
margin: 12px auto;
background-color: rgb(255,0,0);
}

.centered {
    margin: 0 auto;
    border: 3px solid #73AD21;
    width: 1500px;
}
<div class="centered">
<img />
</div>
Rounin
  • 27,134
  • 9
  • 83
  • 108