0

How to make a responsive boxes with elements centered both horizontally and vertically inside it using css flex?

Shuvo Habib
  • 2,035
  • 1
  • 20
  • 25

2 Answers2

1

You can do it simply by using justify-content: center & align-items: center.

A Complete Guide to Flexbox

HTML

<div class="container">
    <div class="item"></div>
    <div class="item"></div>
</div>

CSS

.container {
    width: 100%;
    height: 90vh;
    background: #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
}

.item {
    width: 100px;
    height: 100px;
    background: tomato;
    border: 1px solid #fff;
}

Example http://jsfiddle.net/shishirmorshed/2x3ebpwa/

Shishir Morshed
  • 797
  • 8
  • 21
-1

Some times it's needed you want to center element in a box both vertically and horizontally . There are tons of ways doing that, most of them are too complex and not even responsive. But the easiest way of doing the trick is using flex. I will show you doing that in 4 boxes that will be place horizontally one by one. And they will take equal width in your browser window.

First let us see the example, what we're making: http://jsfiddle.net/shuvohabib/28ehpLbc/

Now let's discuss the matter display:flex to the container that is the wrapper. We have to use flex:1 in the child class box to specify each and every boxes are getting the same width . You can play around it by using nth-child of the .container>.box to see how it works. Moreover you can use media query for more control.
"align-items:center;" is for centering the element vertically in the box and justify-content:center; is for centering the element horizontally. Thanks and Hope it helps.

<style type="text/css">
           .container{
                display:flex;
            }
            .box {
                background: red;
                flex:1;
                height: 200px;
                text-align: center;
                align-items:center;
                justify-content:center;
                display: flex;
                margin-right: 10px;
            }

</style>
<div class="container">
    <div class="box">1</div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
</div>
Shuvo Habib
  • 2,035
  • 1
  • 20
  • 25