在我页面的页脚之前定位div

时间:2017-07-06 17:14:36

标签: html css sass

附加页面布局以更好地解释我的要求。 Page layout

  1. 将文本放在页脚部分之前。
  2. 有时页脚可能不可见(可能需要滚动),在这种情况下将文本带到可见区域的底部。
  3. 我尝试了很多方法来实现这一目标。 任何解决此问题的指针都会有所帮助。

    谢谢, Santhosh

1 个答案:

答案 0 :(得分:3)

您可以使用flexbox实现此目的



body {
  margin: 0;
  
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.content {
  /* occupy all height */
  flex: 1 0 auto;
  /* nested flex container */
  display: flex;
  flex-direction: column;
}

.bottom-text {
  /* Move to the bottom */
  /* This works because this is flex item */
  margin-top: auto;
}

/* styles just for demo */
body {
  text-align: center;
}

header {
  background-color: tomato;
}

.content {
  background-color: lightsteelblue;
}

.bottom-text {
  background-color: moccasin;
}

footer {
  background-color: lime;
}

<header>Page header</header>
<section class="content">
  Page content
  <div class="bottom-text">Place a text just before footer</div>
</section>
<footer>Page footer</footer>
&#13;
&#13;
&#13;

要在bottom-text不可见时显示footer,我们将使用Javascript:

&#13;
&#13;
// Checks if element is visible on screen
function checkVisible(element) {
  var rect = element.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

var footer = document.querySelector("footer");
var bottomText = document.querySelector(".bottom-text");
var bottomTextFixedClassName = "bottom-text--fixed";

// Sets element position as fixed
// when footer is not visible on screen
function setFixedButtonText() {
  if (checkVisible(footer))
    bottomText.classList.remove(bottomTextFixedClassName);
  else
    bottomText.classList.add(bottomTextFixedClassName);
}

window.addEventListener("scroll", setFixedButtonText);

setFixedButtonText();
&#13;
body {
  margin: 0;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.content {
  /* occupy all height by flex-grow: 1 */
  /* Don't shrink using flex-shrink: 0 */
  /* Setting flex-basis to 1500px to emulate long content */
  /* Replace 1500px with auto in production code */
  flex: 1 0 1500px;
  /* nested flex container */
  display: flex;
  flex-direction: column;
}

.bottom-text {
  /* Move to the bottom */
  /* This works because this is flex item */
  margin-top: auto;
}

.bottom-text--fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
}

/* styles just for demo */
body {
  text-align: center;
}

header {
  background-color: tomato;
}

.content {
  background-color: lightsteelblue;
}

.bottom-text {
  background-color: moccasin;
}

footer {
  background-color: lime;
}
&#13;
<header>Page header</header>
<section class="content">
  Page content
  <div class="bottom-text">Place a text just before footer</div>
</section>
<footer>Page footer</footer>
&#13;
&#13;
&#13;

如果您需要IE推文,可以使用min-height: 100vh;更改为height: 100vh;。这是使用min-height进行flex的IE flex-direction: column;错误的解决方法。