Search code examples
cssruby-on-railsturbolinks

CSS :target pseudo-class is not applied after click on link


I'm using Rails5 (with turbolinks)

HTML markup:

<a href="/post/slug#target1">Target1</a>
<a href="/post/slug#target2">Target1</a>
...
<p id="target1">Content1</p>
<p id="target2">Content2</p>

CSS:

p:target {
  background-color: red;
}

Problem is that :target pseudo-class is applied only after page refresh. Style is not applied when clicking on links.

I'm almost sure, that this behaviour caused by turbolinks. How to fix this?


Solution

  • I've found the solution, while writing this question.

    To make things work well, we need to add data attribute to such links, as follows:

    <a href="/post/slug#target2" data-turbolinks="false">Target1</a>
    

    This attribute disables turbolinks on per-link basis.

    More details here: Disabling Turbolinks on Specific Links