如何在CSS网格中垂直居中放置一行?

mik*_*ana 2 css vertical-alignment css3 css-grid

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

在此处输入图片说明 注意:

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

(随机句子,因为markdown做奇怪的事情)

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


.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%;
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经试过了,但是它真的想做多行而不是一行上的多列。

我可以在CSS网格中做单行,垂直居中的布局吗?如果是这样,怎么办?

mik*_*ana 25

这是一个工作示例。它与其他答案一样有效,但使用不同的 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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


Mic*_*l_B 5

要将所有项目强制排成一行,请将它们设置为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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)