Как заставить нижний колонтитул оставаться внизу веб-страницы? - PullRequest
269 голосов
/ 03 сентября 2008

У меня есть простой макет с двумя столбцами и нижним колонтитулом, который очищает правый и левый div в моей разметке. Моя проблема в том, что я не могу заставить нижний колонтитул оставаться внизу страницы во всех браузерах. Это работает, если контент сдвигает нижний колонтитул, но это не всегда так.

Обновление:

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

Ответы [ 24 ]

0 голосов
/ 29 августа 2016

Старая ветка, которую я знаю, но если вы ищете адаптивное решение, это дополнение jQuery поможет:

$(window).on('resize',sticky);
$(document).bind("ready", function() {
   sticky();
});

function sticky() {
   var fh = $("footer").outerHeight();
   $("#push").css({'height': fh});
   $("#wrapper").css({'margin-bottom': -fh});
}

Полное руководство можно найти здесь: https://pixeldesigns.co.uk/blog/responsive-jquery-sticky-footer/

0 голосов
/ 21 сентября 2018

Поскольку решение Grid еще не представлено, оно здесь, с двумя объявлениями для родительского элемента , если мы примем height: 100% и margin: 0 как должное:

html, body {height: 100%}

body {
  display: grid; /* generates a block-level grid */
  align-content: space-between; /* places an even amount of space between each grid item, with no space at the far ends */
  margin: 0;
}

.content {
  background: lightgreen;
  /* demo / for default snippet window */
  height: 1em;
  animation: height 2.5s linear alternate infinite;
}

footer {background: lightblue}

@keyframes height {to {height: 250px}}
<div class="content">Content</div>
<footer>Footer</footer>

Элементы равномерно распределены внутри контейнера выравнивания по поперечная ось. Интервал между каждой парой соседних предметов является так же. Первый элемент находится на одном уровне с основным краем, а последний Элемент находится на одном уровне с основным краем.

0 голосов
/ 25 декабря 2018

      div.fixed {
        position: fixed;
        bottom: 0;
        right: 0;
        width: 100%;
        border: 3px solid #73AD21;
      }
  <body style="height:1500px">

    <h2>position: fixed;</h2>

    <p>An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled:</p>

    <div class="fixed">
      This div element has position: fixed;
    </div>

  </body>
0 голосов
/ 16 января 2016

jQuery CROSS BROWSER CUSTOM PLUGIN - $ .footerBottom ()

Или используйте jQuery, как я, и установите высоту нижнего колонтитула на auto или fix, как вам будет угодно, все равно будет работать. этот плагин использует селекторы jQuery, поэтому, чтобы он работал, вам нужно включить библиотеку jQuery в ваш файл.

Вот как вы запускаете плагин. Импортируйте jQuery, скопируйте код этого пользовательского плагина jQuery и импортируйте его после импорта jQuery! Это очень просто и просто, но важно.

Когда вы делаете это, все, что вам нужно сделать, это запустить этот код:

$.footerBottom({target:"footer"}); //as html5 tag <footer>.
// You can change it to your preferred "div" with for example class "footer" 
// by setting target to {target:"div.footer"}

нет необходимости помещать его в событие готовности документа. Это будет хорошо работать, как есть. Он будет пересчитывать положение нижнего колонтитула при загрузке страницы и изменении размера окна.

Вот код плагина, который вы не должны понимать. Просто знайте, как это реализовать. Это делает работу за вас. Однако, если вы хотите узнать, как это работает, просто посмотрите код. Я оставил для вас комментарии.

//import jQuery library before this script

// Import jQuery library before this script

// Our custom jQuery Plugin
(function($) {
  $.footerBottom = function(options) { // Or use "$.fn.footerBottom" or "$.footerBottom" to call it globally directly from $.footerBottom();
    var defaults = {
      target: "footer",
      container: "html",
      innercontainer: "body",
      css: {
        footer: {
          position: "absolute",
          left: 0,
          bottom: 0,
        },

        html: {
          position: "relative",
          minHeight: "100%"
        }
      }
    };

    options = $.extend(defaults, options);

    // JUST SET SOME CSS DEFINED IN THE DEFAULTS SETTINGS ABOVE
    $(options.target).css({
      "position": options.css.footer.position,
      "left": options.css.footer.left,
      "bottom": options.css.footer.bottom,
    });

    $(options.container).css({
      "position": options.css.html.position,
      "min-height": options.css.html.minHeight,
    });

    function logic() {
      var footerOuterHeight = $(options.target).outerHeight(); // Get outer footer height
      $(options.innercontainer).css('padding-bottom', footerOuterHeight + "px"); // Set padding equal to footer height on body element
      $(options.target).css('height', footerOuterHeight + "!important"); // Set outerHeight of footer element to ... footer
      console.log("jQ custom plugin footerBottom runs"); // Display text in console so ou can check that it works in your browser. Delete it if you like.
    };

    // DEFINE WHEN TO RUN FUNCTION
    $(window).on('load resize', function() { // Run on page loaded and on window resized
      logic();
    });

    // RETURN OBJECT FOR CHAINING IF NEEDED - IF NOT DELETE
    // return this.each(function() {
    //   this.checked = true;
    // });
    // return this;
  };
})(jQuery); // End of plugin


// USE EXAMPLE
$.footerBottom(); // Run our plugin with all default settings for HTML5
/* Set your footer CSS to what ever you like it will work anyway */
footer {
  box-sizing: border-box;
  height: auto;
  width: 100%;
  padding: 30px 0;
  background-color: black;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- The structure doesn't matter much, you will always have html and body tag, so just make sure to point to your footer as needed if you use html5, as it should just do nothing run plugin with no settings it will work by default with the <footer> html5 tag -->
<body>
  <div class="content">
  <header>
    <nav>
      <ul>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
      </ul>
    </nav>
  </header>

  <section>
      <p></p>
      <p>Lorem ipsum...</p>
    </section>
  </div>
  <footer>
    <p>Copyright 2009 Your name</p>
    <p>Copyright 2009 Your name</p>
    <p>Copyright 2009 Your name</p>
  </footer>
...