Blog
Syntax Code Blocks in Webflow CMS: A Step-by-Step Guide
Web
Guides
6
min read

Syntax Code Blocks in Webflow CMS: A Step-by-Step Guide

Published on
Sep 3, 2024
Blog
Syntax Code Blocks in Webflow CMS: A Step-by-Step Guide
Web
Guides
6
min read

Syntax Code Blocks in Webflow CMS: A Step-by-Step Guide

Published on
Sep 3, 2024

Contributors

Omer Hoffman
Web Design Team Lead
Natalia Kovalenko
Web Designer

Adding beautifully styled code blocks with syntax highlighting to your Webflow CMS website is a great way to enhance the user experience. In this guide, we'll walk you through how to integrate Highlight.js into your Webflow project to achieve this, along with adding a 'Copy Code' button to make it even more user-friendly.

Step 1: Add Highlight.js to Your Webflow Site

To begin, you need to add the Highlight.js library to your website. This library provides the syntax highlighting functionality for your code blocks.

  1. Navigate to your CMS Collection page settings in Webflow.
  2. Paste the following script just before the closing </body> tag:
 <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>

Step 2: Select and Apply a Highlight.js Theme

Highlight.js offers various themes to style your code blocks. Here's how to add a theme:

1. To use the default style, go to your CMS Collection page settings and paste this link inside the <head> tag:

 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">

2. If you want to explore more styles, visit the Highlight.js demo page to test different themes. Once you find the theme that suits your website, head over to Highlight.js GitHub to find the corresponding CSS file.

Copy the file name from the URL after /styles/ and replace it in your link.

Important note: It should always end with .min.css.

Step 3: Define Code Blocks in Rich Text Elements

To implement syntax highlighting, you need to create code blocks within a Rich Text field in your CMS item. Follow these steps:

  1. Add a new Embed element in the Rich Text editor and paste this code:
 <pre>
 <code>
 // your code here
 </code>
</pre>
  1. Use an HTML Escape tool like Code Beautify to prevent your code from executing and ensure it displays correctly on the page. Paste the escaped code between the <code> tags.
    Note: You don't need to use the HTML Escape tool for CSS and SQL.
  2. Once done, publish your site to see your newly styled code blocks!

Important Note: To ensure that your code blocks don't disrupt your website's layout, it’s crucial to set a maximum width for the rich text element. This prevents long lines of code from stretching beyond their container and potentially breaking the design.

Optional Step #1: Add a 'Copy Code' Button

To enhance the user experience, consider adding a 'Copy Code' button that allows users to quickly copy code snippets to their clipboard. Here are two different scripts you can use:

Choose Your Button Style

Decide whether you want a text-based button or an icon-based button and paste the relevant script before the closing </body> tag on your page. Below are two script options:

‘Copy Code’ Text Button:

 <!-- Copy Code Text Button -->
<script>
  document.addEventListener('DOMContentLoaded', function() {
    // Select all <pre><code> blocks
    document.querySelectorAll('pre code').forEach(function(codeBlock) {
      // Create a wrapper div for the code block and the button
      var wrapper = document.createElement('div');
      wrapper.classList.add('code-block-wrapper');
      
      // Create the copy button
      var copyButton = document.createElement('button');
      copyButton.classList.add('copy-btn');
      copyButton.textContent = 'Copy Code';

      // Insert the button before the code block
      codeBlock.parentNode.insertBefore(wrapper, codeBlock);
      wrapper.appendChild(copyButton);
      wrapper.appendChild(codeBlock);

      // Add event listener to the copy button
      copyButton.addEventListener('click', function() {
        var code = codeBlock.innerText;
        navigator.clipboard.writeText(code).then(function() {
          // Change button text to "Copied"
          copyButton.textContent = 'Copied!';
          
          // Optional: Reset the text after a delay
          setTimeout(function() {
            copyButton.textContent = 'Copy Code';
          }, 2000); // 2 seconds delay
        }, function() {
          alert('Failed to copy code.');
        });
      });
    });
  });
</script>

Copy Code Icon Button:

 <!-- Copy Code Icon Button -->
