What is the easiest way to add color coding to a code block in HTML?

Creating a color-coded code block on a website to showcase HTML/CSS components can be a tedious process. Is there a faster way to achieve this?

An example of messy code blocks can be seen on Bootstrap 5's buttons page. The implementation involves numerous span tags with different attributes for color-coding. Is there an easier method to accomplish this without individual attribute additions?

<div class="highlight"><pre class="chroma"><code class="language-html" data-lang="html">(example code snippet here)</code></pre></div>

The current approach used by Bootstrap 5 involves multiple spans with various attributes for color-coding sections within the code block. Are there alternatives to simplify this process?

EDIT (My Solution):

To address this challenge, I opted to utilize highlight.js. This tool proved to be user-friendly, and I followed a tutorial on YouTube to seamlessly integrate it into my HTML code. Thank you for all the recommendations!

Answer №1

As @j08691 pointed out, there exist libraries that can handle this task for you.

For instance:

You have the option to utilize a pre-built syntax highlighter such as shiki along with some javascript code to transform your page's markup into a syntax-colored version.

The following snippet takes a moment to perform the conversion, likely due to the external script, but it demonstrates the concept:

shiki
  .getHighlighter({
    theme: 'nord'
  })
  .then(highlighter => {
    document.querySelectorAll('pre').forEach(element => {
      const language = element.dataset.lang || 'js';
      const code = highlighter.codeToHtml(element.innerText, language);
      element.innerHTML = code
    })
  })
pre {
  padding: 1em;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5c6ddcdcfcce9cecfded1dfcbccdfa3e2e3eaeca7d1cadadfdfcdedcddfcedecdcfadfcbd63277502cac8001fefcaccfeecbabefe824cafceaefcacbc6a9cbdcecaaecefabadcebfacdbfbeab6adebbffcdace19dcbcfaadafadbabeafeda9dab">[email protected]</a>/dist/index.unpkg.iife.js"></script>

<pre>
function foo (arg1) {
  console.log('syntax highlighting is fun.');
}
</pre>

<pre data-lang="html">
&lt;button class="foo"&gt;This is a button&lt;/button&gt;
</pre>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I populate the subject line with a select option using only HTML, without the use of JavaScript, PHP, or any other external sources?

Can the subject line be automatically filled using a select element in html alone, without any need for javascript, php, or other sources? See example below <select> <option value="volvo">Volvo</option> <option value="saab">Saab& ...

Can you explain how to handle a POST request in an ASP.NET application?

I have a question that may appear trivial. Our streaming server manual mentions that it can authenticate by sending a POST request to an HTTP server and receiving a couple of lines of text in response. How does this process work in the context of ASP.NET? ...

JavaScript - Receiving alert - AC_RunActiveContent.js needed for this page to function

When I attempt to open the HTML file in my application, a pop-up message appears stating that "This page requires AC_RunActiveContent.js." However, I have already imported and referenced the AC_RunActiveContent.js file in my package. Can someone assist m ...

Choose the first and last div element in the selection

Is there a way to target the first and fourth div elements using the :nth-child selector for styling purposes? .main{ width:460px; height:240px; } .box{ width:100px; height:100px; background:red; float:left; margin:10px; } /*I tried */ . ...

Filtering through Jquery with a combination of two specific values

Having an issue with jQuery filtering this time. $( document ).ready(function() { $('#search').keyup(function() { var s = new RegExp(this.value); $('#support-tasks-table tbody tr').each(function() { i ...

What is the best way to ensure that an input tag within a fieldset tag is required

I am currently working on creating a sign-up page using HTML and JavaScript. However, I am facing an issue with making the input tag required in the HTML code. The following code snippet does not seem to be working as expected: <input type="email" requ ...

Map region indicator tooltip

I possess a map that contains a specific area with a title. Here is the accompanying code: <map name="Map" id="Map"> <area alt="" shape="rect" coords="127,52,186,71" href="#" title="Extending telephone lines to other Egyptian governorates ...

Optimizing CSS for printing by eliminating unnecessary white space with media queries

Appreciate your assistance! I'm currently working on a solution to print a specific div using CSS Media queries. When the user clicks on print, I want to hide all other elements except for the body div they chose. However, I'm facing an issue whe ...

Ways to retrieve inner content as a variable without having to render it in LitElements

Here is how I am utilizing my lit element: <my-header>MyHeading</my-header> Within my lit element, I have the render method defined as follows: render() { return html` <h3><slot></slot></h3> `; } Everything is ...

Javascript dynamically generates CSS animations

I need assistance creating a div with a CSS3 animated timer inside it when a button is clicked. Here is the code I have been working on: http://jsfiddle.net/arcco96/y5nov6rz/1/. Unfortunately, the div is not being created as expected. I believe the code sh ...

Pair of buttons triggering the submission of a form

I'm encountering an issue where I have 2 buttons in my form, one for submitting and one for going to the previous page, but both seem to be performing the same action. How is this happening? <div style="position:fixed; left: 50px; ...

An error occurs when trying to modify the classList, resulting in an Uncaught TypeError for setting an indexed property

I am attempting to modify the classes of multiple sibling elements when a click event occurs. Some of these elements may have multiple classes, but I always want to change the first class. Below is the code that I created: let classList = event.currentTa ...

Issues stemming from undesirable behavior involving iframes and transitions

Hey everyone, I have a question regarding web development. I am quite new to this field and I'm facing an issue with getting videos to open with a fade-in and slide effect when a text link is clicked. I decided to use iframes instead of jQuery's ...

What are the ways to create fading text effect on a webpage?

I'm new to this platform and I have a question. I want to create an Anki card that displays a question for a few seconds before fading out. Here is the code snippet I came across: @-webkit-keyframes fadeIn { 100%,0%{opacity:.5;} 0%,0%{opacity:1;} } . ...

Ways to change the role link in child elements inherited from the parent in terms of Accessibility

How can I create a tooltip with dynamically added tooltip content div requiring a role link for the aria label to be appended as needed? The initial HTML of the tooltip before expansion is: <div class="tooltip" tabindex="0" aria-expa ...

The issue with Three.js responsive canvas is that it fails to properly adjust the size of the

I'm currently working on a threejs basic scene and attempting to create a responsive canvas for a full-screen experience. However, the mesh inside the scene is not resizing correctly as expected. Instead of remaining a cube, it distorts into a rectang ...

Using jQuery, you can easily apply a new class to a div when it is

I'm currently facing an issue with adding a class of "active" to a div upon clicking it using jQuery. My goal is to apply the css class of active in order to give the button a distinct color (or the hover effect.) Unfortunately, I have been unsuccess ...

Can Django implement pagination without altering the URL structure?

I discovered the fundamentals of pagination in Django at this resource: Nevertheless, I am faced with a challenge - I wish to implement pagination without modifying the URL. Specifically, I need to paginate a single table among multiple tables on an HTML ...

Adjust the standard size of the IMG tag using CSS

I have a simple image tag with an incorrect URL http://jsbin.com/monivava/1/edit <img src="http://placekitten!!!.com/g/200/200"> The issue is that the default size for this unsuccessful image is 18x20 (at least in Webkit), but I want it to be 0px ...

Visual content may be unavailable during program execution

When attempting to apply an image in the background of an HTML tag using CSS, I am encountering an issue where the image is not visible during runtime, even though it appears during design time. Additionally, I am curious as to why the full path needs to b ...