This behaviour isn't really supported, as explained in other answers. But if you really need this on a page, it's possible to add it using some JavaScript. Used-defined custom variables/properties in CSS need to start with --
, and I'll use the name --href-override
.
We'll listen for all mousedown
and touchstart
events on links in the document. These events are useful because they'll always occur before the click is registered. Each time we handle one of these events, we check if the associated link has a --href-override
property/variable defined in CSS. If so, we replace the HTML href
with the CSS --href-override
value, and the browser will automatically use that new value when handling the click event.
function overrideEventTargetHref(event) {
// if it's the beginning of a click on a link...
if (event.target.tagName === 'A') {
var link = event.target;
var override = getComputedStyle(link).getPropertyValue('--href-override').trim();
// if the link has an CSS href-override and it's different than the HTML href...
if (override && override != link.href) {
// replace the HTML href with the CSS href-override
link.href = override;
}
}
}
window.addEventListener('mousedown', overrideEventTargetHref, false);
window.addEventListener('touchstart', overrideEventTargetHref, false);
.override {
--href-override: https://stacksnippets.net/;
}
<a href="https://example.com">actually example.com</a>
<a href="https://example.com" class="override">secretly stacksnippets.net</a>
This also work properly for things like middle-clicking to open in a new tab.
This is quite a hack and you usually wouldn't want to do it. But if your situation requires it, you can.