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;
}
user2326844
  • 321
  • 2
  • 8
  • 20

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
  • 3,938
  • 3
  • 31
  • 55
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>