为什么此网格中的第三个元素与页面底部对齐?

问题描述 投票:0回答:3

CodenPen link

<body>
  <container>
    <nav></nav>
    <main>
      <section></section>
      <section></section>
      <section></section>
      <section></section>
      ...
    </main>
    <footer></footer>
  </container>
</body>
container {
    min-height: 100%;
    display: grid;
    grid-template-rows: auto 1fr auto;
    grid-template-columns: 100%;
}

main {
    margin: 0 auto;
    position: relative;

    min-height: 100%;
    display: grid;
    grid-template-rows: auto 1fr auto;
    grid-template-columns: 100%;
}

下面的图像在'section'元素上附加了一个border-style: dashed。在main组中只有一两个部分,一切都很好:

“”“”

但是具有三个或更多元素,它们将转到屏幕底部:

“”“”

当屏幕上的项目足够填满一个视图时,它似乎又可以工作了:

“”

html css grid
3个回答
1
投票

使用伸缩框来构造页面而不是网格。它更灵活,响应速度更快,这就是引导程序使用并推荐它的原因。也没有<container></container>元素。

body {
 background-color: red;
 margin: 0;
 padding: 0;
} 

nav {
 background-color: yellow;
 width: 100%;    
}

main {
 background-color: pink;
 flex-grow: 1;
 width: 100%;
}


footer {
 background-color: blue;
 width: 100%;
}

.container {
    background-color: cyan;
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 100vh;
}

main {
    display: flex;
    flex-direction: column;
    align-items: center;
}
<body>
  <div class="container">
    <nav>nav bar</nav>
    <main>
      <section>section 1</section>
      <section>section 2</section>
      <section>section 3</section>
      <section>section 4</section>
    </main>
    <footer>footer</footer>
  </div>
</body>

1
投票

不是最后一个元素与页面底部对齐,而是您定义的网格使之成为网格的第一个“行”获得其内容的高度,第二个“行”设置为1fr(1fr代表1分数,占可用空间的1分数),第三个“行”再次设置为auto。从第四个元素开始,不存在“行”规则,因此默认情况下将其设置为自动。

让我们考虑您的第三张图片。因为您的代码的css规则为“ grid-template-rows:auto 1fr auto;”第一个和第三个(以及第三个标签之后的每个元素)将具有自动高度,该高度由标签的内容设置。现在,由于1fr规则,第二个元素将始终占用剩余的可用空间。这就是为什么您可以通过示例看到并非最后一个元素“粘在”底部,而是第二个元素总是占用了剩余的可用空间。

希望有帮助=]。对我好一点,这是我的第一个答案,将感谢所有反馈。


0
投票

不清楚您要问什么。您希望页面顶部的前两个部分彼此相邻,然后是什么?

取决于您要如何显示网格,请更改网格模板行的css。尽管我会按照建议亲自使用flexbox

container {
    min-height: 100%;
    display: grid;
    grid-template-rows: auto 1fr auto;
    grid-template-columns: 100%;
}

main {
    margin: 0 10px;
    position: relative;

    min-height: 100%; 
    display: grid;
    grid-template-rows: 25px auto    ;
    grid-template-columns: 100%; 
}
<body>
  <container>
    <nav style="background-Color:lightBlue;height:10px"></nav>
    <main style="background-Color:pink;height:200px">
      <section style="background-Color:purple;height:25px;margin:0 40px"></section>
      <section style="background-Color:green;height:25px;margin:0 40px"></section>
      <section style="background-Color:purple;height:25px;margin:0 40px"></section>
      <section style="background-Color:green;height:25px;margin:0 40px"></section>
      
    </main>
    <footer style="background-color:blue;height:10px"></footer>
  </container>
</body>
© www.soinside.com 2019 - 2024. All rights reserved.