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; }
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.
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.
To just center the text inside an element, use text-align: center; This text is centered.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With