How can I make an element stick at the bottom of another element using the top position

I have two stacking elements of varying heights within a scrolling container.

When the lower element extends below the bottom of the container, I want to display a part of it affixed to the bottom.

To achieve this, I applied position: sticky to position the element at calc(100%-2em) from the top, which theoretically should place it 2em above the bottom of the element.

However, when the position is set to sticky, it behaves contrary to my intention as it only sticks when scrolled to its intended position.

#container {
  width: 500px; height: 100px; background: black; margin: 2em auto; color: white; overflow-y: scroll;
}

#bottom {
  background: red;
  position: sticky;
  top: calc(100% - 2em);
}
<div id="container">
  <div id="top">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin justo sem, egestas eget massa sit amet, volutpat facilisis orci. Aenean tristique pulvinar viverra. Integer dui nunc, sodales id mi vitae, dignissim volutpat nisl. Sed ac tristique ipsum. Nulla quis metus id massa sagittis interdum. Maecenas egestas imperdiet maximus. Etiam vehicula metus sit amet tellus posuere feugiat. Mauris non nisl felis. Suspendisse eu elementum justo. Nulla a semper nisi. Aliquam posuere pulvinar bibendum. Cras eget sem eget nunc rhoncus maximus. In hac habitasse platea dictumst. </p>
    <p>Ut suscipit, augue sed eleifend cursus, quam urna tempus turpis, et consequat neque nisl vel magna. Morbi et fringilla est, eget efficitur nulla. Cras nec finibus sapien. Aenean vitae mauris auctor, ornare sapien et, consectetur eros. Nullam maximus eu augue sed blandit. Aliquam ligula sem, pellentesque quis eleifend id, venenatis sit amet nibh. Curabitur aliquam dolor lacus, non sollicitudin nulla gravida nec. Sed diam odio, sodales sed pretium lobortis, accumsan et nulla. Proin nec posuere nibh. Sed ullamcorper neque eu eros sodales tempus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris et purus purus. Duis in pulvinar tortor. Morbi fringilla elit eget augue aliquet vulputate vel ut felis. Morbi in est suscipit ex consequat lobortis dapibus id augue. Nulla sagittis, erat vitae tincidunt faucibus, nulla nulla fermentum elit, vitae viverra mi augue sit amet tellus. </p>
  </div>
  <div id="bottom"><h3>bottom</h3>
  <p>Phasellus malesuada, ipsum vel ullamcorper elementum, eros leo eleifend nisi, at scelerisque erat lorem id lorem. Mauris vestibulum massa ac bibendum pretium. Cras non tempus nibh, vel finibus tortor. Nulla posuere justo erat, id elementum lectus porttitor in. Nullam leo nibh, dictum ut mauris eget, tristique malesuada nunc. Phasellus vestibulum elit nec ex mollis, sed ultricies est sagittis. Nullam faucibus urna non tortor efficitur, at aliquet sapien dapibus. Aliquam condimentum dapibus neque, imperdiet egestas massa convallis tincidunt. Nam ultrices urna in sem posuere placerat. Praesent sem erat, dignissim et magna sed, luctus cursus lacus. Mauris sed nisi sed est facilisis euismod a quis mauris. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
    </div>
</div>

Answer №1

For those seeking a solution, consider utilizing jQuery. Below is an example that demonstrates displaying the #bottom div when the user scrolls past the #top div.

Key modifications made include:

  1. Introducing a new div, #placeholder, with a height identical to the hidden #bottom div's height, which serves as a reference point for determining when to reveal the #bottom div
  2. Incorporating the necessary jQuery function

Here's an explanation of the jQuery script:

  • jQuery(window).scroll triggers the code each time the user scrolls
  • $(window).scrollTop() captures the current scroll position, while $( window ).height() establishes the 'detector line' at the window's bottom. The subtraction of 32 accounts for the 2em height (equaling 32px) of the #bottom div.
  • The variable x stores the scroll position indicating when the #bottom div should appear
x = $("#placeholder").offset().top
jQuery(window).scroll(function(){
if ($(window).scrollTop() + $( window ).height() - 32 > x) {
  x = $("#bottom").offset().top
  $("#bottom").css({"position": "initial"});
  $("#placeholder").css({"display":"none"});
} else {
  $("#bottom").css({"position": "fixed"});
  $("#placeholder").css({"display":"block"});
}
});
#bottom {
  background: red;
  position: fixed;
  top: calc(100% - 2em);
}

#placeholder {
  height: calc(2em);
  width: 100%;
  display: block;
}

Additional Code and Elements:

123

Lorem ipsum dolor sit amet...

Ut suscipit, augue sed eleifend cursus...

bottom

Phasellus malesuada, ipsum vel ullamcorper elementum...

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

The custom font in my Next.js project is functioning perfectly in the development environment, but when I try to build it locally, the font doesn

Incorporating the Amazon Ember font as a custom font in my application has been a bit of a challenge. I followed the necessary steps of setting up a font.ts file in the lib folder and exporting the font correctly, as guided by various blog posts. Initially ...

