I'm building a site with a fixed (not sticky) footer, kept behind the main page using z-index so that it only appears once the user scrolls to the bottom of the content. It's revealed by assigning a margin-bottom value to .pagewrap that is equal to the height of the footer.
Because the footer height is dynamic (changing with content and viewport width), I can't give the .pagewrap div a fixed margin-bottom value in px. Rather I need to fetch the current height of the footer element and apply that value to the margin-bottom of the main div, presumably using JS or jQuery (although a pure CSS solution would be a revelation, obviously).
Important: because the re-flow of text in the footer can cause the element's height to change, the solution to this problem needs to happen on resize AND on load.
I can find plenty of resources to match height using JS and jQuery, but these all apply the value to the height property of the targeted element. Here the value is needed for a different property.
JSFiddle: https://jsfiddle.net/sL0brv3j/
html:
<div >
<p>Scroll down</p>
</div>
<footer>
<p>Fixed position, behind the .pagewrap element</p>
</footer>
CSS:
body {
margin: 0;
}
.pagewrap {
background: #FFF;
width: 100%;
min-height: 100vh;
position: relative;
margin-bottom: 64px; /* should be set to = dynamic height of footer*/
z-index: 1;
}
footer {
background: #000;
width: 100%;
position: fixed;
bottom: 0;
left: 0;
height: auto; /* changeable value */
z-index: 0;
}
footer p {
color: #FFF;
}
CodePudding user response:
You can still use position: sticky on the footer to do this. If you want to do this pure CSS than it's very difficult to use position: fixed because it's outside the normal document flow so it has no idea about the elements inside the document flow, but position: sticky does.
Using bottom: 0 to put it at the bottom of the page and the z-index: 0 to have it underneath the main content.
It's just the reverse of a sticky header that is on top of the page.
footer {
background: #000;
width: 100%;
position: sticky;
display: inline-block;
bottom: 0;
left: 0;
height: auto;
z-index: 0;
}
Edited JSFiddle: https://jsfiddle.net/g7a8b51z/1/
CodePudding user response:
You don't need to listen for load or resize. You should be setting this where you are setting the footer.
You can set margin-bottom by doing
myElement.style.marginBottom = "" calculated value;
CodePudding user response:
You can do this by taking advantage of the height() property in jQuery. Create a variable with this value and then use it to apply the margin-bottom.
var h = $("div").height();
$("h1").css("margin-bottom", h);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Title</h1>
<div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</p>
</div>
