33

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
  • 13,617
  • 16
  • 88
  • 129
Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
  • If the line breaks are meaningful, then they are "content," not "style," and should be coded with <pre> tags. Would it change the meaning of your page if a user stylesheet reset your code to a different style? – Thomas L Holaday Jun 18 '09 at 09:25
  • The meaning would not be changed in that case (it's C code so line breaks are not meaningful to the parser). – Matthew Murdoch Jun 18 '09 at 09:44

2 Answers2

21

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>
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • 1
    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: https://www.w3schools.com/cssref/pr_text_white-space.asp --- "Text will wrap when necessary, and on line breaks" – sunyata Nov 21 '18 at 13:50
11

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

Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
SpliFF
  • 38,186
  • 16
  • 91
  • 120