Home >Web Front-end >CSS Tutorial >How to Prevent Fixed Position Elements from Overlapping the Footer?

How to Prevent Fixed Position Elements from Overlapping the Footer?

Barbara Streisand
Barbara StreisandOriginal
2024-11-14 16:24:01564browse

How to Prevent Fixed Position Elements from Overlapping the Footer?

Solving the Fixed Position Overlap at Footer Issue

When designing web pages with fixed position elements, it is common to encounter scenarios where these elements overlap with the page footer. To address this issue, a simple and effective jQuery solution can be implemented.

Identify the Elements

The html code provided defines the share box element (#social-float) and the CSS positions it at a fixed bottom left corner. The footer element (#footer) does not have a fixed height.

Handle Page Scrolling

To monitor the position of the share box relative to the footer, register a scroll event handler using jQuery's scroll() method.

$(document).scroll(function() {
    checkOffset();
});

Check Share Box Offset

Inside the checkOffset() function, calculate the vertical offset of the share box in relation to the footer. If the offset is less than 10px, meaning the share box has encroached upon the footer, update its position to absolute.

function checkOffset() {
    if($('#social-float').offset().top + $('#social-float').height() 
                                           >= $('#footer').offset().top - 10)
        $('#social-float').css('position', 'absolute');
}

Restore Fixed Position

When the user scrolls back up the page, restore the fixed position of the share box by setting its position back to fixed.

if($(document).scrollTop() + window.innerHeight < $('#footer').offset().top)
        $('#social-float').css('position', 'fixed');

Ensure Sibling Elements

The parent of the share box (#social-float) should be a sibling of the footer (#footer). This allows for proper positioning relative to the footer.

<div class="social-float-parent">
    <div>

By implementing this jQuery solution, the share box will remain fixed in place but will automatically stop before overlapping the footer, ensuring a clean and visually appealing design.

The above is the detailed content of How to Prevent Fixed Position Elements from Overlapping the Footer?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn