Burger mobile menu

CSS: Center text/image/div in middle of parent div (container)

Piotr Elmanowski | Published: 22 Aug, 2018

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

CSS

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

CSS

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.

  1. We must set height (and optionally width) and “postion: relative;” rule to parent element.
  2. Set to child element “position: absolute” – with that we can do a magic.
  3. 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.
  4. 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

CSS

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.

Tags: , ,


Scroll top
Loading
Zdjęcie w lewo Zdjęcie w prawo