CSS: Center text/image/div in middle of parent div (container)
It is a common situation, that you want to put some element (like text, image or div) in the center (horizontally and vertically) of parent div (container). Setting some element in the center horizontally is usually quite easy – just put CSS rule “margin: 0 auto” to element or “text-align: center” to its parent element and it is done.
But when we want to put html element in center vertically – then it is not so easy! You can try to use “vertical-align: middle;” but quickly you will discover that it is not so easy to use. It works not as we expect. Check code below, of course, “vertical-align: middle;” is not working as we want.
HTML
1 2 3 |
<div class="parent"> <div class="inner"></div> </div> |
CSS
1 2 3 4 5 6 7 8 9 10 11 12 |
.parent { background: blue; height: 200px; } .inner { width: 100px; height: 100px; background: green; margin: 10px auto; vertical-align: middle; } |
RESULTS
And as you can see, it is not working 😉 “vertical-align: middle;” works in different way than we could think. We need to have 2 or more child elements, then it could be aligned one to another. Analyze example below to check it.
HTML
1 2 3 4 |
<div class="parent"> <div class="inner first"></div> <div class="inner second"></div> </div> |
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
.parent { background: blue; text-align: center; height: 300px; } .inner.first { height: 200px; } .inner { display: inline-block; width: 100px; height: 100px; background: green; vertical-align: middle; } |
RESULTS
So now the question is: How to center vertically one element inside another?
The answer is easy – we must use one trick and combine two rules coming with CSS3.
- We must set height (and optionally width) and “postion: relative;” rule to parent element.
- Set to child element “position: absolute” – with that we can do a magic.
- Now we set child position for top and left to 50%. remember, the base of the co-ordinate system is located in top left corner of parent element.
- And to finish it, we set translation to child element to -50% horizontally and vertically. Using translation remember that the base of the co-ordinate system is located in top left corner of child element.
Check code below 🙂
HTML
1 2 3 |
<div class="parent"> <div class="inner"></div> </div> |
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
.parent { background: blue; height: 300px; position: relative; } .inner { width: 100px; height: 100px; background: green; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } |
RESULTS
And thats it! 🙂
If you have some questions or you know some other method to position child elements vertically in center, just write it in comments below.