Home > Software engineering >  Why doesn't margin-top: auto work inside a nested div?
Why doesn't margin-top: auto work inside a nested div?

Time:03-20

Let's say there is a div of min-height 500px and there is a nested div of min-height 200px. If I put the margin-top for the nested div as 150px, it is vertically centered. So the margin property is working. But if I give the same thing as margin-top or margin as auto, the nested div is not vertically centered, but margin: auto; centers horizontally. Why?

.container {
  min-height: 500px;
  border: 0.3em solid black;
}

.nested-div {
  min-height: 200px;
  width: 200px;
  border: 0.3em solid red;
  margin: auto;
}
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="styles.css" />
  </head>
  <body>
    <div >
      <div >
      </div>
    </div>
  </body>
</html>

CodePudding user response:

It's not working because margin-top:auto and margin-bottom:auto values would compute as zero.

Have you tried using flex to center the div though?

.container {
  min-height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 0.3em solid black;
}

.nested-div {
  min-height: 200px;
  width: 200px;
  border: 0.3em solid red;
}
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="styles.css" />
  </head>
  <body>
    <div >
      <div >
      </div>
    </div>
  </body>
</html>

  • Related