Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I style code listings using CSS?

Tags:

html

css

People also ask

What does list style do in CSS?

The list-style-type CSS property sets the marker (such as a disc, character, or custom counter style) of a list item element.


Sharing an example I use in website, I do use following pre in my stylesheet:

pre {
    background: #f4f4f4;
    border: 1px solid #ddd;
    border-left: 3px solid #f36d33;
    color: #666;
    page-break-inside: avoid;
    font-family: monospace;
    font-size: 15px;
    line-height: 1.6;
    margin-bottom: 1.6em;
    max-width: 100%;
    overflow: auto;
    padding: 1em 1.5em;
    display: block;
    word-wrap: break-word;
}

This gives the following results:

enter image description here

Disclaimer: In my leisure time, I have spend few hours to update this CSS with a bit extra features like code lines and code Copy button using CSS with JavaScript to my personal use that I like to share. Please use as you like github source code.


This javascript library seems excellent:

https://highlightjs.org/

UPDATE: I also used this on my Tumblr-based blog because it was easiest to deploy:

https://github.com/google/code-prettify

and I have used this one also (some extra features):

http://alexgorbatchev.com/SyntaxHighlighter/


<pre> would automatically retain your tabs and line-breaks within the bounding pre tags. Most browsers automatically default to a monospaced font inside pre but if you want to force it, (which is a good idea) you can use the following CSS:

pre { font-family: monospace; }

I would recommend that you not place code directly into a <blockquote> element. It is semantically incorrect.

If you want your code to be semantically correct, you should mark it up like this:

<pre><code>
My pre-formatted code
    here.
</code></pre>

If you are actually "quoting" a block of code, then the markup would be:

<blockquote><pre><code>
My pre-formatted "quoted" code here.
</code></pre></blockquote>

If you want even better-looking code, you can employ Google Code's Prettify which is used by StackOverflow to color code-snippets. It has it's own stylesheets that it automatically imports based on what language it thinks the code is and colors the code accordingly. You can give it a hint as to what language the code is by appending a class.


Well, you could try using a <pre> tag in your blockquote to preserve the formatting first, and then use a monospaced font, like courier for the css style.

Something like this would work in the css:

pre {
  font-family:     "Courier New"
                    Courier
                    monospace;
}