Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve line breaks in <code> block?

Tags:

css

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?

like image 567
Matthew Murdoch Avatar asked Jun 18 '09 09:06

Matthew Murdoch


People also ask

How do you keep a line break in HTML?

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!

How do you stop a line from breaking?

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.

How do you do line breaks in coding?

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.

How do you prevent a line break in CSS?

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.


1 Answers

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> 
like image 65
Paolo Bergantino Avatar answered Sep 25 '22 00:09

Paolo Bergantino