Beginner Help - Website Header loses it's top margin on scroll (and sticky)

Hi peeps,

Super new to CSS, basically I'm building a website, just using Wordpress and the header has a 20px margin all around it... However that header is sticky and when you scroll down, it loses it's top margin then joins to the top of the browser window.

I know how to add a margin to a header, but not a sticky header and I have looked online for it a lot but may be phrasing it wrong for google to pick up...

Anyone help? Let me know if you want images to assist.

TIA.

Posted May 13, 2022, 7:41 PM UTC

15
pookage•

So margin is the space between elements in-flow - once the position: sticky 'activates', it is quasi-removed from flow, and also has no elements to push against! It sounds like what you need is to say top: 20px so that when the header sticks, it sticks 20px from the top of the window.

Hope that makes sense!

2
TheOmegaProjectOP•

I understand what you're saying, however could you provide code for what you mean?

Literally all the CSS is at the minute is:

header {
	margin:20px;

}

1
pookage•

Not seeing your code it's hard to say! But, presumably, there is also:

.header {
    position: sticky;
    top: 0;
}

which makes the .header 'stick' as soon as it is 0px from the top of the viewport - you'd just need to change that to 20px so that it matches your margin:

.header {
    position: sticky;
    top: 20px;
}

UPDATE: here's a codepen with the above implementation in-action.

3
rbad8717•

instead of margin use top: 20px with position sticky

1
GrismundGames•

Maybe also position: fixed

Depending on what you want

0