我想使用flexbox垂直对齐一些内容在一个<li>,但没有很大的成功。

我在网上检查过,许多教程实际上使用了一个包装器div,它从父上的伸缩设置中获得align-items:center,但我想知道是否有可能删除这个额外的元素?

在这个例子中,我选择使用flexbox,因为列表项的高度将是一个动态%。

* { 填充:0; 保证金:0; } 超文本标记语言 身体{ 高度:100%; } ul { 高度:100%; } 李{ 显示:flex; justify-content:中心; align-self:中心; 背景:银色; 宽度:100%; 高度:20%; } < ul > <li>这是文本</li> < / ul >


当前回答

结果

HTML

<ul class="list">
  <li>This is the text</li>
  <li>This is another text</li>
  <li>This is another another text</li>
</ul>

使用align-items而不是align-self,我还添加了flex-direction到column。

CSS

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
}

.list {
  display: flex;
  justify-content: center;
  flex-direction: column;  /* <--- I added this */
  align-items: center;   /* <--- Change here */
  height: 100px;
  width: 100%;
  background: silver;
}

.list li {  
  background: gold;
  height: 20%; 
}

其他回答

使用display: flex可以控制HTML元素的垂直对齐。

.box { 身高:100 px; 显示:flex; 对齐项目:中心;/*垂直*/ justify-content:中心;/*水平*/ 边框:2px纯黑色; } .box div { 宽度:100 px; 高度:20 px; 边界:1 px固体; } < div class = "盒子" > < div > < / div >你好 世界< p > < / p > < / div >

结果

HTML

<ul class="list">
  <li>This is the text</li>
  <li>This is another text</li>
  <li>This is another another text</li>
</ul>

使用align-items而不是align-self,我还添加了flex-direction到column。

CSS

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
}

.list {
  display: flex;
  justify-content: center;
  flex-direction: column;  /* <--- I added this */
  align-items: center;   /* <--- Change here */
  height: 100px;
  width: 100%;
  background: silver;
}

.list li {  
  background: gold;
  height: 20%; 
}

我就不写答案了,因为很多人已经给出了正确答案。但是,我想向您展示一个有用的工具,可以在将来避免此类问题。

在浏览器的Dev Tools中,你需要检查一个元素,并使用display: flex on,按屏幕截图中显示的图标。

然后,您将看到选择要显示的一些属性的选项:flex,这样您就可以轻松地快速检查所有选项,而不知道您可以使用什么

最好的做法是将一个flexbox嵌套在一个flexbox中。你所要做的就是给子元素align-items: center。这将垂直对齐父文本。

// Assuming a horizontally centered row of items for the parent but it doesn't have to be
.parent {
  align-items: center;
  display: flex;
  justify-content: center;
}

.child {
  display: flex;
  align-items: center;
}

投票最多的答案是解决OP发布的这个特定问题,其中内容(文本)被包装在一个内联块元素中。有些情况下,可能是关于一个正常的元素在容器内垂直居中,这也适用于我的情况下,所以你所需要的是:

align-self: center;