Kinda Code
Home/HTML & CSS/CSS: How to Center an Element with Fixed Position

CSS: How to Center an Element with Fixed Position

Last updated: June 07, 2022

There might be cases where you want to center an element whose position is fixed (e.g., you need to implement a modal dialog or a floating button, etc).

1. If you need to center the fixed element both horizontally and vertically, set the top, left, and transform properties as follows:

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

2. In case you only need to center the fixed element horizontally, use this:

left: 50%;
transform: translateX(-50%);

3. And here is how to center the fixed element vertically:

top: 50%;
transform: translateY(-50%);

The three examples below will cover all of these use cases.

Example

Screenshot:

The code:

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .wrapper {
            width: 100vw;
            height: 100vh;
            background: rgba(0, 0, 0, 0.6);
        }

        #dialog {
            position: fixed;
            z-index: 100;
            width: 300px;
            height: 200px;
            padding: 20px;
            background: #fff;
            
            /* Center the dialog */
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
    <title>KindaCode.com</title>
</head>

<body>
    <div class="wrapper">
        <div id="dialog">
            <h1>Sample Dialog</h1>
        </div>
    </div>
</body>

</html>

That’s it. Further reading:

You can also check out our CSS category page for the latest tutorials and examples.