Подтвердить что ты не робот

Исправить нижний колонтитул внизу страницы

Хотя на большинстве страниц моего сайта достаточно контента, чтобы подтолкнуть нижний колонтитул к нижней части страницы для большинства людей. Я хотел бы знать, что он всегда фиксируется на дне, независимо от размера экрана с этого момента.

Я пробовал несколько способов, таких как bottom: 0x; position:absolute: и т.д. Никогда не работает очень хорошо, изредка выталкивает нижний колонтитул из контейнера, чтобы исправить его внизу, используя некоторые из этих примеров прямо там.

В комплект входят HTML и CSS для двух частей нижнего колонтитула (нижний колонтитул и панель авторских прав). В любом случае, они находятся внутри <section id="footer"> div.

Я удалил свои попытки заставить его придерживаться, чтобы люди могли взглянуть на него прямо сейчас и посмотреть, что должен изменить текущий код.

Live URL - http://www.mangdevelopment.co.uk/nakedradish

(Это веб-сайт-ресторанчик. Не беспокойтесь о слове "голый" ).

HTML

<section id="footer">
  <div class="container">
    <div class="row">
      <div class="span1">
        <div id="small-logo">
          <img src="img/small-logo.png" />
        </div>
      </div>
      <div class="span2">
        <div class="footer-list">
          <h6>OUR BOXES</h6>
          <ul>
            <a href="#">
              <li>Classic Box</li>
            </a>
            <a href="#">
              <li>Vegetarian Box</li>
            </a>
            <a href="#">
              <li>Family Box</li>
            </a>
            <a href="#">
              <li>Dinner Party Box</li>
            </a>
            <a href="#">
              <li>Gift Box</li>
            </a>
          </ul>
        </div>
      </div>
      <div class="span2">
        <div class="footer-list">
          <h6>OUR RECIPES</h6>
          <ul>
            <a href="#">
              <li>Last Weeks Feature</li>
            </a>
            <a href="#">
              <li>Next Weeks Feature</li>
            </a>
          </ul>
        </div>
      </div>
      <div class="span2">
        <div class="footer-list">
          <h6>ABOUT US</h6>
          <ul>
            <a href="#">
              <li>The Food</li>
            </a>
            <a href="#">
              <li>How We Sourcex</li>
            </a>
            <a href="#">
              <li>Sustainability</li>
            </a>
            <li><a href="about.html">About Us</a></li>
            <a href="#">
              <li>Contact Us</li>
            </a>
          </ul>
        </div>
      </div>
      <div class="span5">
        <div id="twitter">
          <img src="img/twitter-logo.png" alt="" title="" height="50" width="50" class="twitter-logo" />
          <div class="tweet-bg">
            <div class="tweets">
              <p>@chefallanp that just not on really</p>
            </div>
            <div id="follow-btn">
              <img src="img/follow-us.jpg" />
            </div>
          </div>
        </div>
        <div class="checkout-options">
          <h6>SECURE CHECKOUT</h6>
          <ul>
            <li><img src="img/solo-logo.png" /></li>
            <li><img src="img/switch-logo.png" /></li>
            <li><img src="img/maestro-logo.png" /></li>
            <li><img src="img/visa-logo.png" /></li>
            <a href="#">
              <li><img src="img/facebook-logo.png" /></li>
            </a>
            <a href="#">
              <li><img src="img/twitter-logo-flat.png" /></li>
            </a>
          </ul>
        </div>
      </div>
    </div>
  </div>
  <div id="copyright-bar">
  <div class="container">
    <div class="row">
      <div class="copyright-content">
        <div class="span4">
          <p>The Naked Radish Limited. 2013 All rights reserved.</p>
        </div>
        <div class="span4 offset4">
          <div class="copyright-list">
            <ul>
              <a href="terms.html">
                <li>Terms &amp; Conditions</li>
              </a>
              <a href="privacy.html">
                <li> - Privacy Policy</li>
              </a>
              <a href="#">
                <li> - Cookie Policy</li>
              </a>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

CSS

#footer {
    background-color: #F3F3F3;
    padding-top: 10px;
    padding-bottom: 0px;
}
4b9b3361

Ответ 1

Для footer:

#footer {
    position: fixed;
    height: 50px;
    background-color: red;
    bottom: 0px;
    left: 0px;
    right: 0px;
    margin-bottom: 0px;
}

Для вашего body:

body {
    margin-bottom:50px;
}

#footer {
  background-color: red;
  position: fixed;
  bottom: 0px;
  left: 0px;
  right: 0px;
  height: 50px;
  margin-bottom: 0px;
}

div {
  margin: 20px 20px;
}

