Place the footer element at the bottom of the page in relation to its preceding sibling

Having an element positioned at the bottom of a page can sometimes be tricky, especially when there are elements that slide up and down based on user interactions. On pages with enough content to push the element down naturally, everything works fine.

The challenge arises when a user triggers an action that causes a sibling element to slide up, subsequently making our target element slide up as well until it reaches the next visible element.

My goal is to have the element stay at the bottom of the screen if there isn't much content, but adjust its position relative to the sibling above when there is enough visible content. I hope this explanation makes sense!

This is the footer

<footer>
<div class='container'>
    <span>
        <h2><b>Contact</b></h2>
        <b>Telephone:</b> +45 000000<br/>
        <b>Email:</b> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9d4d8d7d8dedcd4dcd7cdf9fce1f8f4e9f5fc97dad6d4">[email protected]</a>
    </span>
    <span>
        <h2><b>FAQ</b></h2>
        Some text<br/>
        Some other text
    </span>
    <span>
        <h2><b>Some header</b></h2>
        <?php 
        if(date('Y') == '2019'){
           echo 'example &copy; 2019';
        } else {
           echo 'example &copy; 2019-'.date('Y');
        }
        ?>
    </span>
</div>
</footer>

--- CSS ---

.container{
width: 80%;
margin: auto;
overflow: hidden;
}
footer
{
color: #FFF;    
background: #d99741;
padding: 20px;
margin-top: 20px;
}

footer span
{
float: left;
text-align: center;
width: 30%;
padding: 10px;
}

footer h2
{
position: relative;
margin-top: -10px;
}

--- Html for the sibling above ---

echo "
    <section id='displayevents'>
        <div class='container'>
            <div class='eventCountry'>
                <p>".$trim."</p>
            </div>
            <div class='framework''>
                <div class='imageFrames'>
                    <img src='".$image[0]."' />
                    <h3>".$club[0]."</h3>
                </div>
                <div class='imageFrames'>
                    <img src='".$image[1]."' />
                    <h3>".$club[1]."</h3>
                </div>
                <div class='imageFrames'>
                    <img src='".$image[2]."' />
                    <h3>".$club[2]."</h3>
                </div>
            </div>
        </div>
    </section>
";

--- javascript that slides up and down ---

<script type='text/javascript'>
$(document).ready(function(){
//Hides all .framework and then shows the first
var getamount = $('.framework');
for(var x=0;x<=getamount.length;x++){
    $(getamount[x]).hide();
}
$('.framework').first().show(); 
//Creates a function that will handle the display of each .framework. Only 
one at a time.
function openSection(element){
    var display = element.css('display');
    var find = $('.framework');
    var getAttr;
    if(display != 'none'){
        $(element).slideUp(500);
    } else{
        for(var x=0;x<=find.length;x++){
            getAttr = $(find[x]).css('display');
            if(getAttr != 'none'){
                $(find[x]).slideUp(500);
            }
        }
        $(element).slideDown(500);
    }
}
//Create clickfunction to .eventCountry and call function to hide/show 
content
$('.eventCountry').click(function(){
    openSection($(this).next());
});
});
</script>

Answer №1

To solve this issue, you can add padding to the bottom of the body tag and utilize position:absolute;bottom:0 to position the footer within the newly created space. If you already know the amount of padding required, you can specify it in CSS; otherwise, a small snippet of JavaScript will do the trick.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
footer {
background-color:red;
position: absolute;
bottom: 0;
}
body {
/*padding-bottom: 90px; use this if the footer height is known*/
position: relative;
min-height: 100vh;
box-sizing:border-box;
}

/*for demo*/
body {
margin: 0;
}
h1 {
margin: 0;
}
  </style>
</head>
<body id="body">
<h1>Qui officia deserunt mollit anim id est laborum.
Facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.
Itaque earum rerum hic tenetur a sapiente delectus. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae.
At vero eorunt mollitia. Esse cillum dolore eu fugiat nulla pariatur. Itaque earum rerum hic tenetur a sapiente delectus. Ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</h1>
<button>Slide Togle</button>
<h2 id="slide">Qui officia deserunt mollit anim id est laborum.
Facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.
Itaque earum rerum hic tenetur a sapiente delectus. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae.
At vero eorunt mollitia. Esse cillum dolore eu fugiat nulla pariatur. Itaque earum rerum hic tenetur a sapiente delectus. Ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</h1>

<footer id="footer">At vero eos et accusamus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. Nihil molestiae consequatur, vel illum qui dolorem eum.
Sed ut perspiciatis unde omnis iste natus error sit voluptatem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque earum rerum hic tenetur a sapiente delectus. Quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.
Accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat.
</footer>

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<script>
var h = document.getElementById('footer').scrollHeight;
document.getElementById('body').style.paddingBottom  = h+'px';

$('button').click(function(){
$('#slide').slideToggle("slow");
});
</script>
</body>
</html>

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

Display a series of numbers in a stylish Bootstrap button with uniform dimensions

