R. Catalin R. Catalin - 8 days ago 5
CSS Question

It is not correctly centered vertically

I want to center the paragraph in div "box", but vertical is not correctly centered.



.container {
position: relative;
}
p {
position: absolute;
left: 0;
top: 50%;
width: 100%;
text-align: center;
}
.box {
width: 100%;
height: 120px;
background-color: #62a6c9;
}

<div class="container">
<div class="box"></div>
<p>center</p>
</div>




Answer

You should change your approach, the element .box used as a push-down margin is totally unnecessary, the paragraph p that is the element we want to keep in the middle of the .container should have a reset on its margins and the .container should have a fixed height.

Finally, use flex-boxes:

.container {
  height: 200px;
  background: orange;
  
  display: flex;
  align-items: center;
  justify-content: center;
}

.container p {
  margin: 0;
  background: cyan;
}
<div class="container">
  <p>Hello World</p>
</div>