gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:51:13 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com