How to center div horizontally and vertically using flexbox?

How can I move any div to center vertically and horizontally, using Flexbox? I don't want to use position property or float, I am looking to use flex css properties to center elements vertically and horizontally.

Asked by:- bhanu
: 114 At:- 1/7/2022 4:22:25 PM
CSS flexbox center div

1 Answers
profileImage Answered by:- vikas_jk

To center a div vertically and horizontally using flexbox, you need to wrap the div or div's inside a container with properties 'display: flex; flex-direction: column; justify-content: center;align-items: center;', then just make the div 'text-align: center;' if it has text.

Here is the complete example

<div id="mainContainer"><!-- flex container -->

    <div class="box"><!-- flex item -->
        <p>Some Text</p>


and CSS for it will be as below

#mainContainer {
    display: flex; /* establish flex container */
    flex-direction: column; /* make main-axis vertical */
    justify-content: center; /* align items vertically, in this case */
    align-items: center; /* align items horizontally, in this case */
    height: 300px; 

Output will be like this


Here is the working fiddle


You can also take a look on following links which may be helpful

Responsive center image using pure CSS or Bootstrap 3/4

How to use vertically align : middle text, next to image using CSS?

At:- 1/7/2022 4:39:21 PM
Excellent and easy answer thanks. 0
By : bhanu - at :- 1/19/2022 10:40:23 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use