【问题标题】:Grid inside flex with fixed-width left and right sidebars带有固定宽度左右侧边栏的 flex 内部网格
【发布时间】:2019-05-19 15:33:56
【问题描述】:

我正在尝试使用 html 和 css 进行以下操作: Image sketch

基本上,我想做到这一点:

  • 左侧和右侧边栏的宽度始终为 200 像素,并且它们本身没有填充或边距(它们的高度为 100%)
  • 中间有12列的grid-gap 10px的grid-gap

网格本身的结构并不重要(我知道这部分),但我无法以正确的顺序对齐 div(左侧、网格和右侧边栏)。

#container{
	display: flex;
}

#left-sidebar{
	background-color: blue;
	height: 100%;
    width: 200px;
	position: fixed;
	left: 0;
}

#grid{
	display: grid;
	grid-template-columns: repeat(12,1fr);
	grid-template-rows: repeat(12, 1fr);
	grid-gap: 10px;
	height: 100vh;
	padding: 10px;
  flex: 1;
}

#right-sidebar{
	background-color: blue;
	height: 100%;
    width: 200px;
	position: fixed;
	right: 0;
}

#g1{
	background-color: orange;
	grid-column: 1 / 4;
	grid-row: 1 / last-line;
	border-radius: 4px;
}

#g2{
	background-color: red;
	grid-column: 4 / 13;
	grid-row: 1 / last-line;
	border-radius: 4px;
}
<div id="container">

  <div id="left-sidebar"></div>
  
  <div id="grid">
    <div id="g1"></div>
    <div id="g2"></div>
  </div>
  
  <div id="right-sidebar"></div>
  
 </div>

我希望网格位于这两个侧边栏之间...

【问题讨论】:

    标签: html css flexbox css-grid


    【解决方案1】:

    您可以在网格的左侧和右侧添加一个 200 像素的填充,因此它位于侧边栏之间。

    #container{
    	display: flex;
    }
    
    #left-sidebar{
    	background-color: blue;
    	height: 100%;
        width: 200px;
    	position: fixed;
    	left: 0;
    }
    
    #grid{
      padding-left: 200px !important;
    padding-right: 200px !important;
    	display: grid;
    	grid-template-columns: repeat(12,1fr);
    	grid-template-rows: repeat(12, 1fr);
    	grid-gap: 10px;
    	height: 100vh;
    	padding: 10px;
      flex: 1;
    }
    
    #right-sidebar{
    	background-color: blue;
    	height: 100%;
        width: 200px;
    	position: fixed;
    	right: 0;
    }
    
    #g1{
    	background-color: orange;
    	grid-column: 1 / 4;
    	grid-row: 1 / last-line;
    	border-radius: 4px;
    }
    
    #g2{
    	background-color: red;
    	grid-column: 4 / 13;
    	grid-row: 1 / last-line;
    	border-radius: 4px;
    }
    <div id="container">
    
      <div id="left-sidebar"></div>
      
      <div id="grid">
        <div id="g1"></div>
        <div id="g2"></div>
      </div>
      
      <div id="right-sidebar"></div>
      
     </div>

    【讨论】:

    • 好的,你会考虑那个好的解决方案吗?这 3 个 div 中的每一个都无法相互“了解”并自动对齐?
    • 这完全没问题!因为您有 position: fixed,所以您的侧边栏已从“正常”流程中删除,这就是为什么您有问题中的行为。要么按照我的建议使用填充,要么尽量不使用 position: fixed 并让你的侧边栏 div 保持正常流动
    • 好的,我现在就这样了。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2012-07-30
    • 2015-02-04
    • 2014-04-05
    相关资源
    最近更新 更多