34

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.

I've tried the following in IE7 (which according to this reference should work), but with no joy (line breaks are stripped):

code {
 white-space: pre;
}

Is this possible?

Alexander Abakumov
14.7k16 gold badges99 silver badges135 bronze badges
asked Jun 18, 2009 at 9:12
2
  • If the line breaks are meaningful, then they are "content," not "style," and should be coded with &lt;pre&gt; tags. Would it change the meaning of your page if a user stylesheet reset your code to a different style? Commented Jun 18, 2009 at 9:25
  • The meaning would not be changed in that case (it's C code so line breaks are not meaningful to the parser). Commented Jun 18, 2009 at 9:44

2 Answers 2

22

Are you sure you're not doing something wrong? This code works for me on 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>
answered Jun 18, 2009 at 9:15
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this, it worked for me! I also found pre-wrap which wraps both for line breaks in the text as well as when needed: w3schools.com/cssref/pr_text_white-space.asp --- "Text will wrap when necessary, and on line breaks"
11

Check your doctype is valid and on the first line. Maybe it's slipping into quirks mode?

Matthew Murdoch
31.6k32 gold badges99 silver badges127 bronze badges
answered Jun 18, 2009 at 9:20

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.