Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position div to center of visible area

I'm in the midst of making a lightbox style pop-up for a mailing list sign up, but I want the pop-up to position to the center of the visible page, not just the center of the whole document; if the user scrolls to the bottom of the page and clicks to sign up, I want it to appear in the center of the screen.

I'm assuming jQuery/JS will be the best way to go for this; here's my current CSS code which works fairly well but the div needs to be pushed down into the visible space dynamically for smaller screens.

.my-div{     width:960px;     height:540px;     position:absolute;     top:50%;     left:50%;     margin-left:-480px;     margin-top:-270px;     z-index:60;     display:none; } 
like image 537
mmmoustache Avatar asked Jan 30 '12 10:01

mmmoustache


People also ask

How do you place a div in the center of the screen?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do you center an element by position?

To center an element both vertically and horizontally: position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; But if you would like to understand how I came to these solutions, read further for more explanation.

How do you put elements in the middle in HTML?

To just center the text inside an element, use text-align: center; This text is centered.


1 Answers

You were close! It can be done with CSS alone:

Use position: fixed instead of position: absolute.

Fixed refers to the viewport, while absolute refers to the document. Read all about it!

like image 93
Madara's Ghost Avatar answered Sep 21 '22 15:09

Madara's Ghost