【问题标题】:How do I do a single row, vertically centered, layout in CSS grid?如何在 CSS 网格中进行单行垂直居中布局?
【发布时间】:2018-11-20 22:09:48
【问题描述】:

我正在尝试使用 CSS 网格进行单行垂直居中布局。这是一个粗略的草图:

注意:

  • 我只有一行项目
  • 这些项目(可能)将具有相同的宽度
  • 我不知道我有多少项目(所以我不想说 '200px' 八十次)
  • 项目高度不同,但需要垂直居中

HTML:

<div class="wrapper">
    <div class="box a">A</div>
    <div class="box b">B</div>
    <div class="box c">C</div>
</div>

CSS:

.wrapper {
    display: grid;
    grid-gap: 10px;
    grid-auto-columns: 200px;
    background-color: #fff;
    color: #444;
    .box {
        background-color: #444;
        color: #fff;
        border-radius: 5px;
        padding: 20px;
        font-size: 150%;
    }
}

我试过这个,但它真的想在一行上做多行而不是多列。

我可以在 CSS 网格中进行单行垂直居中布局吗?如果有,怎么做?

【问题讨论】:

    标签: css vertical-alignment css-grid


    【解决方案1】:

    这是一个工作示例。它与其他答案一样有效,但使用不同的 CSS 来避免显式设置网格行。点击下方的“运行”:

    • grid-auto-flow: column; 使项目跨列流动,即进入单行
    • align-self: center; 垂直居中

    .wrapper {
        display: grid;
        grid-auto-flow: column;  
    }
    
    .box {
        align-self: center;
    }
    
    /* Additional styles below */
    
    .wrapper {
      grid-gap: 10px;
      background-color: #fff;
      color: #444;
    }
    
    .box {
        background-color: #444;
        color: #fff;
        border-radius: 5px;
        padding: 20px;
        font-size: 150%;
    }
    
    body {
      margin: 40px;
    }
      
    .box.a {
         height: 200px;
    }
        
    .box.b {
      height: 20px;
    }
    
    .box.c {
      height: 120px;
    }
    <div class="wrapper">
      <div class="box a">A</div>
      <div class="box b">B</div>
      <div class="box c">C</div>
      <div class="box c">D</div>
    </div>

    【讨论】:

      【解决方案2】:

      要将所有项目强制放在一行中,请将它们设置为grid-row: 1

      要使项目居中,请将容器设置为align-items: center,或将每个项目设置为align-self: center。 (align-self 默认继承 align-items 值)。

      .wrapper {
        display: grid;
        align-items: center;     /* new */
      }
      
      .box {
        grid-row: 1;             /* new */
      }
      
      .box.a { height: 200px; }
      .box.b { height: 20px;  }
      .box.c { height: 120px; }
      .box.d { height: 50px;  }
      
      
      /* non-essential decorative styles */
      
      .wrapper {
        grid-gap: 10px;
        background-color: #fff;
        color: #444;
      }
      .box {
        background-color: #444;
        color: #fff;
        border-radius: 5px;
        padding: 20px;
        font-size: 150%;
      }
      body {
        margin: 40px;
      }
      <div class="wrapper">
        <div class="box a">A</div>
        <div class="box b">B</div>
        <div class="box c">C</div>
        <div class="box d">D</div>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-19
        • 2018-07-22
        • 2019-03-03
        • 1970-01-01
        • 1970-01-01
        • 2018-07-06
        • 2019-06-02
        • 2023-03-28
        相关资源
        最近更新 更多