CSS 如何在 <code> 块中保留换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1011641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to preserve line breaks in <code> block?
提问by Matthew Murdoch
I have some code samples which I want to publish in an HTML document. I'm wrapping them with <code>
, tags but I'd like them to be styled such that line breaks are preserved. I can do this by also enclosing them with <pre>
tags, but I'd prefer to use CSS.
我有一些代码示例要发布在 HTML 文档中。我用<code>
, 标签包装它们,但我希望它们的样式可以保留换行符。我也可以通过用<pre>
标签将它们括起来来做到这一点,但我更喜欢使用 CSS。
I've tried the following in IE7 (which according to this referenceshould work), but with no joy (line breaks are stripped):
我在 IE7 中尝试了以下操作(根据这个参考应该可以工作),但没有任何乐趣(换行符被剥离):
code {
white-space: pre;
}
Is this possible?
这可能吗?
采纳答案by SpliFF
Check your doctype is valid and on the first line. Maybe it's slipping into quirks mode?
检查您的文档类型是否有效并在第一行。也许它正在滑入怪癖模式?
回答by Paolo Bergantino
Are you sure you're not doing something wrong? This code works for me on IE7:
你确定你没有做错什么?这段代码在 IE7 上对我有用:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
code { white-space: pre; }
</style>
</head>
<body>
<code>
function() {
alert('yay');
}
</code>
</body>
</html>
回答by Ian Oxley
You could try using the CSS suggested here: http://ajaxian.com/archives/wrapping-the-pre-tag
您可以尝试使用此处建议的 CSS:http: //ajaxian.com/archives/wrapping-the-pre-tag