fightstarr20
fightstarr20

Reputation: 12598

Vertically center list item content with Flexbox?

I have the following simple list...

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-block;margin-right:10px;background:green;color:white;}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

I am trying to get the item contents to be vertically centered, is flexbox the way to do this?

Upvotes: 3

Views: 1987

Answers (2)

Jake Winters
Jake Winters

Reputation: 85

You could add padding on the top of your li

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;padding-top: 100px;display:inline-block;margin-right:10px;background:green;color:white;}
since you directly defined the height of the box I was able to just divide that value in half in order to center the content using padding. If you don't know the difference between padding margin and border. Look into the box model in css. It is one of the most fundamental concepts you will need to grasp to have a good understanding of css.

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

Upvotes: 0

Michael Coker
Michael Coker

Reputation: 53674

Yes flexbox is great for this. You can use the existing layout and just use inline-flex on the li and set align-items: center to vertically center the content.

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-flex;margin-right:10px;background:green;color:white;align-items:center;}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

You could also just set the line-height of the content to the height of the parent and it will center the content vertically.

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-block;margin-right:10px;background:green;color:white;line-height:200px;}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

Upvotes: 5

Related Questions