DEV Community

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

Posted on

3 1

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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay