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.
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>
</div>
</div>
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
https://jsfiddle.net/c4td0hqx/
Thanks
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?
We can use flexbox to center div vertically and horizontally considering the below details:
justify-content: center; align-items: center;
' to center flex div's
flex-direction: column
to place them in center
lex-direction: row
to place them in center
So, here is the demo when items are vertically stacked
#container {
display: flex; /* establish flex container */
flex-direction: column; /* make main axis vertical */
justify-content: center; /* center items vertically, in this case */
align-items: center; /* center items horizontally, in this case */
height: 200px;
}
.divs {
width: 200px;
margin: 5px;
color:white;
text-align: center; /* will center text in <p>, which is not a flex item */
}
#redbox{
background-color:red;
}
#bluebox{
background-color:blue;
}
HTML
<div id="container"><!-- flex container -->
<div class="divs" id="bluebox"><!-- flex item -->
<p>First Div</p>
</div>
<div class="divs" id="redbox"><!-- flex item -->
<p>Second Div</p>
</div>
</div>
Output:
For Horizontal div's considering the above HTML and given points, we can have below CSS
#container {
display: flex; /* establish flex container */
flex-direction: row; /* make main axis horizontal, CHANGE HERE REST IS SAME */
justify-content: center; /* center items vertically, in this case */
align-items: center; /* center items horizontally, in this case */
height: 200px;
}
.divs {
width: 200px;
margin: 5px;
color:white;
text-align: center; /* will center text in <p>, which is not a flex item */
}
Output:
Hope it helps.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly