Flexbox的align-content和justify-content属性无法正常工作

6

我设置了特定的宽度,并且我的flex项目上没有margin: auto,但是由于某些原因,这些属性没有按预期工作。

我只想在headbox和list classes之间添加间距。

现在在我的电脑上,headbox是居中的,但在片段上不是,我不确定为什么,即使justify-content设置为居中也是如此。

但是即使在我的电脑上,align-items也没有像应该一样工作。

我的意思是,我知道它没有影响,但那只是如果只有一个项目的情况。

我还注释掉了一些常见的问题,但那并没有起作用。

最后,right实际上是更大的容器div的一部分,但这应该是无关紧要的。如果您对片段进行全屏显示,您将看到我在说什么。

.right {
  display: flex;
  position: relative;
  flex-flow: row wrap;
  align-items: space-between;
  justify-content: center;
  // text-align: center;
  order: 3;
  //background: yellow;
  flex: 1 50%;
  height: 100%;
}
div.list {
  display: flex;
  flex-flow: row wrap;
  width: 70%;
  justify-content: center;
  line-height: 300%;
  border: 1px solid pink;
}
.right .headbox {
  border-bottom: 1px solid orange;
  width: 70%;
  height: auto;
}
.right .list {
  // text-align: center;
  height: auto;
}
.list ul {
  list-style: none;
  padding: 0;
}
.list a {
  text-decoration: none;
  color: inherit;
}
<div class="right">
  <div class="headbox">
    <h3>Visit Us</h3>
  </div>
  <div class="list">
    <ul>
      <li><a href="#">Home</a>
      </li>
      <li><a href="#">Hours</a>
      </li>
      <li><a href="#">Plan</a>
      </li>
      <li><a href="#">Directions</a>
      </li>
    </ul>
  </div>
</div>

1个回答

10

实际上,justify-contentalign-items都工作正常。

你没有得到想要的结果是由于其他原因。


首先,请记住,flex formatting context的范围是父子关系。

这意味着超出子元素的后代不是 flex 项,也不接受 flex 属性。

因此,每当您想将 flex 属性应用于元素时,请确保父级是 flex 容器(display: flexdisplay: inline-flex)。

您的具有justify-content: center.right flex 容器实际上已经将.headbox居中了。在.right.headbox周围添加边框以清楚地看到这一点。

但是,如果您想使用 flex 属性居中<h3>,还需要使.headbox成为 flex 容器:

.headbox {
    display: flex;
    justify-content: center;
    align-items: center;
}

其次,你的布局没有定义高度。它默认为height: auto(内容的高度)。因此,align-items没有空间来移动元素。

请将以下代码添加到你的代码中:


html, body { height: 100%; }

html, body { height: 100%; }      /* NEW */

.right {
    display: flex;
    position: relative;
    flex-flow: row wrap;
    align-items: space-between;
    justify-content: center;
    order: 3;
    flex: 1 50%;
    height: 100%;
}

div.list {
    display: flex;
    flex-flow: row wrap;
    width: 70%;
    justify-content: center;
    line-height: 300%;
    border: 1px solid pink;
}

.right .headbox {
    border-bottom: 1px solid orange;
    width: 70%;
    height: auto;
    
    display: flex;                 /* NEW */
    justify-content: center;       /* NEW */
    align-items: center;           /* NEW */
}

.right .list {
    height: auto;
}

.list ul {
    list-style: none;
    padding: 0;
}

.list a {
    text-decoration: none;
    color: inherit;
}
<div class="right">
    <div class="headbox">
        <h3>Visit Us</h3>
    </div>
    <div class="list">
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Hours</a></li>
            <li><a href="#">Plan</a></li>
            <li><a href="#">Directions</a></li>
        </ul>
    </div>
</div>

jsFiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接