To add an explanation in short on :target
, it applies the style to the element that has an id which is same as location.hash
As this post intends to discuss the usage, pros & cons of :target
selector, an example to explain the same in-depth is not considered.
Say, there is a need for a slider or a tab, we usually apply the styles to all the slides or tabs. The slides or tabs that are not displayed, need not use the Layout
resources of the browser. There is absolutely no necessity to apply the style to the content that is not displayed to the user.
If the particular slide/tab CONTENTS(not the tab title) can be given an id and set the hash, all the styles that need to be applied can be written inside :target
.
Yes, the additional styles have to be written to accommodate the changes that happen due to scroll to the element that happens after setting the hash.
Pros - A relevant usage
It's good to consider this when the slide/tab is occupying most space on the screen because there's no scroll that will happen.
Here is a github link for a similar scenario that was tried. The only style that is applied to target in the example is to change the color. But as the relevant styles that are needed to an app are applied, this will be more beneficial.
Cons - Not a successful usage
The same was tried to apply the style only to the content that is displayed on a scrollable content. Here is github link
This is a failed scenario as there will be a flickering that happens on the screen as the user scrolls. Speaking about performance, to set a new id on scroll should not be expensive as it is done not on every scroll event but in batches. Also, for the browser engine to erase the styles that were applied to the sections which the user has already passed, it shouldn't cause a lot of Layout
cost.
<div class="block-custom">hello</div>
<div class="block-custom">hello2</div>
<div class="block-custom">hello3</div>
var num = 0;
window.location.hash = "#focused_0";
window.onscroll = function(x,y){
//- only chrome for now
var range = document.caretRangeFromPoint(0,10); // screen coordinates of upper-left corner of a scolled area (in this case screen itself)
var element = range.startContainer.parentElement; // this an upper onscreen element
console.log(range);
num++;
if(Number(window.location.hash.split("_")[1])+10 <num){
element.setAttribute("id", "focused_"+num);
//pushState can also be used
window.location.hash = "#focused_"+num;
}
}
.block-custom:target {
background-color:red;
}
If the flickering can be avoided, this can be a good benefit to the long scrolling content such as Facebook feed or similar.
Thanks for reading. Please help me with an update, if any alternatives are known without a flicker to apply style only to the content that is displayed on the screen(scrollable).
Top comments (0)