<script>
  document.addEventListener('DOMContentLoaded', function() {
    // Select all <pre><code> blocks
    document.querySelectorAll('pre code').forEach(function(codeBlock) {
      // Create a wrapper div for the code block and the button
      var wrapper = document.createElement('div');
      wrapper.classList.add('code-block-wrapper');
      
      // Create the copy button with only the icon
      var copyButton = document.createElement('button');
      copyButton.classList.add('copy-btn');
      copyButton.innerHTML = `
        <img src="https://cdn.prod.website-files.com/64889d1417f36c1e9731bb2c/66cb0f42609ab9d86273fa35_copy.svg" alt="Copy" class="copy-icon"/>
      `;

      // Insert the button before the code block
      codeBlock.parentNode.insertBefore(wrapper, codeBlock);
      wrapper.appendChild(copyButton);
      wrapper.appendChild(codeBlock);

      // Add event listener to the copy button
      copyButton.addEventListener('click', function() {
        var code = codeBlock.innerText;
        navigator.clipboard.writeText(code).then(function() {
          // Change button to indicate code was copied
          copyButton.innerHTML = 'Copied!';
          
          // Optional: Reset the button to icon after a delay
          setTimeout(function() {
            copyButton.innerHTML = `
              <img src="https://cdn.prod.website-files.com/64889d1417f36c1e9731bb2c/66cb0f42609ab9d86273fa35_copy.svg" alt="Copy" class="copy-icon" />
            `;
          }, 2000); // 2 seconds delay
        }, function() {
          alert('Failed to copy code.');
        });
      });
    });
  });
</script>

Styling Your Button

To make the ‘Copy Code’ button visually appealing and consistent with your website’s design, you’ll need to add some custom CSS. You can further customize the button’s appearance by modifying the CSS properties to better match your site’s design.

 <style>  
  .copy-icon {
  width: 24px;
  height: 24px;
  }

  .code-block-wrapper {
    position: relative;
  }

  .copy-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 10px;
    right: 10px;
    padding: 4px 4px;
    background-color: #ffffff;
    border: 1px solid #000000;
    border-radius: 4px;
    color: #000000;
    cursor: pointer;
    transition: background-color 0.3s;
    font-family: "Open sans", sans-serif;
  }
  
   .copy-btn:hover {
    background-color: #ffffff;
  }
  
   .copy-btn.copied {
    background-color: #ffffff; /* Change color when copied */
    padding: 4px 14px;
  }  
</style>

Optional Step #2: Custom Styling for Highlight.js Elements

To customize the appearance of different elements within your Highlight.js code block, you can apply specific styles to the Highlight.js CSS classes. Below is a guide to custom styling for various code elements, including comments, numbers, keywords, and more.

  1. Base Code Block Styling: To style the entire code block, use the .hljs class
  2. Specific Element Styling:
    • Comments, Invisibles, Line Highlighting (.hljs-comment): To style comments and other less visible text
    • Integers, Boolean, Constants, XML Attributes, Markup Link URL (.hljs-symbol, .hljs-number, .hljs-link, .hljs-attr, .hljs-variable.constant_, .hljs-literal): To style numbers, symbols, constants, etc.
    • Classes, Markup Bold, Search Text Background (.hljs-title, .hljs-class .hljs-title, .hljs-title.class_): To style class names, bolded text, and search highlights
    • Storage, Selector, Markup Italic, Keywords (.hljs-type, .hljs-template-tag, .hljs-keyword): To style keywords and types
    • Emphasis (.hljs-emphasis): To style emphasized text

Example:

 

Add the above styles in your Webflow project through an Embed element or in the Project Settings under the 'Custom Code' section. Publish the changes to apply custom styles to your code blocks. This will give you control over how different parts of your code are styled.

Conclusion

At Polar, we've found that enhancing our clients' websites with Highlight.js and custom styling is a game-changer for showcasing code snippets. It's become our go-to method for improving both functionality and visual appeal. The "Copy" button we add is always a hit, making it a breeze for users to grab code quickly. Plus, we love how customizing the appearance of different code elements lets us align the styling with each client's unique brand while keeping things readable.

We've streamlined the process of implementing these changes in Webflow, making it a smooth part of our workflow. This approach helps us create engaging and professional presentations for any technical content.

By following these steps in your own projects, you'll give your users the polished, interactive experience we strive for in all our builds. We've seen firsthand how these small touches can significantly boost user engagement and satisfaction. So go ahead, give it a try – we think you'll love the results as much as we (and our clients) do!

Contributors

Omer Hoffman
Web Design Team Lead
Natalia Kovalenko
Web Designer
Visual
5
min read

Product Animation: Beyond Basic Screen Recording

Web
Tips
3
min read

AVIF vs WebP: The Right Image Format for Your Webflow Site

Web
Guides
3
min read

Enhance Webflow Sliders with Splide.js

Web
Guides
4
min read

Country Codes in Webflow Form: A Step-by-Step Guide

Web
6
min read

Rive vs Interactive Lottie: Choosing Your Web Animation Tool

Web
Guides
5
min read

Custom Menu Breakpoints in Webflow: A Step-by-Step Guide