使用flexbox无法将侧边栏贴到左边。

问题描述 投票:0回答:1

我有一个简单的布局:页眉+侧栏+表单。我想把侧边栏放在左边,而表单则放在中间位置。侧边栏和表单都在一个包装盒内。content 鸿沟 display: flex; flex-direction: row; justify-content:center. 我试着设置 margin-left:0 在侧边栏 div但它没有工作。

JsFidlde: https:/jsfiddle.net2qzmkwaj。

电流输出。

需要实现。

/*
  Positioning
*/

#app {
  display: flex;
  flex-direction: column;
  justify-items: center;
}

#navbar {
  display: flex;
  justify-content: flex-end;
}

#navbar .button {
  margin-right: 20px;
  background-color: green;
}

#header {
  background-color: dimgray;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

#logo-wrapper {
  display: flex;
  justify-content: center;
  flex-direction: row;
  width: 100%;
}

#content {
  display: flex;
  justify-content: center;
  border: 1px solid red;
  height: 100%;
}

#sidebar {
  margin-left: 0 !important;
  border: 1px solid black;
  height: 100%;
}

#content form {
  margin-left: 0;
  border: 1px solid white;
  height: 100%;
}

/*
  Colors
*/

#sidebar {
  background-color: yellow;
}

body {
  background-color: chocolate;
}

#content textarea {
  background-color: black;
  color: silver;
}
<div id="app">

  <div id="header">
    <div id="navbar">
      <div class="button">
        Button
      </div>
      <div class="button">
        Button
      </div>
      <div class="button">
        Button
      </div>
    </div>

    <div id="logo-wrapper">
      <div id="logo">
        <img width="100" src="https://i.pinimg.com/originals/37/25/de/3725deaa9c536997aaa2f4956c2045b3.jpg" />
      </div>
    </div>
  </div>

  <div id="content">

    <div id="sidebar">
      <div class="sidebar-option">
        Option
      </div>

      <div class="sidebar-option">
        Option
      </div>

      <div class="sidebar-option">
        Option
      </div>
    </div>

    <form>
      <textarea></textarea>
    </form>
  </div>
</div>

我还需要让侧栏占据整个页面的高度。我尝试了 height: 100% 在两个 contentsidebar divs,但它没有工作。

html css flexbox
1个回答
3
投票

在你的css中,尝试添加以下内容

#content > *{
    margin-right: auto;
    height: calc(100vh - 115px);
}

这是为了将侧边栏调整到屏幕左侧,并使侧边栏覆盖剩余的屏幕高度。

让我来解释一下发生了什么。

当你说margin-right: auto时,你是说屏幕右侧的边距应该自动确定。所以在这种情况下,它对齐屏幕的左侧。

而现在对于让侧边栏成为屏幕的高度。

我们说我们要让侧边栏的高度为100vh,也就是100个视图高度。但是,如果我们就这样放着,侧边栏将占据整个页面的高度(包括标志和上面的2个div)。但我们不希望这样。我们想让侧边栏占据整个页面的 歇息 的高度(不包括标志和上面的2个div)。所以我们计算logo的高度(79px)+2个div的高度(18px+18px)。所以总高度将是115px。所以简单的说,我们只要从100vh中减去115px就可以了。

希望对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.