I am using the following alert:
<div id="success-alert" style="display: none; color: darkgreen; text-align: center; top: 50%; z-index: 9999" role="alert">
Some Message
</div>
When this is displayed, the alert initially shows in the center of the screen. However after scrolling it does not and stays out of view in the original place.
I am wondering how to ensure this is shown in the middle of the screen even after scrolling.
Thanks
CodePudding user response:
Using position: fixed
should achieve your goal. The later rule tells the browser that the element
will always stay fixed in its place even when the page scrolls.
When combined with some other rules, we can have the wanted result, basically we will center the element horizontally using right
, left
and margin
rules (a width
is required for this to work properly).
Also, with the help of top
and transform
rules we can center the elemnt vertically.
Here's a demo that illustrates how things would work:
#success-alert {
position: fixed;
/** will always stay in place even when the page scrolls */
width: 50%;
/** give it a width so the element doesn't take 100% of the viewport (you may alternatively "col-*" classes to it to maintain responsiveness) */
right: 0;
left: 0;
margin: auto;
/**
* the above 3 rules center the element horizontally.
* the "right" and "left" rules must have a value of "0" or else the element cannot be centered using the "margin" rule;
*/
top: 50%;
transform: translate3d(0, -50%, 0);
/** the above 2 rules center the elemnt vertically */
text-align: center;
z-index: 9999;
}
/** just to visually showcase the demo */
body {
height: 300vh; /** to simulate a long page */
background-image: linear-gradient(to bottom, red, blue)!important;
}
/** "!important" is not required but since SO applies a background rule to the body elemnt on snippets we must override it */
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- just for the demo -->
<h5 >Try to scroll you'll notice that the alert stays in place all the time</h3>
<div id="success-alert" role="alert">
Lorem ipsum Lorem ipsum sit oolor amet sit oolor amet. Lorem ipsum sit ool Lorem ipsum sit oolor amet rem ipsum sit oolor amet.
</div>
The above solution is definitely not the only solution for that specific problem but its a good start to keep you on track.
Learn more about the
position
rule on MDN.
Learn more about the
transform
rule on MDN.