无法使用align-self将Flex项目居中

时间:2016-11-21 16:28:30

标签: html css css3 flexbox

我有一个简单的布局要求,我想在正常情况下显示标题和徽标,并在页面上垂直居中。

根据我的理解,这应该可以通过flexbox使用align-self属性轻松实现。

这是我的代码:

html,
body {
  height: 100%;
}
.base {
  display: flex;
  align-content: flex-start;
  flex-wrap: wrap;
  min-height: 100%;
  background: blue;
}
.header {
  flex-grow: 1;
  flex-basis: 100%;
  height: 30px;
  background: yellow;
}
.logo {
  flex-grow: 1;
  flex-basis: 100%;
  height: 50px;
  background: orange;
}
.content {
  flex-grow: 1;
  flex-basis: 100%;
  align-self: center; /* <<< DOESN"T SEEM TO WORK */
  background: green;
}
<div class="base">
  <div class="header">HEADER</div>
  <div class="logo">LOGO</div>
  <div class="content">CONTENT</div>
</div>

jsFiddle

2 个答案:

答案 0 :(得分:4)

align-self属性与align-items密切相关。一个旨在覆盖另一个。因此,they both function together

但是,align-selfalign-items主要用于 单行灵活容器 (即flex-wrap: nowrap )。

当您使用 多行灵活容器 (即flex-wrap: wrap)时 - 就像问题一样 - 要使用的属性是{ {3}}

但当align-content生效时,align-itemsalign-self都会被覆盖。

  

因此,应用于align-self元素的.content规则将被忽略,因为您的Flex容器中有多行。

问题的一个可能解决方案是将容器从row切换到column,然后在auto上使用.content页边距:

html, body {
  height: 100%;
}
.base {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  background: blue;
}
base > * {
  width: 100%;
}
.header {
  height: 30px;
  background: yellow;
}
.logo {
  height: 50px;
  background: orange;
}
.content {
  margin: auto 0;
  background: green;
}
<div class="base">
  <div class="header">HEADER</div>
  <div class="logo">LOGO</div>
  <div class="content">CONTENT</div>
</div>

align-content

请注意,上面的解决方案将内容元素垂直居中在剩余空间中,而不是容器中的总空间

要将元素置于总空间中心,请参阅此帖子:revised fiddle

有关auto页边距的详情,请参阅此帖:Center and bottom-align flex items

答案 1 :(得分:0)

对齐自我工作会尊重弹性项目所在的当前行。

因此,如果您希望元素在flex容器中居中,则必须只有一行(在您的情况下,只有一行)

该代码段显示了其工作原理,即使它不是您问题的解决方案:

html, body {
  height: 100%;
}

.base { 
  display: flex;
  align-content: flex-start;
  flex-wrap: wrap;
  min-height: 100%;
  background: blue;
}

.header {
  flex-grow: 1;
  flex-basis: 30%;
  height: 30px;
  background: yellow;
}

.logo {
  flex-grow: 1;
  flex-basis: 30%;
  height: 50px;
  background: orange;
}

.content {
  flex-grow: 1;
  flex-basis: 30%;
  align-self: center; /* <<< DOESN"T SEEM TO WORK */
  background: green;
}
<div class="base">
  <div class="header">HEADER</div>
  <div class="logo">LOGO</div>
  <div class="content">CONTENT</div>
</div>

相关问题