如何将一个伸缩项目与容器顶部对齐,而其他伸缩项目则遵循对齐内容:居中?

时间:2019-06-07 18:17:32

标签: 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项目却位于剩余空间的中心?

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

2 个答案:

答案 0 :(得分:0)

.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>

您已经通过代码实现了,只是忘了对齐文本...如果我正确理解了您想要的内容

答案 1 :(得分:0)

如果方便的话,您可以将其他div包裹在父div中并赋予flex: 1

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

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