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! πŸš€ πŸš€ πŸš€

Problem description

The beneath element was blocked by the above element.

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


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.


Use jQuery to change CSS with a dynamic value.

You may need to add jQuery to your html code.

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());
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: Check that too if you're interested!

Top comments (0)