Question

I'm about to make a one-page site with tabs for navigation between several divs, that are display:none by default. I want to use the :target CSS3 selector to make them visible on link click. And I also want the first div to be visible on page load. For this I use

document.location.href = "#div1";   

The markup:

<div id="nav">
<a href="#div1">div1</a>|
<a href="#div2">div2</a>|
<a href="#div3">div3</a>
</div>
<div id="div1"><h1>div1</h1><p>div1</p></div>
<div id="div2"><h1>div2</h1> <p>div2</p></div>
<div id="div3"><h1>div3</h1><p>div3</p></div>

CSS:

#div1, #div2, #div3
{
position: relative;
display: none;
background: #ff7;
width: 400px;
height: 400px;
}

#div1:target, #div2:target, #div3:target
{
display: block;
}

The full sample working in Chrome http://jsfiddle.net/zy9Pt/

Everything works fine in Chrome, but, as always, there are some issues in FF (the first div is still not visible on page load) and in IE (the :target selector doesn't work, and the first div is not visible on page load as well). How can I fix that? Why doesn't the script work in FF and is it a bug in IE with the :target selector?

StoR: run the following in IE9 or Chrome:

    <script>
document.location.hash = "#div1";   
</script>
<style>
#div1, #div2, #div3
{
position: relative;
display: none;
background: #ff7;
    width: 400px;
    height: 400px;
}

#div1:target, #div2:target, #div3:target
{
display: block;
}
</style>
<div id="nav">
<a href="#div1">div1</a>|
<a href="#div2">div2</a>|
<a href="#div3">div3</a>
</div>
<div class="clear"></div>
<div id="div1"><h1>div1</h1><p>div1</p></div>
<div id="div2"><h1>div2</h1> <p>div2</p></div>
<div id="div3"><h1>div3</h1><p>div3</p></div>

Then try to run the same in Firefox. #div1 won't be visible on the page load. If to refresh - it will appear.

Was it helpful?

Solution 2

Such a dumb question 7 years ago! You NEVER need :target for navigation. Just use JS frameworks/libraries.

OTHER TIPS

Make sure that your browsers supports the :target selector using the following url css3test.com. Scroll down to the Selectors section and find whether :target is supported in your browser or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top