How to Center an Element with a Fixed Position
Sometimes, you may have difficulties trying to center an element which has a position set to "fixed". If you have faced it, read and find the answer.
Let’s start and find the solution!
First, we’ll show an example where we know the size of an element.
Create HTML
- Use a <div> element with a class name “container”.
<div class="container">
Example of centering an element with a fixed position
</div>
Add CSS
- Set the top and left properties to 50% to center the left-top corner of the <div>.
- Set the margin-top and margin-left properties to the negative half of the height and width of the <div>.
.container {
position: fixed;
width: 500px;
height: 200px;
padding: 10px;
border: 3px solid #147d43;
background-color: #d4fce6;
top: 50%;
left: 50%;
margin-top: -100px; /* Negative half of height. */
margin-left: -250px; /* Negative half of width. */
}
Here is the result of our code.
Example of centering an element with a fixed position:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.container {
position: fixed;
width: 500px;
height: 200px;
padding: 10px;
border: 3px solid #147d43;
background-color: #d4fce6;
top: 50%;
left: 50%;
margin-top: -100px;/* Negative half of height. */
margin-left: -250px;/* Negative half of width. */
}
</style>
</head>
<body>
<div class="container">
Example of centering an element with a fixed position.
</div>
</body>
</html>
If you don’t know the size of the element, you can use the transform property set to "translate".
Example of centering an element with a fixed position with the transform property:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.container {
position: fixed;
width: 500px;
height: 200px;
padding: 10px;
border: 3px solid #147d43;
background-color: #d4fce6;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="container">
Example of centering an element with a fixed position
</div>
</body>
</html>