Reputation: 14370
I need to do some blog posting. For that i need to paste some code of my program.
I want to make use of this code block similar to this
Similar to this
I tried using code or pre but it didn't produced the same output.
How to do it in HTML?
Upvotes: 7
Views: 23642
Reputation: 6776
You probably want to do it in cascading style sheets (CSS). Create some CSS with the look you want, and things marked as <code>
should take on that appearance. For example:
<html>
<head>
<style type="text/css">
code { background-color: gray; color: blue; }
</style>
</head>
<body>
<p>Some code:</p>
<code>My code...</code>
</body>
</html>
You can do tons of formatting in CSS. Use <span class="small_block">
for short blocks of text like keywords, or <div class="big_block">
for larger blocks. Create entries for small_block and big_block in the style section in the header to define the look, but please use better class names than those :). Have fun!
Update: Deep down, the highlighting is properly done through CSS, shown simply and manually above (technically inline styles are possible too, but that is an ugly solution). As the other answers show, there are libraries that can automate the highlighting process, by means of JavaScript that examines and highlights your source code blocks when the page is rendered. They basically provide rich CSS and apply span
and div
tags automatically, and can apply language-specific rules to make code look very elaborately formatted, like modern IDE editors.
Upvotes: 9