Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center div using Flexbox

Tags:

css

flexbox

I am trying to center the outer 'div' container using Flexbox. I have an unordered list with 3 li's. The li's width is: width: calc(100%/3). The ul's width is 70%. The problem is that when I try centering the ul (justify-content: center), it doesn't get centered.

I finally figured out the source of the problem. When I remove the line: width: calc(100%/3), it centers properly. My question is: How can I get it to center properly?

I tried margin: auto, but that didn't work.

Here's the JSFiddle, and here's the code snippet:

#flex-container {
  width: 70%;
  list-style-type: none;
  padding: 0;
  margin: 0;
  display: -webkit-inline-flex;
  display: inline-flex;
  -webkit-justify-content: center;
  justify-content: center;
}
li {
  box-sizing: border-box;
  background-color: tomato;
  width: calc(100%/3);
}
<ul id="flex-container">
  <li class="flex-item">First</li>
  <li class="flex-item">Second</li>
  <li class="flex-item">Third</li>
</ul>
like image 279
Jessica Avatar asked Aug 17 '26 13:08

Jessica


1 Answers

When I remove the line: width: calc(100%/3), it centers properly

You should not calculate the width when you are using flex layout, because that is what flex is itself supposed to do.

  1. If you are looking to align the text inside of the lis then text-align is what you need. You should also remove the width from the lis and use the flex property instead.

Snippet:

* { box-sizing: border-box; padding: 0; margin: 0; }
#flex-container {
    list-style-type: none;
    width: 70%; display: flex; 
}
li {
    flex: 1 1 auto;
    background-color: tomato; border: 1px solid #fff;
    text-align: center;   
}
<ul id="flex-container">
    <li class="flex-item">First</li>
    <li class="flex-item">Second</li>
    <li class="flex-item">Third</li>
</ul>
  1. If you are looking to have variable width lis then justify-content is what you need. You should control the width via the width property and use flex property as required to expand or shrink.

Snippet:

* { box-sizing: border-box; padding: 0; margin: 0; }
#flex-container {
    list-style-type: none; width: 70%;
    display: flex; justify-content: center;
    background-color: #eee;
}
li {
    flex: 0 0 auto; width: 15%;
    background-color: tomato; border: 1px solid #fff;
}
li:first-child { width: 20%; }
li:last-child { width: 30%; }
<ul id="flex-container">
    <li class="flex-item">First</li>
    <li class="flex-item">Second</li>
    <li class="flex-item">Third</li>
</ul>
like image 160
Abhitalks Avatar answered Aug 20 '26 12:08

Abhitalks