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?
Preserve Newlines, Line Breaks, and Whitespace in HTML If you want your text to overflow the parent's boundaries, you should use pre as your CSS whitespace property. Using white-space: pre wraps still preserves newlines and spaces. Enjoy!
Use white-space: nowrap; or give that link more space by setting li 's width to greater values. I prevented line break in li items using display: inline; . Maybe this will also help others with similar problems. Its important to be careful with display: inline as it can have side effects.
The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.
The white-space property has numerous options, all of which define how to treat white space inside a given element. Here, you have set white-space to nowrap , which will prevent all line breaks.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With