Reputation: 1633
I've seen other answers, but none of them seem to work for me.
What I want: when I type the URL .../page.html#two
to go to #two
, but with a 50px offset from the top of the page.
note: ive added the big space
and <a>'s
because you can't type the url in jsfiddle. I want it to work with urls, as well as with links.
<body>
<section id="one">First section</section>
<section id="two">Second section</section>
<section id="three">Third section</section>
<div id="big_space"></div>
<a href="#one">one</a>
<a href="#two">two</a>
<a href="#three">three</a>
</body>
body
{
height: 2000px;
}
#big_space
{
height: 1000px;
}
section
{
height: 100px;
background-color: lightblue;
margin-bottom: 5px;
}
Here's a link to the JSfiddle: http://jsfiddle.net/hAmCL/
I have tried using the section:before
but it seems to give the wrong result (i've commented it out in jsfiddle)
Upvotes: 3
Views: 830
Reputation: 25944
This is impossible to do with pure CSS as you want it, though there are some semi-work arounds
This approach only works in certain instances, but the trick is to use margin-top:-50px; padding-top:50px;
. This makes the element appear in the same position except for the background will be 50px
higher and pushed up 50px
. Here's a demo of that approach
The second approach which I'd recommend more is one involving an added inner element. I decided to format each one like so <section id="one"><div class="reference" id="refOne"></div>First section</section>
. Then you can point to the refence in the link, i.e. <a href="#oneRef">one</a>
. Then all it takes it the following simple CSS
section {
... Your other lines ...
position:relative;
}
.reference {
position:absolute;
top:-50px;
}
Demo. This approach leaves all of the elements the way they were before in performance and looks but requires slight additional HTML markup
It'd be nice to be able to reference element's pseuo-elements like you tried to do but I understand how it could be non-syntactically correct to do so
Upvotes: 2