-1

I am trying to center a DIV vertically and horizontally in a page:

* {
  box-sizing: border-box;
}

div.wrapper {    
  border: 1px solid red;
  position: relative;
}

div.window {
  border: 1px solid blue;
  max-width: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="wrapper">
  <div class="window">
    Sed blandit augue quis diam tristique fringilla. Morbi tortor leo, efficitur sit amet ultrices non, lacinia ut nunc. Donec ut odio a diam semper consequat quis in leo. 
  </div>
</div>

Somehow this is not vertically centered. What am I doing wrong?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

2 Answers2

2

This is because of the position: relative in wrapper div. Without it, it works correctly.

div.wrapper {
  border: 1px solid red;
}

div.window {
  border: 1px solid blue;
  max-width: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="wrapper">
  <div class="window">
    Sed blandit augue quis diam tristique fringilla. Morbi tortor leo, efficitur sit amet ultrices non, lacinia ut nunc. Donec ut odio a diam semper consequat quis in leo.
  </div>
</div>
MaxiGui
  • 6,190
  • 4
  • 16
  • 33
theWellHopeErr
  • 1,856
  • 7
  • 22
  • the wrapper should be surrounding the window, or else the red border won't render properly, this can't be the actual answer as wrapper needs a min height. If specified it would look proper. – Prathamesh Koshti Nov 27 '20 at 13:01
1

If you just want to center it, i will recommend using display: flex; instead of absolute positioning.

Something like:

* {
  box-sizing: border-box;
}

div.wrapper {
  min-height: 100vh;
  border: 1px solid red;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

div.window {
  border: 1px solid blue;
  max-width: 300px;
}
<div class="wrapper">
  <div class="window">
    Sed blandit augue quis diam tristique fringilla. Morbi tortor leo, efficitur sit amet ultrices non, lacinia ut nunc. Donec ut odio a diam semper consequat quis in leo.
  </div>
</div>

Example codepen here: https://codepen.io/bj-rn-nyborg/pen/OJRJawN

theWellHopeErr
  • 1,856
  • 7
  • 22
Bjørn Nyborg
  • 993
  • 7
  • 17