CSS - How to make a DIV (or an element) float to Center

← PrevNext →

Let us assume, you want to design a little popup window, which will sit exactly at the center of the screen (from top and left) and should float (as fixed). I’ll show how you can do this using a DIV element and CSS.

Float and Center DIV

<!DOCTYPE html>
<html>
<head>
  <title>Floating and centered DIV using CSS</title>
  
  <style>
    #container {
/*    center and float the element */
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: rgba(255, 255, 255, 0.75);
  
/*   design the element */
      width: 500px;
      height: 200px;
      padding: 20px;
      text-align: center;
      -webkit-border-radius: 10px;
      box-shadow: 0 4px 23px 5px rgba(0, 0, 0, 0.2), 0 2px 6px rgba(0, 0, 0, 0.15);
      display: block;
    }
  </style>    
</head>
<body>
  <div id="container">
    Floating and Centered DIV
  </div>
</body>
</html>
See this demo

Note: It is responsive. So it will work on any device like a mobile or a tab.

In order to make the element float, I am using the fixed property.

See the CSS: position: fixed;

It remains fixed at a particular point on the screen. You can use absolute position if you don’t to fix it at one place. Now, we have to center the element, exactly at the center of the screen.

To center the element, I have set the top and left properties to 50%.

top: 50%;
left: 50%;

However, this is not enough to center the DIV element exactly at the center, since the DIV has some specific size like the width, height or margin, padding etc.

Therefore, I am using the translate value of the transform property to adjust the centering of the DIV element.

transform: translate(-50%, -50%);

With transform property defined, you can now change the size of the element as you want and see the result. Or, remove width and height of the element and simply add some padding, and see what happens.

padding: 200px;

The element floats at the center. In-fact, now you can show anything at the center of the screen. Thanks.

← PreviousNext →