Problem when using pre-tag

In my project, we need to display a code snippet, so I use the pre and code (both) tag.

PROBLEM

When the code snippet is displayed, it displays spaces before and after the actual content. How do I remove those spaces before and after a snippet.

+2


source to share


4 answers


Remove spaces inside your pre tag.

Example:

<pre>
  This is a test.

  We want a new line here.
</pre>

      



it should be

<pre>This is a test.

We want a new line here.</pre>

      

+7


source


As of HTML 5, the pre tag is no longer supported if you want to use its features. Create 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;
}

      



Canceling /*white-space: pre; white-space: pre-wrap;*/

will cause your white spaces to act like a div. use it as a class to give the same look and feel for your elements.

+2


source


The tag <pre>

is for preformatted text. This means you have to do the formatting yourself - all of this, including making sure the spaces are exactly what you want to display. Do not print extra spaces between tags <pre>

and the content inside them.

0


source


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

The little thing that I myself have 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 to 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;
}

      

You may find it helpful.

0


source







All Articles