Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't margin-top: auto work inside a nested div?

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 class="container">
      <div class="nested-div">
      </div>
    </div>
  </body>
</html>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 class="container">
      <div class="nested-div">
      </div>
    </div>
  </body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading