DEV Community

Cover image for CSS: Fix a div center on the page
GreggHume
GreggHume

Posted on • Updated on

CSS: Fix a div center on the page

Sometimes you need to fix an element that you want to stay within the bounds of a container. Or you want to center the fixed element.

The best way to do this is have the fixed div that does the floating and then have a normal div inside that does the centering.

The magic touch is the pointer-events which makes sure the overlaying fixed div does not cover clickable content and get in the way of the cursor.

<div class="fixed">
  <div class="container">
   <div class="toast">A notification that shows up</div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode
.fixed {
 position: fixed;
 top: 32px;
 left: 0;
 right: 0;
 pointer-events: none; // so this div does block clicks on content underneath it
}

.container {
 max-width: 1200px;
 width: 100%;
 margin: 0 auto;
}

.toast {
 pointer-events: all; // so you can click on the toast to close it
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
codedbychavez profile image
Chavez Harris

Nice read! Thanks Gregg!