body {
  margin-bottom: 50px;
}
<div>
  Although most pages on my site have enough content to push the footer to the bottom of the page for most people. I would like to know it always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom:
  0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright
  bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site have enough content to push the footer to the
  bottom of the page for most people. I would like to know it always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally
  pushes the footer out of it container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts
  at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site have enough content to push the footer to the bottom of the page for most people. I would like to know it always
  fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it container to fix to the bottom using
  some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and
  see what the current code is to amend. Although most pages on my site have enough content to push the footer to the bottom of the page for most people. I would like to know it always fixed to the bottom regardless of screen size from now on anyway.
  I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for
  the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site
  have enough content to push the footer to the bottom of the page for most people. I would like to know it always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc.
  Never seems to work very well, occasionally pushes the footer out of it container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside
  of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site have enough content to push the footer to the bottom of the page for most
  people. I would like to know it always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it's
  container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people
  can have a look at it right now and see what the current code is to amend.
</div>
<div id="footer">
  This is footer
</div>

Ответ 2

Подобно этому добавьте position:fixed; и bottom:0; под селектором #footer:

демонстрация

CSS

#footer {
    background-color: #F3F3F3;
    padding-top: 10px;
    padding-bottom: 0px;
    position:fixed;
    bottom:0;
    width:100%;
}

Ответ 3

Мы можем использовать FlexBox для Sticky Footer и Header без использования POSITIONS в CSS.

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

header {
  height: 50px;
  flex-shrink: 0;
  background-color: #037cf5;
}

footer {
  height: 50px;
  flex-shrink: 0;
  background-color: #134c7d;
}

main {
  flex: 1 0 auto;
}
<div class="container">
  <header>HEADER</header>
  <main class="content">

  </main>
  <footer>FOOTER</footer>
</div>

Ответ 4

Задавать

html, body {
    height: 100%;
}

Оберните все содержимое до нижнего колонтитула в div.

.wrapper {
    height:auto !important;
    min-height:100%;
}

Вы можете настроить минимальную высоту по своему усмотрению в зависимости от того, сколько нижнего колонтитула вы хотите отобразить в нижней части окна браузера. Если установлено значение 90%, перед прокруткой будет отображаться 10% нижнего колонтитула.

Ответ 5

Вот простое решение CSS, которое будет работать:

#fix-footer{
    position: fixed;
    left: 0px;
    bottom: 0px;
    height: 35px;
    width: 100%;
    background: #1abc9c;
}

Ответ 6

CSS

html {
    height:100%;
}
body {
    min-height:100%; position:relative;
}
.footer {
    background-color: rgb(200,200,200);
    height: 115px;
    position:absolute; bottom:0px;
}
.footer-ghost { height:115px; }

HTML

<div class="header">...</div>
<div class="content">...</div>
<div class="footer"></div>
<div class="footer-ghost"></div>

Ответ 8

Я нашел решение липкого нижнего колонтитула немного болезненным на чувствительных сайтах, учитывая, что высота вашего навигатора и нижнего колонтитула может отличаться в зависимости от устройства. Если вы только заботитесь о работе над современными браузерами, вы можете достичь своей цели, используя немного Javascript.

Если это ваш HTML:

<div class="nav">
</div>
<div class="wrapper">
</div>
<div class="footer">
</div>

Затем используйте этот JQuery на каждой странице:

$(function(){

  /* Sets the minimum height of the wrapper div to ensure the footer reaches the bottom */
  function setWrapperMinHeight() {
    $('.wrapper').css('minHeight', window.innerHeight - $('.nav').height() - $('.footer').height());
  }
  /* Make sure the main div gets resized on ready */
  setWrapperMinHeight();

  /* Make sure the wrapper div gets resized whenever the screen gets resized */
  window.onresize = function() {
    setWrapperMinHeight();
  }
});

Ответ 9

Элемент нижнего колонтитула по существу не будет привязан к нижней части окна просмотра, если вы не настроите его таким образом.
Так что, если у вас есть страница, на которой недостаточно контента, чтобы полностью оттолкнуть ее он окажется где-то посередине окна просмотра; выглядя очень неудобно и не уверен, что делать с собой, как в первый день учебы в средней школе.

Позиционирование элемента путем объявления правила fixed отлично, если вы всегда хотите, чтобы нижний колонтитул был видимым независимо от начальной высоты страницы, но затем не забудьте установить нижнее поле, чтобы оно не перекрывало последний бит контента на этом стр. Это становится сложным, если нижний колонтитул имеет динамическую высоту; что часто случается с чувствительными сайтами, поскольку оно в природе элементов для стека.

