Custom Content Code Block Using HTML CSS JS

3 min read
Dec 21, 201

Code blocks are an integral part of developer-facing content, enabling clear and organized presentation of code. In this guide, we will walk through creating custom, aesthetically pleasing code blocks with both single-tab and multi-tab functionality using modern web technologies. This guide is targeted at developers with a working knowledge of HTML, CSS, and JavaScript.

Why Custom Code Blocks?

While libraries like Prism.js and Highlight.js provide excellent syntax highlighting, creating a custom code block allows for:

  • Complete Control: Tailor the design and functionality to your needs.
  • Seamless Integration: Align the blocks with your application's design system.
  • Interactive Features: Implement bespoke user interactions like copy buttons or collapsible sections.

Setting Up: The Basic HTML Structure

Single-Tab Code Block

A single-tab code block displays one snippet at a time. Here’s the basic structure:

<div class="code-block">
  <div class="code-header">
    <span>Example Code</span>
    <button class="copy-btn">Copy</button>
  </div>
  <pre class="code-content"><code class="language-js">
function greet(name) {
    return `Hello, ${name}!`;
}
console.log(greet('World'));
  </code></pre>
</div>

Multi-Tab Code Block

A multi-tab code block allows toggling between different snippets or languages:

<div class="code-block">
  <div class="tabs">
    <button class="tab active" data-target="html">HTML</button>
    <button class="tab" data-target="css">CSS</button>
    <button class="tab" data-target="js">JavaScript</button>
  </div>
  <div class="code-content">
    <pre class="code-tab active" id="html"><code class="language-html">
<!-- HTML Example -->
<div class="container">Hello, World!</div>
    </code></pre>
    <pre class="code-tab" id="css"><code class="language-css">
/* CSS Example */
.container {
    font-size: 16px;
    color: blue;
}
    </code></pre>
    <pre class="code-tab" id="js"><code class="language-js">
// JavaScript Example
console.log('Hello, World!');
    </code></pre>
  </div>
</div>

Adding Styles with CSS

To make the code blocks visually appealing, use CSS for styling:

.code-block {
  border: 1px solid #ddd;
  border-radius: 6px;
  font-family: 'Fira Code', monospace;
  overflow: hidden;
  margin-bottom: 1.5rem;
}

.code-header {
  background-color: #f5f5f5;
  padding: 0.5rem 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.9rem;
  border-bottom: 1px solid #ddd;
}

.copy-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 0.3rem 0.8rem;
  border-radius: 4px;
  cursor: pointer;
}

.copy-btn:hover {
  background-color: #0056b3;
}

.tabs {
  display: flex;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
}

.tab {
  padding: 0.5rem 1rem;
  cursor: pointer;
  background: none;
  border: none;
  outline: none;
}

.tab.active {
  border-bottom: 2px solid #007bff;
  font-weight: bold;
}

.code-content {
  padding: 1rem;
  background-color: #282c34;
  color: #fff;
  overflow-x: auto;
}

.code-tab {
  display: none;
}

.code-tab.active {
  display: block;
}

Adding Functionality with JavaScript

Copy Button for Single Tab

Add a "Copy to Clipboard" feature for the single-tab block:

document.querySelectorAll('.copy-btn').forEach(button => {
  button.addEventListener('click', () => {
    const code = button.parentElement.nextElementSibling.textContent;
    navigator.clipboard.writeText(code).then(() => {
      alert('Code copied to clipboard!');
    });
  });
});

Tab Switching for Multi-Tab

Enable switching between tabs in the multi-tab block:

document.querySelectorAll('.tabs').forEach(tabContainer => {
  tabContainer.addEventListener('click', event => {
    const targetTab = event.target.dataset.target;
    if (!targetTab) return;

    // Handle active tab
    tabContainer.querySelectorAll('.tab').forEach(tab => {
      tab.classList.toggle('active', tab.dataset.target === targetTab);
    });

    // Handle active code block
    const codeContainer = tabContainer.nextElementSibling;
    codeContainer.querySelectorAll('.code-tab').forEach(tab => {
      tab.classList.toggle('active', tab.id === targetTab);
    });
  });
});

Enhancements and Next Steps

  1. Syntax Highlighting: Integrate a library like Prism.js for professional syntax highlighting.
  2. Dark/Light Modes: Add theme toggling to align with user preferences.
  3. Responsive Design: Ensure the blocks look good on smaller screens.
  4. Accessibility: Use ARIA attributes for better screen reader compatibility.

Conclusion

By now, you’ve built a custom code block that’s stylish, functional, and unapologetically yours. Not only does it fit your application like a glove, but it also comes with bragging rights: “Yes, I wrote this from scratch.” And isn’t that what being a developer is all about?

Wanna Discover more Interesting Topics?
Regression-Analysis
Apr 12, 2023

Curve fitting for charts in Analytics

Linear regression is just a special case of polynomial regression where the order is 1. You can drag the slider above to see how different polynomial orders affect the fitting curve. When the order is N, the polynomial function will have a degree of N, and the curve will have N1 turning points (so 1 is a straight line). The Mean Squared Error (MSE) value (Σ(value predictedValue)^2 / dataNum) measures the "goodness" of the fit of the curve to the data. The smaller the error is, the better the curve describes the given data. Usually, the easy solution would be manually choosing a reasonable order and hardcoding it in our visualization. That’s w
powershell
Nov 12, 2022

Configuring PowerShell (shell prompt)

In Windows PowerShell, customizing your shell prompt can enhance your development environment by providing valuable information at a glance. This guide walks you through configuring Windows PowerShell to display a customized prompt with the username, date, and current folder name. Checking for Existing Profile STEP 1: Check for an Existing Profile Run the following command to check if you have an existing profile set up in PowerShell: powershell testpath $profile STEP 2: Create a New Profile (if needed) If the result is false, create a new profile: powershell newitem path $profile itemtype file force STEP 3: Open the Profile in Notepad Open t
markdown
Apr 9, 2022

Markdown Syntax Guide

Markdown is a lightweight markup language that allows you to format text in a plaintext editor while still having a structured and readable output. It is often used for writing documentation, readme files, blog posts, and other content where readability and simplicity are important. Markdown syntax is simple and intuitive, making it an ideal choice for writing and formatting text without the need for complex HTML tags. Its flexibility and ease of use make it a popular tool among developers, writers, and content creators alike. By using basic symbols and characters, you can structure documents that are both humanreadable and machinereadable, w