Anchor positions and fixed header

Hi,

I’ve tried various solutions to try and make my anchor links position correctly but I don’t seem to be having much luck - is anyone aware of a simple solution that would work with my code, or is JavaScript the only way?

HTML
CSS

Website

Thanks!

Fraser

Here are some different techniques for the jump links. You should be able to just use padding and margin.

/* Example for the #product-gallery */
#product-gallery {
  width: 95%;
  margin: 0.6em auto;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  
  /* push it down */
  padding-top: 280px;
  
  /* pull it back up, account for top margin */
  margin-top: calc(-280px + 0.6em);
}

280px will land on the title, if you use 192px it will land on the #product-gallery div.

You will have to account for the change in header height at lower screen size if you want it to still land exactly the same place (media query with new px values to push/pull).

1 Like

This works great thanks! I’ve been playing around with it for half an hour but can’t figure out why it works! You you mind putting me out of my misery? :slight_smile:

This specific technique works when the elements do not have a background color(*). Try giving the #product-gallery element a red background color. You can now see how it is actually overlapping the above element.

The positive top padding will push the elements content down. Remember that it is not pushing the box down like when using margin, it’s pushing the actual content inside the box down (the box actually gets taller). The negative top margin will pull the element box up, the top padding part of the box is now overlapping the above element. Because the element is (by default) transparent you just can’t see the elements overlapping.

(*) If you use background-clip: content-box; you can’t see the overlap even with a background color, but the overlap is still there (the background color is clipped to the content box).

Visually it looks like the element hasn’t moved but if you check the elements offsetTop you can see it is not in the same location.

/* Without padding/margin */
document.getElementById('product-gallery').offsetTop
// 637

/* With padding/margin */
document.getElementById('product-gallery').offsetTop
// 357

Each technique has drawbacks depending on the circumstances as described on the demo page.

1 Like