DEV Community

Cover image for How to position an element under a fixed element
Geek Lady
Geek Lady

Posted on

How to position an element under a fixed element

Here's my first article on Dev.to! šŸš€ šŸš€ šŸš€

Problem description

The beneath element was blocked by the above element.

You may have met this problem when you have a fixed nav bar.

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.

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.

After adding this code snippet, it works fine. But wait a sec. If you click HTML/CSS/JS button in codepen or drag your browser window, the result is not right again.

Why? Because the window size has changed. So we need to let the size change 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);
Enter fullscreen mode Exit fullscreen mode

About jQuery functions, it's a little different from JS. I firstly used 'dynamicHeight()', and failed.

If you have other solutions, feel free to contact me! Iā€™m eager to learn! This is firstly published at my blog: https://geekladysite.wordpress.com. Check that too if you're interested!

Top comments (0)