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:
- CSS: Styling Scrollbar Example
- CSS: Adjust the Gap between Text and Underline
- CSS Flexbox: Make an Element Fill the Remaining Space
- CSS: Make a search field with a magnifying glass icon inside
- Tailwind CSS: How to Create Parallax Scrolling Effect
- Tailwind CSS: Creating Shimmer Loading Placeholder (Skeleton)
You can also check out our CSS category page for the latest tutorials and examples.