How can I style code listings using CSS?

后端 未结 6 1671
生来不讨喜
生来不讨喜 2021-01-29 23:56

I\'d like to display snippets of programming language code, and also HTML code, inside an HTML document using CSS. I want it to be indented and in fixed-width font... I\'m think

6条回答
  •  深忆病人
    2021-01-30 00:48

     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

    element. It is semantically incorrect.

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

    
    My pre-formatted code
        here.
    

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

    
    My pre-formatted "quoted" code here.
    

    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.

提交回复
热议问题