Home > Net >  How to make an alert banner have height and float?
How to make an alert banner have height and float?

Time:06-25

We have an position: fixed; alert banner which appears at the top of the page to display different alerts. We want it to have a height (or appear to have height) so that it doesn't cover up the top menu of the page, but rather pushes the page content down. When the user accepts or x's out of the banner, the page should pop back to the top. When the user scrolls down the page, the banner should float at the top of the window, remaining on screen the whole time.

The current strategy is very kluge and uses a setBannerHeight() function all over the place that gives a above our banner a set height, pushing the main page content down and allowing the banner to appear to 'take up space'.

It's proven to be non future proof and does things like prevents our iOS Smart App Banners (a totally different banner) from appearing properly.

Is there a way I can either give a fixed element a height, make a sticky element float (so far I can't, this is in a self contained alert.component.ts component so don't think I can give a parent element height), OR, perhaps a 3rd party alert library you'd recommend that already has this solved?

CodePudding user response:

One way to do it is by toggling a CSS class to the <body> that matches the state of the alert (open or closed). This class affects the behavior of the body, specifically his top-padding which should equal the height of alert.

Now all you have to worry about is to toggle the class on the proper show/hide events of the alert component.

body.alert-on {
    padding-top: 60px;
}
.alert {
    position: fixed;
}

CodePudding user response:

This may help. It's simple, using position: sticky in CSS and some vanilla JavaScript. The alert stays at the top of the page when a user scrolls. It disappears when a user clicks on it.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div id="container">

        <div id="alert">Alert</div>

        <nav>Menu</nav>

        <section>
            <p>Add enough content here so you can scroll the page.</p>
        </section>
    </div>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>
#container {
    width: 600px;
    margin:  0 auto;
}

nav {
    width: 600px;
    height: 100px;
    background: lightblue;
}

#alert {
    width: 600px;
    height: 40px;
    position: sticky;
    top: 0;
    background: orangered;
    cursor: pointer;
}

section {
    width: 600px;
}
const alert = document.getElementById("alert");

alert.addEventListener("click", function() {
    alert.style.position = "static";
    alert.style.display = "none";
})
  • Related