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?
nextjs
Dec 21, 2024

Next.js (Pages Router) and Contentlayer Setup

In this blog we will look how to setup Next.js and Contentlayer for an Blog page. Step one Install necessary deps ```bash npm install \ contentlayer next-contentlayer \ shiki rehype-shiki rehype-pretty-code \ rehype-autolink-headings rehype-slug rehype-rewrite rehype-stringify \ remark-gfm unified \ date-fns reading-time ``` create contentlayer.config.ts file add contentlayer.config.ts in your root of the project and you have to create your blog files in this folder folder strcture of the necessary files and folders ```bash /public /content /blog /markdown-syntax-guide index.mdx contentlayer.config.ts tsconfig.json nextjs.config.ts ``` ```ts
nextjs
Dec 21, 2024

Next.js (Pages Router) and Contentlayer Setup

# Building a Scalable MDX Blog with Next.js and Contentlayer As engineering leads, one of our recurring challenges is balancing scalability, readability, and extensibility when building content-heavy frontend applications. A lightweight, composable blog system using **Next.js (Pages Router)** and **Contentlayer** checks all the right boxes—type safety, statically generated performance, and full MDX control. In this post, you'll set up a production-grade foundation for a statically rendered blog using **Contentlayer** and **Next.js**, with an emphasis on correctness, long-term maintainability, and modern DX. --- ## Project Structure Here’s the
powershell
May 5, 2023

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**: Before proceeding, check if you have an existing profile set up in PowerShell: ```powershell test-path $profile ``` **STEP 2**: If the result is false, create a new profile: ```powershell new-item -path $profile -itemtype file -force ``` **STEP 3**: Now, open the profile in Notepad: ```powershell notepad $profile ``` **ST