Reputation: 1684
I would like add a padding-top
to my div
when I click on the link to the anchor :
<a href="#myAnchor">Go to my anchor</a>
...
<div id="myAnchor"> ... </div>
The issues is that I want add the padding just when my link redirect me to the anchor. I don't want add padding-top
in the html, I just don't want that my div is on the top of my page, I need a padding or margin top.
Thank you.
Upvotes: 4
Views: 10629
Reputation: 1126
I think, best way is
#myanchor:before {
display: block;
content: " ";
height: 50px;
margin: -50px 0 0;
}
Source and demo: http://nicolasgallagher.com/jump-links-and-viewport-positioning/demo/#method-B
If you choose ugly way (that is margin-top: -50px;
and padding-top: 50px;
) layer will remain on the bottom and you need to use z-index
.
Upvotes: 1
Reputation: 827
I think what you're trying to do is cause the link, when clicked, to scroll the browser window to a few pixels above the target, instead of having the target flush with the top of the browser window.
You can check this article for several solutions http://css-tricks.com/hash-tag-links-padding/
The simplest solution, generally would appear to be to add in your css:
#myanchor{
margin-top: -200px;
padding-top: 200px;
}
Replacing 200px with whatever value you feel is appropriate. You may also wish to use a class to apply this, as I asume you won't just wish to use it on the one item :)
Upvotes: 11
Reputation: 8851
There's only one way I know of: javascript. If you're already using jquery:
$('a[href="#myAncre"]').click(function(){
$("#myAncre").css("padding-top", "20px");
});
Although if you don't use jquery already, it might be worth to do it with simple javascript.
Upvotes: 1