How to center flexbox container alignment?

I successfully created a sensitive grid, as the fragment shows.

Currently, I see the fields aligned to the left.

How can I put the container in the center of the page without using a pad?

I tried using margin:auto , but that 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 .

+6
source share
4 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 documents in MDN .

Updated JS script .

+6
source

just add this line to your source code:

 .container{ width: 100% } 

and put the div field in another div that has margin: auto;

if you need 2 fields in one row, add display: inline-table; to class box

0
source

Use margin:0px auto; using width .

For instance:

 .container{ display:flex; flex-wrap:wrap; text-align:center; margin:0px auto; width: 400px; } 
0
source

So, if you want the fields to be added from left to right, and the first field in the next line is left aligned, you can use: `

 .container { display:flex; flex-flow: row wrap; justify-content: flex-start; margin: 0 auto; border: 1px solid red; } .container:after { content: ""; flex: auto; } 

Fiddle

0
source

All Articles