Creating a Sidebar within a flexbox with CSS [duplicate]

*爱你&永不变心* 提交于 2019-12-24 06:37:14

问题


on my page I want to have a header and below this I want to have a sidebar on the left side and the content page on the right side.

The sidebar should have a width of X (maybe 100 px) and the content page should have the rest of the full window with.

I started creating this but my sidebar and content page don't have a full height. Even when setting height to 100% the don't fill the rest of the page.

And why do I have to set a min and max width for the sidebar instead of width? When setting width: 100px the width returns 70px.

html {
  height: 100%;
}

body {
  height: 100%;
  margin: 0;
  font-family: Ubuntu;
  background: linear-gradient(#b3ffab, #67fffc);
}

#header {
  height: 30px;
  display: flex;
  align-items: center;
  background: linear-gradient(#444444, #333333);
  color: #bbbbbb;
}

#headerContent {
  margin-left: 10px;
}

#page {
  display: flex;
}

#sideBar {
  min-width: 100px;
  max-width: 100px;
  background: red;
}

#content {
  width: 100%;
  background: blue;
}
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Ubuntu" />

<div id="header">
  <div id="headerContent">
    Desktop
  </div>
</div>

<div id="page">
  <div id="sideBar">
    <div>
      box 1
    </div>
    <div>
      box 2
    </div>
  </div>
  <div id="content">
    content
  </div>
</div>

回答1:


You can set the height and width in a flexible way.

  • Height is set to 100% of the height of the viewport minus the height of the header.
  • Width is set to 100px for the sidebar. The content is now allowed to grow to fill the rest of the screen.

Hope this helps.

html {
  height: 100%;
}

body {
  height: 100%;
  margin: 0;
  font-family: Ubuntu;
  background: linear-gradient(#b3ffab, #67fffc);
}

#header {
  height: 30px;
  display: flex;
  align-items: center;
  background: linear-gradient(#444444, #333333);
  color: #bbbbbb;
}

#headerContent {
  margin-left: 10px;
}

#page {
  display: flex;
  height: calc( 100vh - 30px);
  /* calculate the height. Header is 30px */
}

#sideBar {
  width: 100px;
  background: red;
}

#content {
  background: blue;
  flex: 1 0 auto;
  /* enable grow, disable shrink */
}
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Ubuntu" />

<div id="header">
  <div id="headerContent">
    Desktop
  </div>
</div>

<div id="page">
  <div id="sideBar">
    <div>
      box 1
    </div>
    <div>
      box 2
    </div>
  </div>
  <div id="content">
    content
  </div>
</div>


来源:https://stackoverflow.com/questions/48822650/creating-a-sidebar-within-a-flexbox-with-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!