【问题标题】:How to make flex items that are also flex containers stack horizontally?如何使也是弹性容器的弹性项目水平堆叠?
【发布时间】:2018-02-21 11:21:15
【问题描述】:

我正在尝试创建一个水平菜单。我对 flexbox 的理解是,如果我想让元素水平堆叠,我应该应用 CSS 规则

display: flex
flex-direction: row;

但是,在接下来的页面中,盒子是垂直堆叠的

div#navcontainer {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}

div.navitem {
  color: #292929;
  height: 45px;
  width: 150px;
  padding: 5px;
  border-color: 292929;
  border-width: 2px;
  border-style: solid;

  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
<div id="header">
  <div id="navcontainer">
    <div class="navitem"><a href="./index.html">home</a></div>
    <div class="navitem"><a href="./about.html">about</a></div>
    <div class="navitem"><a href="./services.html">services</a></div>
    <div class="navitem"><a href="./contact.html">contact</a></div>
  </div>
</div>

我如何使 css 弹性项目本身是其他元素的弹性容器垂直堆叠?

【问题讨论】:

  • 请注意,在您的 HTML 中您有 id="navcontainer",但在 CSS 中它是 .navcontainer...您还将 navcontainer 设置为 flex-direction: column,它垂直堆叠项目。
  • 第一个错误是由其他人的编辑引入的,将 css 和 html 拆分为单独的块。第二个错误是我自己的——在询问 SO 之前我尝试的最后一件事是查看 flex-direction: column 是否会自相矛盾地工作。
  • 其实没有。第一个错误出现在我最初的问题中,实际上是问题的原因:当我应该引用 id 时,我将选择器写错以引用 class navcontainer 。所以我的display: flex 根本就没有被申请。

标签: html css layout flexbox


【解决方案1】:

水平弯曲方向是默认方向,所以flex-direction: row 是多余的。现在你有一个包含垂直弹性框的水平列表。

#navcontainer {
  display: flex;
  flex-wrap: nowrap;
}

.navitem {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

【讨论】:

  • 抱歉——我的意思是让flex-direction: row 加入#navcontainer。
【解决方案2】:

display: flex 设置为#navcontainer。你也可以在没有 flexbox 的情况下获得它。对框使用display: inline-block 和百分比值。

【讨论】:

  • 使用display: inline-block,当屏幕太小时,项目会自动换行,对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 2016-02-04
  • 1970-01-01
  • 2023-04-10
  • 2021-11-01
  • 2018-04-15
  • 2017-10-01
相关资源
最近更新 更多