【问题标题】:flex direction "row" inside a flexbox with flex-direction "column"带有 flex-direction “column” 的 flexbox 内的 flex 方向 “row”
【发布时间】:2020-09-01 18:23:22
【问题描述】:

我正在尝试使用 flexbox 制作导航栏。在我的代码中,我用 flex-direction:"row" 包裹了实际的导航栏,以对齐徽标和按钮。 现在我想在导航栏(应该是 100vw 宽)下有 nav-inner(米色 div),但实际上它位于导航栏旁边。 我试图在我的导航菜单 div 中将 flex-direction 更改为“列”,但汉堡按钮会从屏幕上消失。我做错了吗?

body {
  margin: 0;
  overflow: hidden;
}

/* defaults */
.safe-view {
  display: flex;
  height: 100vh;
}

.hamburger {
  height: 30px;
  width: 30px;
}

/**/
/* navbar */
.navbar {
  position: sticky;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30px;
  width: 100vw;
  font-size: 1.2em;
  height: 100px;
}

.nav-menu {
  width: 100%;
  display: flex;
  flex-direction:row;
  /*flex-direction:column;*/
  position: absolute;
  height: 100%;
  overflow: hidden;
  background-color: white;
}


.nav-inner {
  height: 100%;
  width: 100%;
  background-color: blanchedalmond;
}

/**/
<div class="safe-view">
        <div class="nav-menu">
            <div class="navbar">
                <h1>logo</h1>
                    <button class="hamburger"></button>
            </div>
            <div class="nav-inner"></div>
        </div>
    </div>

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    这是一个 CSS 盒子模型问题。您需要添加box-sizing: border-box。这将确保填充包含在宽度的计算中。

    *{
       box-sizing: border-box;  
    }
    

    默认情况下,box-sizing 设置为content-box。这将只关心元素内容和元素外的填充和边框。这就是为什么您看到按钮向右推出的原因! This也可以帮助你进一步了解。

    此外,flex-direction for .nav-menu 需要设置为 column 才能将 .nav-inner 定位在下方。

    这是另一种选择。我删除了填充,只是使用calc() 函数来创建填充。但始终在您的 CSS 中包含 box-sizing:border-box :)

    *{
       box-sizing: border-box;  
    }
    
    
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
    }
    
    .safe-view {
      display: flex;
      height: 100vh;
    }
    
    .navbar {
      position: sticky;
      display: flex;
      flex-direction:row;
      align-items: center;
      justify-content: space-between;
      width: calc(100vw - 60px);
      margin: 0 auto;
      font-size: 1.2em;
      height: 100px;
    }
    
    .nav-menu {
      width: 100%;
      display: flex;
      flex-direction:column;
      position: absolute;
      height: 100%;
      overflow: hidden;
      background-color: white;
    }
    
    .nav-inner {
      height: 50px;
      width: 100%;
      background-color: blanchedalmond;
    }
    <div class="safe-view">
      <div class="nav-menu">
        <div class="navbar">
          <h1 class="logo">logo</h1>
          <button class="hamburger">button</button>
        </div>
        <div class="nav-inner"></div>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 2018-07-21
      • 2016-11-26
      • 2016-11-19
      • 1970-01-01
      • 2021-11-25
      • 2020-07-26
      相关资源
      最近更新 更多