Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center align a flexbox container? [duplicate]

Tags:

I successfully created a responsive grid as the snippet shows.

At the moment, I see the boxes aligned to the left.

How can I put the container in the center of the page without having to use padding?

I tried using margin:auto but it did not work.

.container{      display:flex;      flex-wrap:wrap;      text-align:center;      margin:auto;  }  .box{      width:100%;      max-width:30%;      border:1px solid red;      margin:5px;  }  @media only screen and ( max-width:768px ){	      .box{          width:100%;          max-width:40%;          border:1px solid red;      }  }
<section class="container">      <div class="box">          <h1>This is the first box</h1>          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci voluptates, aut totam eaque possimus molestiae atque odio vero optio porro magni, quis culpa ea. Perferendis, neque, enim. Rem, quia, quisquam.</p>      </div>  </section>

JS Fiddle.

like image 746
user agent Avatar asked Aug 11 '16 12:08

user agent


People also ask

How do you center a Flex box container?

To center the inner div element we will make the parent a flex container. By adding the display: flex; property we make the section element a flex container allowing us to adjust the layout of the div which is now a flex item. To center out item horizontally we use the justify-content: center; .

How do you center a Flex container but left align Flex items?

Using the code posted in the question, we could create a new flex container that wraps the current flex container ( ul ), which would allow us to center the ul with justify-content: center . Then the flex items of the ul could be left-aligned with justify-content: flex-start .

How do I align two items in flexbox?

With the existing markup, using flex-direction: column , you can't make those two "buttons" align side-by-side. One way is to change to row wrap and make all the input + label 100% width, which can be done with either width: 100% (used below) or flex-basis: 100% .


2 Answers

Use justify-content: center; instead of margin: auto;:

.container {   display: flex;   flex-wrap: wrap;   text-align: center;   justify-content: center; } .box {    width: 100%;    max-width: 30%;    border: 1px solid red;    margin: 5px; } @media only screen and (max-width: 768px) {    .box {     width: 100%;     max-width: 40%;     border: 1px solid red;   } } 

See justifiy-content docs on MDN.

Updated JS Fiddle.

like image 112
Michał Perłakowski Avatar answered Oct 21 '22 18:10

Michał Perłakowski


just add this line to your original code:

.container{   width: 100% } 

and put the div box into another div that have a margin: auto;

if you need 2 boxes in the same line add display: inline-table; to the box class

like image 33
Alaa DAIRY Avatar answered Oct 21 '22 17:10

Alaa DAIRY