2

I'm writing a tutorial for my blog, and I'm using [code][/code] tags around the text I want to be displayed as code. I've tried replacing [code] with <code>, <pre> or <div class="code-block">

However, with <code></code> if I indent some lines with spaces the spaces don't show up, so it's not as easy to read. For example

<div id="example1">
code which I would like indented
</div>

<div id="more-code1">
more code
</div>

With <pre></pre> the spaces do show up okay, but it looks like this

<div id="example2">

code which I would like indented

</div>



<div id="more-code2">
more code
</div>

If I do <div class="code-block"></div> it looks the same as using code

It could be to do with how I display the posts, so here's my PHP code

<div class="box-content">
    <p><?php echo bbconvert(nl2br(htmlentities($post['content'], ENT_QUOTES))); ?></p>
</div>

bbconvert() is a simple function that replaces [list] with <ul> or [row] with <li>

2 Answers 2

7

Have you taken a look at Google Code Prettify?

I've used it for countless code displays and tutorials. If not, put it between <pre></pre> tags. This will make whitespace matter in the HTML, so whatever you type in the .html file will show up exactly as typed on the webpage in a monospace font

Sign up to request clarification or add additional context in comments.

2 Comments

It has moved here github.com/googlearchive/code-prettify and is no longer supported. I guess you would like to use different libs, Monaco editor has powerful features for example.
Or highlight (highlightjs.org) unfortunately both this and Markdown are (rather heavy) JS libs... no pure css
4

You need to either surround the <code> elements with <pre> tags, or you need to paste on a CSS style of white-space: pre. Those two things should be equivalent in most cases. The pre setting means that the renderer will preserve the spaces instead of collapsing them as normal, and will break lines on newlines as well.

For example, if you choose <div class="code-block">, then div.code-block { white-space: pre; } in your CSS rules should help. Or you could just go with

<pre><code>
code which I would like indented
</code></pre>    

1 Comment

thanks, but if I use <pre> or white-space: pre then instead of being 1 line in between bits of code, there's 2 lines. I think it may be due to nl2br though. may need to work out how to skip certain parts of my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.