Vekobr
Vekobr

Reputation: 31

Padding of container is ignored if anchor link is used

I have a container with overflow set to hidden, and it has a child which is higher than it. When I activate an anchor link to an object inside of it, container's padding-top is no longer used in calculating it's children's position.

How do I keep padding-top intact?

HTML:

<a href='#target'>Hit the top</a>
<div class='container'>
  <div class='tall'>Tall object</div>
  <div id='target'>Target</div>
</div>

CSS:

.container {
  padding: 40px;
  position: relative;
  overflow: hidden;
}
.tall {
  position: absolute;
  left: 200px;
  height: 2000px;
}

Demo: http://jsfiddle.net/aSDk5/2/

I've tested it (on Win7) in IE, FF, Chrome, Opera, Safari and the results are the same.

Upvotes: 3

Views: 996

Answers (2)

Xavier Vilanova
Xavier Vilanova

Reputation: 31

The scroll-margin-top property lets you define a top margin that the browser should use when snapping a scrolled element into place. For example using scroll-margin-top: 10vh; will jump to the anchored section but 10vh higher, exactly what you want.

Upvotes: 2

Hashem Qolami
Hashem Qolami

Reputation: 99484

Actually, there's nothing wrong with the padding. It's working.

The fact is when you hit the hyperlink, the content of container scrolls up to the top of the #target element.

And the above space (which you see that as padding-top visually), would be hidden because of overflow: hidden; CSS declaration.

You can check the padding by using overflow-y: scroll;.

.container {
    background-color: navy;
    padding: 40px;
    position: relative;
    overflow-y: scroll; /* Then, move the scroll-bar to check the padding */
}

JSFiddle Demo.

Upvotes: 2

Related Questions