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.
Use a container element and set a specific max-width . A common width many websites use is 960px. To actually center the page, add margin: auto .
Just replace #sticky_div's_name_here with the name of your div, i.e. if your div was <div id="example"> you would put #example { position: sticky; top: 0; } .
Change the position
attribute to fixed
instead of absolute
.
Change position:absolute;
to position:fixed;
Quote: I would like to know how to display the div in the middle of the screen, whether user has scrolled up/down.
Change
position: absolute;
To
position: fixed;
W3C specifications for position: absolute
and for position: fixed
.
I just found a new trick to center a box in the middle of the screen even if you don't have fixed dimensions. Let's say you would like a box 60% width / 60% height. The way to make it centered is by creating 2 boxes: a "container" box that position left: 50% top :50%, and a "text" box inside with reverse position left: -50%; top :-50%;
It works and it's cross browser compatible.
Check out the code below, you probably get a better explanation:
jQuery('.close a, .bg', '#message').on('click', function() {
jQuery('#message').fadeOut();
return false;
});
html, body {
min-height: 100%;
}
#message {
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
}
#message .container {
height: 60%;
left: 50%;
position: absolute;
top: 50%;
z-index: 10;
width: 60%;
}
#message .container .text {
background: #fff;
height: 100%;
left: -50%;
position: absolute;
top: -50%;
width: 100%;
}
#message .bg {
background: rgba(0, 0, 0, 0.5);
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
z-index: 9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="message">
<div class="container">
<div class="text">
<h2>Warning</h2>
<p>The message</p>
<p class="close"><a href="#">Close Window</a></p>
</div>
</div>
<div class="bg"></div>
</div>
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