Auto-Formatting Code Snippets with CSS

Edit: I added overflow: auto to handle long lines of code.

I’ve recently thought about putting some of my code snippets up on this site, since I come up with a lot of them at work. This led to the question of how to format these without losing my mind. I wrote a few lines of CSS to do this automatically. The example of this is the below code itself:

<b>HTML</b>
&lt;code&gt;&lt;b&gt;Type of code&lt;/b&gt;
Code
  Indented code (tabs work!)
Code
&lt;/code&gt;<br />
<b>CSS</b>
code {
  display: block;
  margin: 1.5em 50px;
  padding: 12px;
  background-color: #DDD;
  border: 1px dashed #999;
  font-family: "Courier New", Courier, mono;
  color: #666;
  white-space: pre;
  overflow: auto;
}
code b {
  display: block;
  border: 1px dashed #666;
  width: 100px;
  height: 20px;
  background-color: #CCC;
  text-align: center;
  line-height: 20px;
}

I haven’t found a way to convert the < and > symbols, since I also have to use those internally for the subheaders, so I’m having to manually go in and change those to &lt; and &gt;, but I’ll look for a way around this.

Note: WordPress is deciding to “help” me by automatically closing tags if I put more than one line break in-between them and adding a <br> tag when I put in a line break. While this is usually a good thing, it doesn’t go well with my new design. I’ll work on taking out this functionality once I have some more time.

Leave a Reply