英文:
How to center a flex child vertically which has height set to 100%
问题
我想要垂直居中红色框中的数字。
英文:
I've some elements within a flex div that I want to be the same height as its parent, but also to center its contents vertically.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.container{
display:flex;
border:1px solid orange;
}
li{
border:1px solid red;
height:100%;
}
ul{
list-style:none;
display:flex;
margin:0;
align-items:center;
}
<!-- language: lang-html -->
<div class="container">
<div class="any-height">
0
<br>
0
</div>
<ul class='should-stertch'>
<li class="">1</li>
<li class="">2</li>
<li class="">3</li>
<li class="">4</li>
</ul>
</div>
<!-- end snippet -->
Basically I want to vertically center the numbers in the red boxes.
答案1
得分: 0
请查看以下已翻译的内容:
使用 flexbox 在 li 元素上。让它们具有 display: flex 和 align-items: center,就像这样:
.container{
display:flex;
border:1px solid orange;
}
li{
display: flex;
align-items: center;
border:1px solid red;
height:100%;
}
ul{
list-style:none;
display:flex;
margin:0;
align-items:center;
}
<div class="container">
<div class="any-height">
0
<br>
0
</div>
<ul class='should-stertch'>
<li class="">1</li>
<li class="">2</li>
<li class="">3</li>
<li class="">4</li>
</ul>
</div>
align-items 会沿着次轴对齐容器的内容。在这种情况下,由于 flex 默认是行方向,所以次轴是垂直方向。
英文:
Use flexbox on the li elements. Have them have display: flex and align-items: center, like this:
<!-- begin snippet: js hide: false console: true babel: null -->
<!-- language: lang-css -->
.container{
display:flex;
border:1px solid orange;
}
li{
display: flex;
align-items: center;
border:1px solid red;
height:100%;
}
ul{
list-style:none;
display:flex;
margin:0;
align-items:center;
}
<!-- language: lang-html -->
<div class="container">
<div class="any-height">
0
<br>
0
</div>
<ul class='should-stertch'>
<li class="">1</li>
<li class="">2</li>
<li class="">3</li>
<li class="">4</li>
</ul>
</div>
<!-- end snippet -->
Align-items aligns the content of the container across the secondary axis. In this case, since flex is a row by default, the vertical axis.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论