0

How do I center a div inside another div? What about an image? I want it centered vertically and horizontally. I want to be modern and use flex - I don't care about old IE support.

.outside {
  background: orange;
  width: 400px;
  height: 300px;
}

.inside {
  width: 80%;
  background: yellow;
}
<div class='outside'>
  <div class='inside'>
    This is the inside div that I would like to center in the outer one
  </div>
</div>

---------------------------------------------------------------------------

<div class='outside'>
  <img src="http://placehold.it/350x150">
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
blackandorangecat
  • 1,246
  • 5
  • 18
  • 37

1 Answers1

1

Vertically centering in CSS is always trickier than it should be. Here is a simple solution that uses Flex. Flex does not work in all browsers!

A width is required in order to center horizontally.

I know there are lots of similar questions, but I believe this method is quick and simple.

.outside {
  background: orange;
  width: 400px;
  height: 300px;
  
  /* This is the magic*/
  display: flex;
  justify-content: center; /* This centers horizontally */
  align-items: center; /* This centers vertically */
}

.inside {
  width: 80%; /* Without a width, horizontally aligning "doesn't work"*/ 
  background: yellow;
}
<div class='outside'>
  <div class='inside'>
    This is the inside div that I would like to center in the outer one
  </div>
</div>

---------------------------------------------------------------------------

<div class='outside'>
  <img src="http://placehold.it/350x150">
</div>
blackandorangecat
  • 1,246
  • 5
  • 18
  • 37