Vertical 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'm trying to get the content of an element vertically, is there a flexbox way to do this?
+3
source to share
2 answers
Yes flexbox is great for this. You can use the existing layout and just use inline-flex
in 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 can also just set the line-height
content to the parent's height 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>
+4
source to share
You can add registration at the top of your face
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>
0
source to share