Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

html - How can I have a sticky footer with my CSS Grid layout?

I found this CodePen solution for a sticky footer in a CSS Grid layout, but it has two problems for me:

  1. It is kinda ugly with min-height: 100% and height: 100%
  2. It only works with two elements in the body (a div and a footer)

I need something that works with this HTML structure:

<body>
    <nav>Some navigation buttons</nav>
    <main>The content</main>
    <footer>Copyrights and stuff</footer>
</body>

I don't really want to pack the <nav> and the <main> into a <div>, and I would love to do this in pure CSS.

// Not required!
// This is just to demo functionality.

$("#add").on("click", function() {
  $("<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>").appendTo(".content");
});
html {
  height: 100%;
}

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

.content {
  padding: 20px;
}

.footer {
  grid-row-start: 2;
  grid-row-end: 3;
}

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font: 16px Sans-Serif;
}

h1 {
  margin: 0 0 20px 0;
}

p {
  margin: 0 0 20px 0;
}

.footer {
  background: #42A5F5;
  color: white;
  padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
  <h1>Sticky Footer with Grid</h1>
  <p><button id="add">Add Content</button></p>
</div>

<footer class="footer">
  Footer
</footer>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a CSS Grid solution, but it's far better using a class for the target.
Using grid-areas this will be very straight forward:

html, body {
    margin: 0;
    height: 100%;
}
body {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 1fr;
    grid-template-areas: "nav" "main" "footer";
    grid-template-rows: 100px 1fr 80px;
}
nav {
    background-color: #7E57C2;
    grid-area: nav;
}
main {
    background-color: #F8BBD0;
    grid-area: main;
}
footer {
    background-color: #7E57C2;
    grid-area: footer;
}
<body>
    <nav>Some navigation buttons</nav>
    <main>The content</main>
    <footer>Copyrights and stuff</footer>
</body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...