Deepak Kumar
Deepak Kumar

Reputation:

Problem while using pre tag

In my project we need to display code snippet, so I am using pre and code(both) tag.

PROBLEM

While displaying the code snippet it is displaying white spaces before and after the actual content. How to remove these white spaces before and after the snippet.

Upvotes: 5

Views: 14411

Answers (4)

Coderx07
Coderx07

Reputation: 198

With HTML 5 pre tag doesnt supported anymore if you want to use its features. Make your own css class like this...

.pre
{
border: 1px solid #999;
page-break-inside: avoid;
display: block;
padding: 3px 3px 2px;
margin: 0 0 10px;
font-size: 13px;
line-height: 20px;
word-break: break-all;
word-wrap: break-word;
/*white-space: pre;
white-space: pre-wrap;*/
background-color: #f5f5f5;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, 0.15);
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
font-family: Monaco, Menlo, Consolas, "Courier New", monospace;
font-size: 12px;
color: #333333;
}

.pre code
{
    padding: 0;
    color: inherit;
    white-space: pre;
    white-space: pre-wrap;
    background-color: transparent;
    border: 0;
}

Cancelling /*white-space: pre; white-space: pre-wrap;*/ will make your white spaces works like div. use it as a class to give the same look to your elements.

Upvotes: 3

Johan
Johan

Reputation: 20763

You need to make sure the code is formatted correctly, the pre tag tells the browser to show the text inside the pre "as is".

A little thing that I my self has found useful is to use this php to import the file so I don't have to cut and paste all the time.

<?php
$file = "code/hello_world.c";
print "<p>Filename: <a href=\"".$file."\">".$file."</a></p>\n";
print "<div class=\"codebox\"><pre>\n\n";
$lines = file($file); foreach ($lines as $line_num => $line)
{ 
    echo htmlspecialchars($line) . ""; 
}
print "\n</pre></div>\n";
?>

And then to make it look like code I add this in my css

PRE {
    font-family:    'Monotype.com', Courier New, monospace;
    font-size:  0.7em;
}

.codebox {
    width: 90%;
    background-color: #000000;
    color: #FFFFFF;
}

.codebox pre {
    margin:      0 0 0  20px;
}

Maybe you find it helpful.

Upvotes: 0

Amber
Amber

Reputation: 526633

The <pre> tag is for pre-formatted text. That means you need to do the formatting yourself - all of it, including making sure the whitespace is exactly what you want to display. Don't output excess whitespace between your <pre> tags and the content inside of them.

Upvotes: 1

derobert
derobert

Reputation: 51157

Remove the whitespace inside your pre tag.

Example:

<pre>
  This is a test.

  We want a new line here.
</pre>

should be

<pre>This is a test.

We want a new line here.</pre>

Upvotes: 10

Related Questions