Search code examples
htmlwhitespaceremoving-whitespacepre

Tags inside pre tag adding other formatting


I'm using pre tags to display code. I want to show some of the code as green. But when I put a <div> tag around the code I want green, it also does things like adds newlines, swallows spacing, et cetera. How do I get the styling to only change the color?

Here's my minimum example. If I have this text in an html file;

<pre>Some space <div style="background-color:#e6ffed;">then</div> more text.</pre>

and open it in chrome, it rendered as

Some space 
then
 more text.

(where the "then" line is green, as desired).


Solution

  • Just use a <span> instead, since it is an inline element.

    A <div> is inherently a block element, so it will behave just as you see here.

    You can learn more about them here.