Search code examples
htmlcssflexboxcentering

How to position list in the center using flexbox?


I have 3 boxes that are stacked vertically using flexbox. They are positioned to the left now. I want to center them in horizontal direction. I tried div {margin:10px auto} and it works but css looks awkward. Is there any more elegant solution using special flexbox properties?

I want divs in center.

section {
  display: flex;
  flex-direction: column;
  background-color: teal;
}

div {
  background-color: silver;
  width: 200px;
  margin: 10px;
  line-height: 75px;
  font-size: 30px;
}
<section>
	<div>apple</div>
	<div>banana</div>
	<div>pear</div>
</section>


Solution

  • You can center the divs using align-items: center and center the text inside the divs using text-align: center like this:

    section {
      display: flex;
      flex-direction: column;
      background-color: teal;
      align-items: center;
      text-align: center;
    }
    
    div {
      background-color: silver;
      width: 200px;
      margin: 10px;
      line-height: 75px;
      font-size: 30px;
    }
    <section>
    	<div>apple</div>
    	<div>banana</div>
    	<div>pear</div>
    </section>