Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align absolutely positioned element to center?

If you set both left and right to zero, and left and right margins to auto you can center an absolutely positioned element.

position:absolute;
left:0;
right:0;
margin-left:auto;
margin-right:auto;

If you want to center align an element without knowing it's width and height do:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Example:

*{
  margin:0;
  padding:0;
}
section{
  background:red;
  height: 100vh;
  width: 100vw;
}
div{  
  width: 80vw;
  height: 80vh;
  background: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<section>
  <div>
    <h1>Popup</h1>
  </div>
</section>

try this method, working fine for me

position: absolute;
left: 50%;
transform: translateX(-50%); 

Have you tried using?:

left:50%;
top:50%;
margin-left:-[half the width] /* As pointed out on the comments by Chetan Sastry */

Not sure if it'll work, but it's worth a try...

Minor edit: Added the margin-left part, as pointed out on the comments by Chetan...


position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;

All you have to do is make sure your parent <div> has position:relative, and set a height and width for the element you want centered. Use the following CSS:

.layer {
    width: 600px; height: 500px;
    display: block;
    position:absolute;
    top:0;
    left: 0;
    right:0;
    bottom: 0;
    margin:auto;
}

https://output.jsbin.com/aXEZUgEJ/1/