Technology Sharing

[Learning CSS2] Grid layout-keep the page footer at the bottom of the web page

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

How to keep the footer of the page at the bottom of the page when the middle content is not high enough to be stretched by the screen

1. First, look at the display effect on the picture above

2. Provide the source code

2.1、html part

  1. <body>
  2. <header>头部</header>
  3. <main>主区域</main>
  4. <footer>底部</footer>
  5. </body>

2.2, CSS part

  1. <style>
  2. html, body {
  3. margin: 0;
  4. padding: 0;
  5. width: 100%;
  6. height: 100%;
  7. }
  8. body {
  9. min-height: 100vh;
  10. display: grid;
  11. grid-template-rows: auto 1fr auto;
  12. }
  13. header {
  14. background: aquamarine;
  15. height: 40px;
  16. line-height: 40px;
  17. text-align: center;
  18. }
  19. footer {
  20. background: aquamarine;
  21. height: 50px;
  22. line-height: 50px;
  23. text-align: center;
  24. }
  25. main {
  26. margin: 0 auto;
  27. background: aqua;
  28. width: 80%;
  29. }
  30. </style>

3. All codes

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>gridbox布局</title>
  6. <style>
  7. html, body {
  8. margin: 0;
  9. padding: 0;
  10. width: 100%;
  11. height: 100%;
  12. }
  13. body {
  14. min-height: 100vh;
  15. display: grid;
  16. grid-template-rows: auto 1fr auto;
  17. }
  18. header {
  19. background: aquamarine;
  20. height: 40px;
  21. line-height: 40px;
  22. text-align: center;
  23. }
  24. footer {
  25. background: aquamarine;
  26. height: 50px;
  27. line-height: 50px;
  28. text-align: center;
  29. }
  30. main {
  31. margin: 0 auto;
  32. background: aqua;
  33. width: 80%;
  34. }
  35. </style>
  36. </head>
  37. <body>
  38. <header>头部</header>
  39. <main>主区域</main>
  40. <footer>底部</footer>
  41. </body>
  42. </html>

4. Principle

1. Retainedmin-height: 100vhThis method, but then we usegrid-template-rowsTo space out.

2. The trick of this method is to use special grid cellsfr 。 frIndicates "number of copies", using it requires the browser to calculate the available "number of copies" of the remaining space to be allocated to this column or row. In this case, it fills all the available space between the header and footer, which also solves the "defect" of the flexbox method, where the main area cannot be automatically filled.