This article was written in 2014. It might or it might not be outdated. And it could be that the layout breaks. If that’s the case please let me know.

Using the :target pseudo-selector for alternative layouts

I really like the :target pseudo-selector. It enables you to style the target of a so called skip-link. For instance when you link to a section in an article: you could highlight the header of that section. Or you can use it for toggling simple drop-down menus — the ones you see a lot on small screens. But you can also use it to create a completely different layout.

I used this technique on my Daily Rectangle site. As you can see (if your browser supports the vh unit) all the images are as high as the viewport. That’s nice, it enables me to enjoy one single image. But sometimes I want to see all the images on a grid. I could have created a PHP script that responded to a querystring. Or a small JavaScript. But instead I used the :target pseudo-selector. It’s very simple. First I did this:

<html lang="en" id="g">

Then I wrote this

#g:target body {
    columns: 15em;
    column-gap: 0;
}
/* 
and some other styles, you can look at the code: 
view-source:http://ghehehe.nl/the-daily-rectangle/ 
*/

Now if you add #g to the end of the URL, the layout changes. The site now looks like this.

Update

Of course you could add two more alternative layouts by giving both the head and the body element an id. The following CSS would do the trick:

head:target + body {
    /* alternative styles here */
}
body:target {
    /* alternative styles here */
}

Comments

    • Jason
    • #

    This is awesome stuff. When I go to the link you provide, you can’t view source when you right click. Am I missing something here?

    • Vasilis
    • #

    You’re right. The whole viewport is a link, and the menu that appears when you right click on a link is different from the normal context menu. You can view source in Firefox by pressing cmd+u (or ctrl+u on Windows). In Chrome it’s cmd+alt+u (or ctrl+alt+u, I think, on Windows). Other browsers probably have similar keyboard shortcuts.

    • Jason
    • #

    Thanks Vasilis