To achieve the desired outcome, utilizing the CSS property position: fixed
is key. This rule informs the browser that the specified element
will remain fixed in its position even as the page is scrolled.
By combining this with additional CSS rules, such as right
, left
, and margin
, we can center the element horizontally (note that specifying a width
is essential for this to work effectively).
Moreover, by incorporating the top
and transform
rules, the element can be centered vertically.
Here is a demonstration showcasing how these rules can be applied:
#success-alert {
position: fixed;
/** Ensures element stays fixed in place even during page scrolling */
width: 50%;
/** Specifies a width to prevent the element from occupying the entire viewport (alternatively, apply "col-*" classes for responsiveness) */
right: 0;
left: 0;
margin: auto;
/**
* The aforementioned rules horizontally center the element.
* Both "right" and "left" values must be "0" for proper centering through the "margin" rule;
*/
top: 50%;
transform: translate3d(0, -50%, 0);
/** The above rules centrally position the element vertically */
text-align: center;
z-index: 9999;
}
/** Visual representation for the demo */
body {
height: 300vh; /** Simulates a lengthy page */
background-image: linear-gradient(to bottom, red, blue)!important;
}
/** "!important" is used to override SO's background rule on the body element within snippets */
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ae8e5e5fef9fef8ebfacabfa4baa4b8">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- Demo purposes only -->
<h5 class="text-center text-white">Try scrolling to observe the alert remaining fixed in position</h3>
<div id="success-alert" class="alert alert-success alert-autohide shadow" 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>
While the above solution is not the sole method to tackle this specific issue, it serves as a solid starting point to guide you in the right direction.
For further insights, explore the position
rule on MDN.
Enhance your understanding of the transform
rule through MDN.