来源:Rosettacode Quine for HTML/CSS(找到HTML / CSS部分)。
以下代码,当保存为html文件时,在浏览器中呈现为源代码。
<!DOCTYPE html>
<html>
<head>
<title>HTML/CSS Quine</title>
<style type="text/css">
* { font: 10pt monospace; }
head, style { display: block; }
style { white-space: pre; }
style:before {
content:
"\3C""!DOCTYPE html\3E"
"\A\3Chtml\3E\A"
"\3Chead\3E\A"
"\9\3Ctitle\3E""HTML/CSS Quine""\3C/title\3E\A"
"\9\3Cstyle type=\22text/css\22\3E";
}
style:after {
content:
"\3C/style\3E\A"
"\3C/head\3E\A"
"\3C""body\3E\3C/body\3E\A"
"\3C/html\3E";
}
</style>
</head>
<body></body>
</html>
我不知道这是如何运作的,引用页面根本没有解释。
答案 0 :(得分:2)
This is a "cheaty" quine in the sense that it essentially introspects its own source code, and styles it to make it visible rather than the default invisible. The CSS rules are best explained one-by-one:
* { font: 10pt monospace; }
This is just for aesthetics, since code tends to be marked up in monospace.
head, style { display: block; }
Normally, content in <head>
and <style>
is invisible. I don't know if styling these elements like this is strictly standards-conformant, but in general I think the spec gives a lot of freedom to document authors when it comes to changing the display
of elements to something else. For instance, you can style inline or block elements as tables, table-rows and table-cells without problem. We want to make these elements visible in order to make the CSS source code render.
style { white-space: pre; }
This is again for aesthetics: this makes whitespace inside the script element render verbatim, rather than applying the usual coalescing rule for HTML elements where runs of whitespace get replaced by a single space.
style:before {
content:
"\3C""!DOCTYPE html\3E"
"\A\3Chtml\3E\A"
"\3Chead\3E\A"
"\9\3Ctitle\3E""HTML/CSS Quine""\3C/title\3E\A"
"\9\3Cstyle type=\22text/css\22\3E";
}
style:after {
content:
"\3C/style\3E\A"
"\3C/head\3E\A"
"\3C""body\3E\3C/body\3E\A"
"\3C/html\3E";
}
These rules insert the required HTML code before and after the <style>
element, since we can't render these via CSS only. In CSS, a backslash followed by runs of hexadecimal digits forms an escape sequence—\3C
and \3E
are <
and >
respectively, \A
denotes newline and \9
denotes tab. Multiple strings given in a row (with optional whitespace between them) are concatenated together.