Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

css - HTML <pre> tag causes linebreaks

I'm using CSS (via JQuery , but not relevant to this question) to highlight certain elements within an HTML file: I'm using "pre" tags to separate out logical elements in my file, but I noticed that "pre" tags seem to leave newlines between elements.

Can I get rid of these using CSS ?

(Or what shall I use instead of "pre" tags? The text elements may contain HTML elements themeselves : which should not be rendered, and should be shown literally as source-code: hence my initial choice with "pre" tags)

Here's an example of the HTML I'm using: (Requires http://docs.jquery.com/Downloading_jQuery for this example)

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js">
</script>
</head>
<body>
<pre class="error">
This is an error line.
    stack.trace.blah.blah
    more.blah.blah
    yadda.yadda.blah</pre>
<pre class="ok">
this is not an error line.it contains html
&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;hello&lt;/body&gt;&lt;/html&gt;</pre>
<pre class="error">
This is an error line.
    stack.trace.blah.blah
    more.blah.blah
    yadda.yadda.blah</pre>
<pre class="ok">

<script type="text/javascript">
    $("pre.error").css({"background-color":"red","color":"white","display":"block","padding":"0", "margin":"0"});
</script>
</body>
</html>

I'm using Firefox 3.6.12. This is what the code above results in: alt text

And this is simulated output of what I want (switched to yellow, only because I used my vim editor to this, pretend it's red!)

alt text

SOLUTION:

Is to use 'display:inline' for all PRE tags. (Previously I was only applying the 'display:inline' to the 'error' tags in the example above, and had forget to do the same for 'ok' pre tags.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's because <pre> has a default style display: block, use in your css pre { display: inline}

as for your edit, you need to add margin: 0; to ALL the pre blocks, not just the ones you want to style:

pre {
    display: inline;
    margin: 0;
}

You should try to avoid styling with JS whenever possible, but if you really must:

<script type="text/javascript">
    $("pre.error").css({"background-color":"red","color":"white","display":"block","padding":"0", "margin":"0"});
    $("pre").css({ "margin" : 0, "padding" : 0 })
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...