Home » Html » Position absolute div in center of screen view

Position absolute div in center of screen view

Posted by: admin November 29, 2017 Leave a comment

Questions:

I want to place div that has absolute position in center of the screen view (scrolled or not scrolled).

I have this but its places div in mid od the document and not mid of current view.

#main {
    width: 140px;
    height:100px;
    border: 1px solid Black;
    text-align: left;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left:-70px;
    margin-top:-50px;   
}
Answers:

Change position:absolute to position: fixed and you should be good to go!

When you say position – absolute, the reference div is the parent div that has a position – relative. However if you say position -fixed, the reference is the browser’s window. which is wat you want in your case.

In the case of IE6 i guess you have to use CSS Expression

Questions:
Answers:

Use the following CSS:

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

Questions:
Answers:

Since CSS’s calc() is supported by all browsers now, here a solution using calc().

#main {
    width: 140px;
    height:100px;
    border: 1px solid Black;
    text-align: left;
    position: absolute;
    top: calc(50vh - (/* height */100px / 2));
    left: calc(50vw - (/* width */140px / 2)); 
}

Questions:
Answers:
margin-left: -half_of_the_div;
left: 50%;
position: fixed;

example on codepen