Absolute center position
One of very common problems many web developers come across is positioning content in the middle of container. There are different ways of achieving that, but in this post, I will cover how to do it by using absolute position.
For this post I will be using simple HTML structure of just two elements where I will be placing element with ID content in the middle of element with ID container.
<div id=”container”>
<div id=”content”>
Centered content
</div>
</div>
Step 1: Container
When you are positioning something absolute, position will be decided based on first parent element that has relative position. For this I will use element with ID container. I will also define its fixed width, height and background different from content element just so it is easier to see which element is which and their positions.
#container {
background: #eee;
height: 500px;
position: relative;
width: 100%;
}
Step 2: Absolute position
If we want to position content element to absolute center, we need to define its position to center. But there are few more things. We also need to define all positions to 0 and its margin to auto. Again, different background is just there for demo purposes to easier see which element is which.
#content {
background: #aaa;
bottom: 0;
left: 0;
margin: auto;
position: absolute;
right: 0;
top: 0;
}
Step 3: Define width and height
If you run this, you will notice that content element covers container fully. This is because we don’t have defined width and height for content. For this to work you will need to define those two properties. Otherwise, content will just grow to its position on each side, which is 0 in this case.
#content {
background: #aaa;
bottom: 0;
height: 100px;
left: 0;
margin: auto;
position: absolute;
right: 0;
top: 0;
width: 200px;
}
Conclusion
This is just one of several different ways to solve this problem. While it will work everywhere, there are some limitations you should be aware of. One of them is resizing and overflow of parent element that you would need to handle separately. Other one is that you are positioning content element, but content inside of it might not be properly centered. However, once you get to this point, everything else is much easier to solve.
Example code for this can be found in my Github repository.
Top comments (2)
I guess margin:auto; also works if the parent container is relatively positioned.
I use display:flex;
align-item:center;
justify-content:center;
It could and most of browsers do support flex, but absolute position is something that def should work everywhere. Which is why it is more common solution