Аналогичная проблема вы найдете при позиционировании absolute. И хотя он принимает этот элемент из естественного потока документа, он по-прежнему не будет фиксировать его в нижней части экрана, если вы окажетесь со страницей, на которой нет никакого контента, чтобы ее реализовать.

Подумайте об этом:

  • Объявление значения высоты для тегов <body> и <html>
  • Объявление значения minimum-height для вложенного элемента оболочки, обычно это элемент, который обертывает все ваши дочерние элементы, содержащиеся в структуре тела (это не включает ваш элемент footer)

Пример кода пера

$("#addBodyContent").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(".flex-col:first-of-type");
});

$("#resetBodyContent").on("click", function() {
  $(".flex-col p").remove();
});

$("#addFooterContent").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("footer");
});

$("#resetFooterContent").on("click", function() {
  $("footer p").remove();
});
html, body {
    height: 91%;
}

.wrapper {
    width: 100%;
    left: 0;
    right: 0;
    box-sizing: border-box;
    padding: 10px;
    display: block;
    min-height: 100%;
}

footer {
    background: black;
    text-align: center;
    color: white;
    box-sizing: border-box;
    padding: 10px;
}

.flex {
    display: flex;
    height: 100%;
}

.flex-col {
    flex: 1 1;
    background: #ccc;
    margin: 0px 10px;
    box-sizing: border-box;
    padding: 20px;
}

.flex-btn-wrapper {
    display: flex;
    justify-content: center;
    flex-direction: row;
}

.btn {
    box-sizing: border-box;
    padding: 10px;
    transition: .7s;
    margin: 10px 10px;
    min-width: 200px;
}

.btn:hover {
    background: transparent;
    cursor: pointer;
}

.dark {
    background: black;
    color: white;
    border: 3px solid black;
}

.light {
    background: white;
    border: 3px solid white;
}

.light:hover {
    color: white;
}

.dark:hover {
    color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <div class="flex-btn-wrapper">
        <button id="addBodyContent" class="dark btn">Add Content</button>
        <button id="resetBodyContent" class="dark btn">Reset Content</button>
    </div>
    <div class="flex">
    <div class="flex-col">
      lorem ipsum dolor...
    </div>
    <div class="flex-col">
      lorem ipsum dolor...
    </div>
    </div>
    </div>
<footer>
    <div class="flex-btn-wrapper">
        <button id="addFooterContent" class="light btn">Add Content</button>
        <button id="resetFooterContent" class="light btn">Reset Content</button>
    </div>
    lorem ipsum dolor...
</footer>

Ответ 10

Нижний колонтитул расположен в нижней части страницы, но не зафиксирован.

CSS

html {
  height: 100%;
}

body {
  position: relative;
  margin: 0;
  min-height: 100%;  
  padding: 0;
}
#header {
  background: #595959;
  height: 90px;
}
#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 90px;
  background-color: #595959;
}

HTML

<html>
   <head></head>
   <body>        
      <div id="header"></div>
      <div id="content"></div>
      <div id="footer"></div>     
   </body>
</html>  

Ответ 11

Очень простой пример, который показывает, как исправить нижний колонтитул в нижней части макета приложения.

/* Styles go here */
html{ height: 100%;}
body{ min-height: 100%; background: #fff;}
.page-layout{ border: none; width: 100%; height: 100vh; }
.page-layout td{ vertical-align: top; }
.page-layout .header{ background: #aaa; }
.page-layout .main-content{ height: 100%; background: #f1f1f1; text-align: center; padding-top: 50px; }
.page-layout .main-content .container{ text-align: center; padding-top: 50px; }
.page-layout .footer{ background: #333; color: #fff; } 
<!DOCTYPE html>
<html>

  <head>
    <link data-require="[email protected]*" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <table class="page-layout">
      <tr>
        <td class="header">
          <div>
            This is the site header.
          </div>
        </td>
      </tr>
      <tr>
        <td class="main-content">
          <div>
            <h1>Fix footer always to the bottom</h1>
            <div>
              This is how you can simply fix the footer to the bottom.
            </div>
            <div>
              The footer will always stick to the bottom until the main-content doesn't grow till footer.
            </div>
            <div>
              Even if the content grows, the footer will start to move down naturally as like the normal behavior of page.
            </div>
          </div>
        </td>
      </tr>
      <tr>
        <td class="footer">
          <div>
            This is the site footer.
          </div>
        </td>
      </tr>
    </table>
  </body>

</html>

Ответ 12

Использование Flex и Bootstrap4 (если вы не используете Bootstrap4, вы можете достичь того же результата, используя свойства flex)

<body class="d-flex flex-column">
    <div>Header</div>
    <div>Main container</div>
    <div class="mt-auto">Footer</div>
</body>