The problem of centering divs or text is quite common and I often had to spend more time fixing it than I would like. Sometimes the situation is simple and using one of the basic methods, like margin: 0 auto solves the case, and sometimes you have to think a little more. Therefore, below are some useful methods that you can use depending on your needs.
Centering div
1. margin: 0 auto;
We can use this option if the element you want to center is a block element and has defined width. In this way, we center the div or paragraph vertically.
Let’s create two divs, one is larger and contains the second, smaller. We center both vertically using margin: 0 auto;
Za pomocą flexboxa możemy wycentować jednego lub kilka div-ów zarówno w poziomie jak i w pionie. Wystarczy, że element – rodzic posiadać będzie właściwość display: flex i że ustawimy na min odpowiednie zachowanie elementów – dzieci.
Using a flexbox, we can center one or several divs both – horizontally and vertically. It’s enough that the parent element has the display property set to: flex and that we set the appropriate behavior of children elements.
In this case we have child that has absolute positioning, margins setted to auto and from each side we set 0 pixels, so child is centered in parent element.
This technique allows you to add content to an HTML element and center it both horizontally and vertically, without worrying about height or width.
You just need to set display: table in the parent element and display: table-cell in the child element, and then set the vertical and horizontal alignment of the text:
I write code that (usually) works. I tame WordPress, learn React, explore the world of DevOps, and click around in the Linux console. I optimize code as a hobby, because laziness is the purest form of productivity. I do my best not to lose my mind somewhere between a bug and a deadline.