Is it possible to assign the margin-bottom property of one element to be equal to the dynamic height of a sibling element?

I am in the process of creating a website that features a fixed (non-sticky) footer placed behind the main content using the z-index property. The footer only becomes visible when the user scrolls to the bottom of the page, achieved by assigning a margin-bottom value to .pagewrap equal to the height of the footer.

Since the height of the footer is not static and can change with varying content and viewport width, it is impossible to set a fixed margin-bottom value for the .pagewrap div in pixels. Instead, I need to determine the current height of the footer element dynamically and apply that value as the margin-bottom on the main div, most likely utilizing JS or jQuery (though a CSS-only solution would be ideal).

It's worth noting that since text re-flow inside the footer can alter its height, any solution to this issue must take place both on resize and on initial load.

While there are resources available for matching heights using JS and jQuery, they typically apply the value to the height property of the targeted element. In this case, the value is required for a different property.

JSFiddle: https://jsfiddle.net/sL0brv3j/

HTML:

<div class="pagewrap">
  <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;
}

Answer №1

If you're looking to keep your footer in place using CSS, consider utilizing the position: sticky property. Unlike position: fixed, which can cause issues with elements inside the normal document flow, position: sticky keeps things nice and tidy.

Simply set bottom: 0 to anchor the footer at the bottom of the page, and use z-index: 0 to ensure it remains below the main content - just like a sticky header at the top of the page!

footer {
  background: #000;
  width: 100%;
  position: sticky;
  display: inline-block;
  bottom: 0;
  left: 0;
  height: auto;
  z-index: 0;
}

Check out the updated JSFiddle link here: https://jsfiddle.net/g7a8b51z/1/

Answer №2

Listening for the load or resize events is not necessary in this case. The best practice is to set this property when you are setting up the footer.

To set the margin-bottom, you can achieve it by using the following code:

myElement.style.marginBottom = "" + calculated value;

Answer №3

To achieve this, you can utilize the height() property in jQuery. Simply create a variable holding this value and then use it to set 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>

JSFiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create a self-referencing <div> in HTML?

After extensive research, I turn to seeking advice and guidance on Stack Exchange. I have a seemingly straightforward goal in mind. I want to create a <div> id/class that will automatically generate a link to itself using scripting of some sort. Be ...

Employ a pivot table to visually display an array of object data

I am attempting to utilize a pivot table to organize the data provided below: $.pivotUtilities.tipsData=[ {status:"open",year:2014,value:100.00}, {status:"open",year:2015,value:200.00}, {status:"open",year:2016,va ...

What is the best way to apply overlays to customize a specific part of a single character while also accommodating dynamic width adjustments?

Query Is it feasible to style a specific portion of a single character? Interpretation You cannot apply CSS attributes to parts of characters. However, if you wish to style only a particular section of a character, there is currently no standardized met ...

The function Amplify.configure does not exist

Currently attempting to utilize AWS Amplify with S3 Storage, following the steps outlined in this tutorial for manual setup. I have created a file named amplify-test.js, and here is its content: // import Amplify from 'aws-amplify'; var Amplify ...

Is it possible to extract the value displayed on a Typography component in Material UI and store it in a state variable?

I'm currently facing an issue with mapping a data array onto material-ui Typography elements. Here's the code snippet: { array.map((item, id)=> <Typography key={id} value={item.name} />) } While this code successfully displays the val ...

"The Ajax POST request to MyUrl returned a 404 error, indicating that the resource

While working on my Grails code, I encountered an error when the Ajax function received a response from the controller action. The parameters are being passed successfully by the Ajax function, and the controller function is executed. However, upon return ...

Encountered a SyntaxError on JSON Web Tokens Node JS Server: Unexpected token } found in JSON at position 24

Me, along with others, have encountered this issue: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following a tutorial on JSON Web Tokens (TUTORIAL LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s ...

Responding to a tweet with the help of twit and Node.js

Utilizing the Twit Node.js API has presented me with a challenge. I am attempting to reply to a tweet that contains a specific keyword. My goal is for my response tweet to appear nested underneath the original tweet, much like how replies function on socia ...

Retrieving date from timestamp in a node.js environment

Can someone help me figure out how to display my timestamp as the date in the front end? I've tried multiple methods without success. Here is the code snippet: formulaire.addEventListener('submit', posteValidation); /** * Function to add a ...

Utilizing the GET method within a form

I'm currently working on testing a form to ensure that my input values are being submitted correctly. At this point, I haven't set up any server script yet. However, I was hoping that upon clicking submit, I would be able to see my values appende ...

I'm looking for some good .NET MVC frameworks that can help create dynamic AJAX applications

I am interested in developing applications with a dynamic user interface that utilizes ajax technology. Some key features I am looking for include: Automatic saving of user input in forms, even if the data is incomplete Realtime validation of form fields ...

There seems to be an issue with FastAPI not sending back cookies to the React

Why isn't FastAPI sending the cookie to my React frontend app? Take a look at my code snippet: @router.post("/login") def user_login(response: Response, username :str = Form(), password :str = Form(), db: Session = Depends(get_db)): use ...

Identify alterations in an input field after selecting a value from a dropdown menu

Is there a way to detect changes in the input field when selecting a value from a drop-down menu, similar to the setup shown in the image below? html: <input type="text" class="AgeChangeInput" id="range"/> js:(not working) <script> $(docume ...

Obtaining the initial value from an Observable in Angular 8+

Initially, I have a page form with preset values and buttons for navigating to the next or previous items. Upon initialization in ngOnInit, an observable provides me with a list of 3 items as the starting value - sometimes it may even contain 4 items. Ho ...

Exploring the Canvas with Full Element Panning, Minimap Included

Currently, I am working on incorporating a mini map onto my canvas that mirrors what is displayed on the main canvas. The main canvas includes zoom and pan functions. I have created a rectangular shape for the minimap to display the content of the canvas. ...

Insert the AJAX loader graphic

Hello! I may not be a master of jQuery, but I've been tinkering with some source code and stumbled upon an ajax script. I'm feeling a bit lost on how or where to insert an ajax loader image in this snippet: $.post(webroot+'quickLookUp.php&a ...

Collapsed Bootstrap navigation bar on mobile devices

Hello everyone, I am currently using the latest version of Bootstrap for my website. However, I have encountered an issue where the navigation collapses on mobile view. Could anyone provide assistance? Website: Below is a snippet of my HTML code: <he ...

When it comes to printing, the @Media CSS rule

I have a specific structure on my HTML page: <html> <head></head> <body> <nav> .... navigation menu </nav> <div> <div></div> <div class="to-print"> <h2>Th ...

What is the process for accessing my PayPal Sandbox account?

I'm having trouble logging into my SandBox Account since they updated the menu. The old steps mentioned in this post Can't login to paypal sandbox no longer seem to work. Could someone please provide me with detailed, step-by-step instructions o ...

The CSS cubic-bezier fails to smoothly transition back to its initial position

I created an animation that works perfectly when hovering over the target elements, however, it doesn't smoothly transition back to its original position when the cursor moves outside of the target element. Instead, it snaps back abruptly and unattrac ...