Fixed Positioning

With fixed positioning, an element's box is anchored against the browser's viewport. This means that, as the user scrolls the content, the fixed content remains in place. Fixed elements usually sit above the normally flowing content, making fixed positioning a good choice for dialog boxes and widgets that should always be visible, like health bars and mini-maps in games.

Consider this page, which is packed full of text:

html
css
preview

If your site collects or tracks the user's data and serves visitors in the European Union, you will need to display a notice describing your practice in order to comply with the General Data Protection Regulation (GDPR). This notice is often presented as a dialog box that sits in front of the content. Suppose you want to add a dialog announcing that you do not collect any data. You start by adding a div:

html
css
preview

This element can be added anywhere in the HTML. When you set its position to fixed, it will be removed from the flowing hierarchical structure and placed on top of the other content:

html
css
preview

Notice how the dialog is placed. None of its edges have been anchored, so its position is derived from the element's static box. Try moving the dialog element around in the HTML. You should see the dialog appear in its static position but on top of the neighboring content. The dialog is effectively removed from the normal flow. The neighboring content fills in where the dialog's static box would normally appear.

Suppose you want the dialog to appear at the bottom of the page. You anchor it using the bottom property:

html
css
preview

Try resizing the page. The dialog stays anchored to the bottom. Do you see how the dialog doesn't fill the page horizontally? To make it do so, you anchor the left and right edges similarly:

html
css
preview

You can anchor as many of the four edges as you wish to achieve your desired layout. Be aware that setting both left and right indirectly sets an element's width. If you also set the width property, then you have overconstrained the box. In such cases, the width property will be honored and one of left or right will be ignored. Try proving this to yourself. A similar story can told for top, bottom, and height.

To add a little gap from the edge of the viewport, you could set these edges to use non-zero offsets. However, adding margin is a little easier:

html
css
preview

The viewer must be able to close the dialog to get at the content. You place an HTML entity for a heavy X in the dialog and color it red:

html
css
preview

To make the close button appear at the right end of the dialog, you can use Flexbox, which gives you control over the spacing between elements:

html
css
preview

Actually closing the dialog is something best left to JavaScript, which you'll get to soon.