【问题标题】:CSS grid 3 column layout, shrink center after margins have shrank to 0pxCSS网格3列布局,边距缩小到0px后收缩中心
【发布时间】:2019-09-07 13:00:03
【问题描述】:

我想创建一个 CSS 网格响应式 3 列布局,中心列 500 像素,边距占用剩余空间。

但是,当屏幕的大小调整为小于 500 像素时,我希望中心栏缩小,边距完全不占空间 (0 像素)。

我已经使用以下代码完成了这项工作,但我发现除了使用媒体查询和摆弄数字之外别无他法!我确信仅使用网格模板列应该可以做到这一点,但找不到方法。谁能帮忙。

<html>

<head>

  <style>
    .grid {
      display: grid;
      margin: 20px;
      grid-template-columns: 1fr 500px 1fr;
      align-items: stretch;
      justify-items: stretch;
    }
    
    @media only screen and (max-width: 560px) {
      .grid {
        grid-template-columns: 0 1fr 0;
      }
    }
    
    .left {
      grid-column: 1;
      background-color: red;
      height: 200px;
    }
    
    .centre {
      grid-column: 2;
      background-color: green;
    }
    
    .right {
      grid-column: 3;
      background-color: blue;
    }
  </style>
</head>

<body>
  <div class="grid">
    <div class="left"></div>
    <div class="centre"></div>
    <div class="right"></div>
  </div>
</body>

</html>

【问题讨论】:

  • 侧栏会包含内容吗?还是仅用于对齐中间列?
  • 是的,它们包含内容。

标签: css layout css-grid


【解决方案1】:

<html>

<head>

  <style>
    .grid {
      display: grid;
      margin: 20px;
      grid-template-columns: 1fr 1fr 1fr;
    }

    .left {
      grid-column: 1;
      background-color: red;
      height: 200px;
    }
    
    .centre {
      grid-column: 2;
      background-color: green;
      max-width: 500px;
      margin: 0 auto 0;
      width: 100%
    }
    
    .right {
      grid-column: 3;
      background-color: blue;
    }
  </style>
</head>

<body>
  <div class="grid">
    <div class="left"></div>
    <div class="centre"></div>
    <div class="right"></div>
  </div>
</body>

</html>

您是否希望左/右列流动,然后居中为 500 像素,然后边距自动?

【讨论】:

  • 如果有空间,中心需要设置为500px,左右流体不超过500px。但是,如果中心没有空间为 500px,则需要将中心设置为可以达到的最大值,将左/右设置为 0。
  • 这里模仿了metoffice网站上预测表的行为-metoffice.gov.uk/weather/forecast/gcj2x8gt4#?date=2019-09-10
【解决方案2】:

当你发现诀窍时真的很简单..

minmax(0,500px) 尝试为最大 500px 分配尽可能多的空间,同时在视口太窄时允许其缩小。

<html>
<head>

<style>
.grid {
    display: grid;
    margin: 20px;
    grid-template-columns: 1fr minmax(0,500px) 1fr;
    align-items: stretch;
    justify-items: stretch;
}

.left {
    grid-column: 1;
    background-color: red;
    height: 200px;
}

.centre {
    grid-column: 2;
    background-color: green;

}

.right {
    grid-column: 3;
    background-color: blue;
}
</style>
</head>
<body>
    <div class="grid">
        <div class="left"></div>
        <div class="centre"></div>
        <div class="right"></div>
    </div>
</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2013-09-19
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    相关资源
    最近更新 更多