css - 如何将一个 flex 元素对齐到容器顶部,而其他元素遵循 justify-content : center?

标签 css flexbox css-grid

<分区>

我有一个包含两项的网格,第一项是 flex 容器。

html:

  <div class = "grid">
     <div class="flex">
      <h1>Anchor To Top?</h1>
      <div>item</div>
      <div>item</div>
      <div>item</div>
      <div>item</div>
      <div>item</div>
   </div>

   <div class = "other-grid-item">
   Other grid item
   </div>
  </div>

CSS:

.grid{
  display: grid;
  grid-template-columns: 1fr 2fr;
  height: 100vh;
}
.flex{
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: blue;
}

您可以在此处查看示例:https://jsfiddle.net/tc9kdhb1/3/ .有没有一种方法可以让 h1 保持在 flex 容器的顶部,而其他 flex 元素则位于剩余空间的中心?

我尝试在 h1 上使用 position: absoltute,但该元素不再适合容器。在此先感谢您的帮助。

最佳答案

.grid{
  display: grid;
  grid-template-columns: 1fr 2fr;
  height: 100vh;
}
.flex{
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: blue;
}
.item{
text-align:center;
}
<div class = "grid">
     <div class="flex">
      <h1>Anchor To Top?</h1>
      
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      
   </div>

   <div class = "other-grid-item">
   Other grid item
   </div>
  </div>

你已经用你的代码实现了这一点,你只是忘记了对齐文本......如果我理解正确的话

关于css - 如何将一个 flex 元素对齐到容器顶部,而其他元素遵循 justify-content : center?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56499456/

上一篇:javascript - 在不使用 html 的情况下为文本着色

下一篇:javascript - 从 ASP 标签控件中读取文本(由 jquery 填充)

相关文章:

html - 如何缩放 iframe 的内容?

html - devicePixelRatio 和 dppx 有什么不同?

html - 在小屏幕上更改 div 的布局

html - 无法垂直对齐文本 - angularJS + bootstrap + flexbox

css - 在 flex 元素上使用边距

html - CSS网格: row not taking full height space available

javascript - Bootstrap - 如何在两列中拆分和对齐下拉列表?

html - Flexbox 不随内容扩展

html - html列表项(li)可以设置显示: grid?吗

具有全宽行的 CSS 网格模板