I’ve received a few requests on how to highlight the syntax of snippets of in a blog like I have. Here is an example snippet of SCSS code, so you can see exactly what I’m referring to.

// Variables
$font-stack: Helvetica, sans-serif;
$primary-color: #333;

@mixin border-radius($radius) {
  -webkit-border-radius: $radius;
  -moz-border-radius: $radius;
  -ms-border-radius: $radius;
  border-radius: $radius;
}

body {
  font: 100% $font-stack;
  color: $primary-color;
}

.box {
  @include border-radius(10px);
}

Many people initially think you have to manually color the elements, or manually escape the characters, but it’s much more simple than that, so I’ll cover everything necessary to embed snippets in your own blog or website in this article.

Prerequisites
  • Basic knowledge of HTML and CSS.
Goals
  • Highlight code syntax in a website or blog.
  • Automatically escape HTML and PHP code in WordPress.

There are two main options to displaying code on your site - embedding the code or using JavaScript to highlight the syntax of pre and code tags.

Embedding

The faster, easier option for syntax highlighting is embedding the code in the form of a GitHub gist or Codepen pen. Both of these can be done with an account or anonymously.

Gist

Here is an example of the above code embedded as a GitHub gist:

Pen

And here is the above code embedded as a CodePen pen.

See the Pen mEerjX

The advantage to embedding is that it’s quick and easy. CodePen in specific is excellent for demos because you can show the code and the result.

However, loading multiple embed scrips throughout your blog can slow it down significantly, and additionally you don’t have much control as to how the code snippet looks and what colors it uses. CodePen is only for front end web development, and you wouldn’t be able to embed code in PHP, Ruby, Python, and so on. For many, that might not matter, and for others it does. For both of these options, all you do is paste your code and find the “embed” button.

#snippets #tutorial #code #visual studio code

Adding Syntax Highlighting to Code Snippets in a Blog or Website
1.20 GEEK