css - 如何将 CSS 网格子元素对齐到网格顶部

标签 css layout css-grid

我正在尝试对网格子项进行分层。我有一个侧边栏,它叠加在一个全高的英雄图像上,该图像跨越整个网格宽度,以便侧边栏覆盖它。我似乎无法弄清楚如何将包含图像的网格子项与视口(viewport)顶部对齐。

https://codepen.io/coreybruyere/pen/jQqZdp

body {
  margin: 0 0 0 0;
}

#container {
  display: grid;
  grid-template-columns: 25% 75%;
  grid-template-rows: 100%;
}

.section.hero {
  padding:0;

  img {
    display: block;
    height: 100%;
    width: 100%;
    object-fit: cover;
  }
}

#left {
  background-color: aquamarine;
  position: sticky;
  top: 0;
  height: 100vh;
  box-sizing: border-box;
  z-index: 10;
}

// This should be aligned to the top
#right {
  background-color: beige;
  grid-column: span 2;
}

最佳答案

如果您希望侧边栏占 25%,图像占另外 75%,请使用 grid

body {
  margin: 0 0 0 0;
}

#container {
  display: grid;
  grid-template-columns: 25% 75%;
}

.section.hero {
  padding: 0;
}

img {
  height: 100vh;
  width: 100%;
  object-fit: cover;
}

#left {
  background-color: aquamarine;
  height: 100vh;
}

#right {
  background-color: beige;
  height: 100vh;
}
<div id="container">
  <div id="left" class="section">
    <p>This should not scroll</p>
  </div>
  <div id="right" class="section hero">
    <img src="http://placekitten.com/g/2000/2000" alt="">
  </div>
</div>

如果你想让图片全宽,那么你不需要使用grid

body {
  margin: 0;
}

img {
  height: 100vh;
  width: 100%;
  object-fit: cover;
}

#left {
  background-color: aquamarine;
  height: 100vh;
  width: 25%;
  position: absolute;
  z-index: 1;
}

#right {
  background-color: beige;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
}
<div id="container">
  <div id="left" class="section">
    <p>This should not scroll</p>
  </div>
  <div id="right" class="section hero">
    <img src="http://placekitten.com/g/2000/2000" alt="">
  </div>
</div>

关于css - 如何将 CSS 网格子元素对齐到网格顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53216043/

相关文章:

delphi - 如何在 TForm 的 TOleContainer 中正确使用 Word(布局方面)?

css - 仅将 css 网格应用于第一行

java - JPanel 布局问题

jquery - 隐藏/显示特定表格行

jquery - 如何使 inputCheckBoxGroup 在 Play Framework 中垂直堆叠

javascript - jQuery 全日历 : Change the color of every saturday except last saturday in the month

swift - 如何防止 Spacer 使 VStack 贪婪地增长超出必要范围?

html - CSS Grid 自动调整和 min-max 留下空白

html - 仅换行的一部分(全高列旁边)

IE9 上的 CSS : divs inside td elements in a table will display vertically