0

I think I've got some confusion on how margin auto works. In this case, I'm creating a parent div and a children div inside of it, and both div boxes are given width & height. Then, I tried to use margin auto to make the inner div horizontally & vertically aligned.

<div id="parent">
    <div id="child"></div>
</div>
#parent {
  width: 200px;
  height: 200px;
  background: red;
}

#child {
  width: 50%;
  height: 50%;
  background: blue;
  margin: auto;
}

Result: enter image description here

Somehow the result was out of my expectation. Anyone knows why?

jialeee17
  • 601
  • 2
  • 7
  • 12

1 Answers1

0

Just use display: flex

#parent {
  width: 200px;
  height: 200px;
  background: red;
  display: flex;
  justify-content: center;
  align-items: center;
}

#child {
  width: 50%;
  height: 50%;
  background: blue;
}
<div id="parent">
    <div id="child"></div>
</div>
Oleg Barabanov
  • 2,468
  • 2
  • 8
  • 17