- A Bootstrap-style announcement/information bar that is fixed to the top, including one text string and one button
- Makes the button in the bar to become a link in mobile view
Table of contents
- 1. Create an announcement bar with Bootstrap alert class (HTML, CSS)
- 2. Make the announcement bar to stick to the head of the web page
- 3. Center the Bootstrap dismiss close button vertically
- 4. Make the button to become a link in mobile view
1. Create an announcement bar with Bootstrap alert class (HTML, CSS)
2. Make the announcement bar to stick to the head of the web page
Method one: using Bootstrap’s “fixed-top” class
To make this sticky position, you can use “fixed-top” class by Bootstrap. However, the alert element will overlap with the content below. To prevent it to overlap with the next element, you can provide a margin.
First, add “fixed-top” class to the alert element:
Then, provide a margin:
I think this is not a good way because the margin is not a dynamic value. If the alert element is higher than the value provided, it will overlap again. But it is a fast method because it make advantages of Bootstrap and would fit nicely if you always know the height of the announcement bar.
Method two: using “position: sticky”
Another way to stick the bar to the head of the page is to use the “position: sticky” and then set the position of the bar in relation with the whole document so that when visitor scroll down the page, the bar will follow.
So let’s add our custom CSS class:
3. Center the Bootstrap dismiss close button vertically
This is quite a small detail. As you might notice, the close (x) element of the alert class is not vertically centered. It only has a padding. This is perfect if you have only 1 line of information to show on the bar. But what if your bar has more text and the height increases? Then the close button is not centered anymore.
To make this vertically center no matter how high the bar is, simply use “transform: translate“.
4. Make the button to become a link in mobile view
This is another small thing that does not need to be done on every project. But I prefer the info bar to look a bit cleaner on mobile devices and so I would like to replace the button with a simple link.
So the way to do it: have in the html both link and button. By default hide the link and display the button. Hide the button and display the link in the mobile view.
I think this is a quite ugly method but it works and does not take much time to implement. With Bootstrap it is very easy to do using .d-none and .d-block.