Hyperlinks are cool. They’re what make the web, The Web. You know what’s really cool? Linking to specific sections of a web page.
We’ve done that forever with the URL hash/fragment linking to an element with an id
attribute. Now there is a more powerful way! URL Fragment Text Directives is the new hotness in text linking. The spec’s been around for a while, and the idea even longer, but baseline browser support is relatively new with Firefox landing only this year. This is a public service announcement because I think text fragment links are way underutilised.
Before I discuss that let’s review the old and busted:
Heading IDs
My blog and many like it automatically add id
attributes to heading elements. The heading above gets the ID heading-ids
for example.
This ID is often generated by a “slugify” function. The archaic practice of converting text into a limited subset of visible ASCII characters. It involves replacing whitespace with hyphens, stripping diacritic marks like they’re fashion accessories, and if you’re fancy, converting “&” to “-and-“. This works fine, if you’re an English-speaking caveman like myself.
The rest of the world uses Unicode.
Seriously, both IDs and URLs allow Unicode. Just use UTF-8? You can even break the rules and use whitespace in an ID, browsers don’t care! Use emojis! Please @ me on social media if I’m missing an issue that “slugify” still solves.
Anyway; new thing:
Text Fragments
IDs require consideration from both developer and author to provide adequate anchors for linking. That’s too much to ask of most websites. Forget that! Text fragments hand power to the user.
With text fragments anybody can link to #:~:text=Heading IDs
even if the heading has no ID. I can link to any text like: “Hyperlinks are cool” — sorry if you clicked that and had to scroll back down…
That’s really cool!
Chromium browsers have a “Copy Link to Highlight” option in the context menu when you right-click highlighted text. That’s cool too.
The whole colon-tilde-colon directive is less cool — did we run out of single characters? — but I’ll take function over form.
CSS has a target text pseudo-element that can be styled:
::target-text {
background-color: pink;
}
Like ::selection
only certain CSS properties can be used. I generally leave the browser defaults to handle such styles. Opt for visual accessibility over on-brand highlighting.
The downside to using text fragments is that links can break if text is edited. That is also true for IDs if they’re edited. Either way, you just end up at the top of the page, rather than scrolling to the specific content.
What do you think, cool?