0

Hey so I have this div and inside the div I have a button. I wanted to center the div horizontally and vertically. Also I wanted to center the button horizontally and vertically inside the div. Here is my code.

<div style='position: relative; left: calc(50% - 250px); top: calc(50% - 100px); border: 1px solid black; width: 500px; height: 200px;'>
  <button style='position: absolute; width: 100px; height: 30px; left: calc(50% - 50px); top: calc(50% - 15px);'>
    Submit
  </button>
</div>

The button positioning works fine inside the div. However I am curious why the div will center horizontally but not vertically? I am assuming it has something to do with the position: relative? But I am not sure.

Thanks for your help!

Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
j.doe
  • 23
  • 8

1 Answers1

1

Because the DIV doesn't have a reference for its relative height (percentage) - the parent element - in this case body - doesn't have a set height. Add this rule and it will center as desired:

html,
body {
  height: 100%;
  margin: 0;
}

html,
body {
  height: 100%;
  margin: 0;
}
<div style='position: relative; left: calc(50% - 250px); top: calc(50% - 100px); border: 1px solid black; width: 500px; height: 200px;'>
  <button style='position: absolute; width: 100px; height: 30px; left: calc(50% - 50px); top: calc(50% - 15px);'>Submit</button>
</div>
Johannes
  • 64,305
  • 18
  • 73
  • 130
  • I tend to prefer to use `100vh` these days, as opposed to percentages for heights.... percentages tend to break down when used within nested elements (clearly not the case here, but in other more complex cases) – random_user_name Oct 09 '18 at 19:23