I am trying to find a way to show the number of days in a specific month within a bootstrap button. However, the code I have been using does not evenly distribute the buttons in terms of height and width. I would like the display to look similar to the sc ...

Ways to activate a button action with jQuery even when it is disabled and clicked

Thank you for the responses. To clarify my goal, I want the form button to submit all select field responses for processing through php on the next page. If a user clicks the submit button before selecting an option in each field, it should display "whoa d ...

Step-by-Step Guide: Ensuring Only One Menu Item is Active at a Time in AngularJS

How can I make only one menu item active at a time? Currently, when I click on a specific menu item, all menu items become active. I need to remove the previous active menu item and set the currently clicked menu item as active. Can someone assist me with ...

Only displaying sub items upon clicking the parent item in VueJS

I'm in the process of designing a navigation sidebar with main items and corresponding sub-items. I want the sub-item to be visible only when its parent item is clicked, and when a sub-item is clicked, I aim for it to stand out with a different color. ...

Using the setTimeout function is essential for successfully extracting values in a Jquery each loop. Without

I created a loop to adjust the padding on an image tag placed atop another image. Strangely, it was only capturing the first one or two values until I added a setTimeout function, which seemed to fix the issue. Below is the jQuery code: $(document).ready ...

Mastering the art of implementing dynamic template variables in TinyMCE

After exploring the 'full' example and conducting research on the Wiki and moxie forums, I have yet to find a solution. I am attempting to implement what the wiki states is possible, but encountered an issue when replacing the 'staffid' ...

How to center text both horizontally and vertically in HTML

I am struggling with centering a background image along with a 1-line text vertically and horizontally inside a div. Although I have successfully centered the image, the text remains misaligned. I attempted using vertical-align: middle without success. Be ...

Transforming a traditional HTML/CSS/JS website into a cutting-edge React application using Tailwind CSS styling

I have a unique website template complete with HTML, CSS, and all necessary assets. Now, I am looking to develop a React JS application using this template. Firstly, I am wondering: Since I typically use Tailwind CSS for my other projects, would it be mo ...

How can I set the width of a container dynamically using the Next JS Image component?

I have a situation where I am trying to set the height of an image within a container div to be equal to 100% of the container's height, while allowing the width of the container to adjust based on the image's aspect ratio. When using a standard ...

A guide on using JavaScript to obtain the original calculation for a specific equation once a checkbox has been unchecked

I am facing a scenario where I have two input fields. One should display the value of Quantity, and the other should display the value of Price. The first input, which is for quantity and of type number, has the disabled attribute. However, upon checking a ...

Look up and input information into the dropdown selection list

Is there a way to search for and input text in a select drop-down menu? Generally, we are unable to write inside the select drop-down menu. Is there a method that allows me to type inside this drop-down menu and as I am typing, if a similar word appears, I ...

Creating a switch statement that evaluates the id of $(this) element as a case

I have a menu bar with blocks inside a div. I am looking to create a jQuery script that changes the class of surrounding blocks in the menu when hovering over a specific one. My idea is to use a switch statement that checks the ID of $(this) and then modif ...

How can I transform an ajax request into unobtrusive javascript?

Here is the ajax code I have: $('select#books_order').on('change', function() { $.ajax({ url: "/books/#{@book.id}", type: 'GET', dataType: 'script', data: { sort: $('#books_order option:s ...

Is it possible to access the span element through its parent div?

Is there a way to access a specific <span> using its parent <div> as demonstrated below: <div> <!--parent div--> <div> <span>...</span> <span>...</span> </div> <div> <span> ...

Creating a fixed footer within a div that is absolutely positioned using CSS

I am looking to implement a sticky footer within an absolutely positioned div element. My initial approach was to position the footer div absolutely as well - within an additional relatively positioned "page" div (which would contain the main content of t ...

Expanding a feature that modifies the CSS properties of every input element

Creating a text tracking (letter-spacing) demonstration where range sliders are used to update CSS properties. I'm looking to improve the functionality so that the labels also update dynamically, without repeating output2.textContent = this.value;. An ...

Leveraging ng-click and ng-hide/show directives within ng-repeat in Angular

I have a simple Single Page Website built with Angular. I utilized ng-repeat to generate content on the main page, where each item is an image. I am looking to create an alternate view for each image to display more details. I have implemented this feature ...

Can text be formatted differently based on its length and whether it wraps onto multiple lines?

Looking to display book titles on a webpage with varying lengths. Some are short enough to fit in one line, while others are longer and wrap onto two lines. Is it possible to apply different styles (such as color or line-height) for these two cases using ...

Enhancing the styling of checkboxes using CSS and Javascript

My Javascript skills have been put to the test with a simple code snippet that customizes checkboxes by hiding them and using background images in CSS to display checks and unchecks. It's a neat trick, but I'm wondering if it's HTML/CSS comp ...

When a div element overlaps with other elements, everything below it continues to be displayed on top of

I have a DIV that is displaying correctly. However, content that is supposed to be below the DIV is showing on top of it. I need help fixing this issue. I have tried the solutions provided in other similar questions but none of them have resolved my proble ...