



























By default, only the html and the body element (plus its descendants) of a web page are actually rendered. All information within the head element might be parsed and used by the browser, but most of the time it doesn’t get displayed. If you want to, you can use CSS to display these ‘hidden’ elements.
I used to do this on my old site, but then I renewed it, so I just thought I’d document this little ‘trick’.
Look at it this way… Browsers apply the following CSS rule to every document:
head, title, link, meta, style, script {
display: none;
}
As with all browser-default CSS, this can be overridden by declaring the following style rules:
head, title, link[href][rel], meta, style, script {
display: block;
}
This one CSS rule is all it takes to force the browser to display the elements.
Of course, there are a few other things you might want to do — adding inner content to the link and meta elements, for example.
link[href][rel]::after {
content: attr(rel);
text-transform: capitalize;
}
meta[charset]::after {
content: 'Charset: ' attr(charset);
}
meta[name][content]::after {
content: attr(name) ': ' attr(content);
text-transform: capitalize;
}
Similarly, we can style script elements with a src attribute specified:
script[src]::after {
content: 'External file: ' attr(src);
}
To target only inline script blocks, we could use the CSS3 negation pseudo-class:
script:not([src]) {
background: lime;
}
Firefox is the only browser that seems to automatically create clickable links out of visible link elements with a href attribute. This is pretty useful — the link element sort of becomes a hyperlink pointing to the resource it was referring to. To clone this behavior in other browsers as well, we can use JavaScript:
<script>
function() {
var head = document.head || document.getElementsByTagName('head')[0];
var links = head.getElementsByTagName('link');
var length = links.length;
while (length--) {
links[length].onclick = function() {
location.href = this.href;
};
}
}());
</script>
This script simply loops through all link elements inside <head> and adds onclick handlers to them, causing the referenced document to be opened upon clicking.
You can see this technique in action on the demo page. Believe it or not, this is a document with an empty <body>!
Sadly, this fails in Internet Explorer (I’ve tested versions 6, 7, 8, 9 and 10). Nonetheless, I think this is a pretty interesting trick.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。