How to position an element under a fixed element

Problem description

Screen Shot 2020-07-16 at 8.11.21 pm.pngThe beneath element was blocked by the above element.

Analysis

What should you do then?

Change the margin-top of #content element. But to what value?

We can set a fixed value but it might not look good.

This is going to be a responsive webpage, so the height of #fix div is changing as you change the size of the window.

Solution

Use jQuery to change CSS with a dynamic value.

Screen Shot 2020-07-16 at 8.12.51 pm

You may need to add jQuery to your html code.

https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js

I used CodePen to do this demo, which only needs to change the setting.Screen Shot 2020-07-16 at 8.19.05 pm

After adding this code snippet, it works fine. But wait a sec.Screen Shot 2020-07-16 at 8.14.37 pm.png

After resizing the window, the content is blocked again. So we need to let window to be a trigger.

In the end, we need to add the following code to solve the problem. One changes the CSS when the page is loaded. The other changes when window resizes. Problem solved!

function dynamicHeight(){
     $('#content').css("margin-top", $('#fix').height());
}
$(document).ready(dynamicHeight);
$(window).resize(dynamicHeight);

If you have other solutions, feel free to contact me! I’m eager to learn!

Leave a comment