When using iOS, inserting an iFrame with a source URL (SRC) on a webpage will automatically open the URL

Currently facing a peculiar issue within a Cordova app, specifically on iOS. The scenario is: I have an HTML page with existing content. At a later stage, I fetch additional HTML from a remote source and inject it into the original HTML page. However, whe ...

Swapping out bullet points for delicious food icons in an unordered list on an HTML page

I am working with the following code snippet: <div id="instructions"> <h3>Get it done</h3> <ol> <li>In a blender add the eggs, chocolate powder, butter, flour, sugar and milk.</li> <li>Then whisk ...

How come the max-width property is not functioning properly on tables in Internet Explorer 7?

Is there a reason why the "max-width" property does not seem to have any effect on tables in Internet Explorer 7? While it works fine on other elements, when applied to a table, the max-width rule is completely ignored. <!DOCTYPE html PUBLIC "-//W3C//D ...

What are the steps to view my HTML webpage on a smartphone?

Recently, I successfully created an HTML webpage with CSS and JS that looks and functions perfectly on my PC. However, when attempting to access it on my phone, I encountered some issues. Despite transferring all the necessary files to my phone, only the ...

Automating Indesign with HTML5 and JavaScript through IDML files

I am currently working on automating IDML files. My goal is to display an IDML template in an HTML5 editor. Within the sample.idml file, I have a basic TextFrame containing the text "Hello World." After unzipping the file and navigating to the stories fol ...

Having issues with handling button click events in jQuery

I'm currently working with jQuery to show a div when a button is clicked, but for some reason, it's not functioning as expected... HTML: <input type="button" id="addmoresg" value="Add More" name="button"> <div id="addsg" style="display ...

When implementing dynatable with Meteor, the outcomes may vary between the demonstration in a fiddle and the actual application

Here is the fiddle I created for this question: https://jsfiddle.net/ereday/82wzwem8/2/ In the fiddle, you'll notice that the table header has a green background. Now, let me share the code snippet from my meteor project: simple-todos.html <head ...

Having issues with Drupal's lightframe and lightbox functionalities not functioning properly

I recently came across a Drupal 6 project that I have little knowledge about. My goal is to incorporate an Iframe into a lightbox, which seems simple but I'm encountering some obstacles. Despite researching online and attempting to implement the code ...

What is the best way to adjust the size of an image within a div element using HTML?

I've created a Carousel with 5 images to display. However, I'm having an issue where only the image is showing up, and I want the text and button to appear below it. Here's how the nature image is currently displaying: What I want is for th ...

Find and make adjustments to the primary HTML document in your Magento online shop

Trying to enhance the top banner of my Magento website tamween.biz by adding a shadow effect PNG picture. Successfully managed this on my local server using firebug and creating a new class in the coding area with all selector properties modified in the bo ...

Retrieve webpage content using an ajax request in JavaScript

I'm working on an HTML page with an Ajax call to load table content. <html> .... <script sec:haspermission="VIEW_NOTE" th:inline='javascript'> require(['app/agent/viewGlobalAgent'], function (){ ...

Struggling to determine the expense upon button activation - data remains stagnant

My coding project involves a basic ordering system where users can input an integer, click on an update button, and see the total cost displayed below. Despite my efforts, I've encountered issues with two different methods: Using plain JavaScript for ...

When you open the link in a new tab, the form submission does not occur

I am currently working on a form that includes a JavaScript submit function. Within the form, there are 3 anchor tags that I want to use to set different values to a hidden parameter when submitted based on the link clicked. Although the form submission w ...

Modify the input value when using the get_search_form() function in Wordpress

After experimenting with the latest get_search_form() function in WordPress, I've encountered an issue where I can't figure out how to remove the text label from the search submit button. Does anyone have any suggestions or solutions for this pr ...

I am on a quest to locate the xpath for a day that is divided by the HTML line break element,

In my HTML structure, I have the following code snippet: <td class="FormLabel" valign="top"> <span class="DataLabel">Consists of:</span> </td> <td class="FormData"> <span class="BodyText"> Sunday<br> M ...

Updating the color scheme of the selected nav-item and showcasing the corresponding page in relation to the navbar selection

I have been trying various methods, but I am unable to change the background color of an active navigation item and also display the corresponding page. Important: The jQuery code below successfully changes the background color of the navbar list item. Ho ...

How come the margin-bottom is displaying as the margin-top?

When I attempt to add margin-bottom on a div inside its parent, it seems to display as the parent's margin-top. Why is that? HTML: <div id="wrapper"> <div id="content"> <div id="box"></div> </div> </d ...

Is there a way to add a dynamic animation of steam rising from a coffee cup to my SVG icon design?

I'm a budding graphic designer eager to master the art of SVG animated icons and coding. Recently, I created an SVG file of a beautiful cup of coffee using Illustrator and now I want to make the steam rise realistically through animation. However, des ...

Generate an image, PDF, or screenshot of a webpage with the click of a button

I've been searching for a solution that would enable users to click a button and save an image or PDF of the current page. The content on the page is dynamic and dependent on user input, resulting in sequences displayed in various colors. I'm loo ...