To create a code box with color-coded text (syntax highlighting), you can use a library like Prism.js or Highlight.js. These libraries automatically apply syntax highlighting for various programming languages, making your code box visually appealing.
Here’s how to create a syntax-highlighted code box with Prism.js:
Step 1: Include Prism.js in Your Project
Add the Prism.js CSS and JavaScript to your HTML file. You can use their CDN links.
// <head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
</head>
Step 2: HTML Structure
Wrap your code snippet in a <pre> and <code> block. Add a language-* class to specify the programming language (e.g., language-javascript for JavaScript).
<body>
<div class="code-container">
<pre><code class="language-javascript">
// JavaScript example code
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('World');
</code></pre>
<button class="copy-btn" onclick="copyCode(this)">Copy Code</button>
</div>
<div class="code-container">
<pre><code class="language-html">
<!-- HTML example code -->
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
</code></pre>
<button class="copy-btn" onclick="copyCode(this)">Copy Code</button>
</div>
<script src="script.js"></script>
</body>
Step 3: CSS for Styling
You can use the default Prism.js theme or add additional styles for the code box and buttons.
// body {
font-family: Arial, sans-serif;
background-color: #f7f7f7;
margin: 0;
padding: 20px;
}
.code-container {
position: relative;
margin: 20px auto;
padding: 20px;
background-color: #2d2d2d;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.copy-btn {
position: absolute;
top: 10px;
right: 10px;
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 15px;
font-size: 14px;
cursor: pointer;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.copy-btn:hover {
background-color: #45a049;
}
Step 4: JavaScript for Copy Functionality
Add JavaScript to handle the copy-to-clipboard functionality.
function copyCode(button) {
var codeBox = button.previousElementSibling.querySelector("code");
var textArea = document.createElement("textarea");
textArea.value = codeBox.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("copy");
document.body.removeChild(textArea);
// Provide feedback
button.textContent = "Copied!";
setTimeout(() => {
button.textContent = "Copy Code";
}, 2000);
}
Result:
- Your code box will display syntax-highlighted text for different programming languages.
- Users can click the "Copy Code" button to copy the code snippet to their clipboard.
Demo:
If you want to include other themes, check the Prism.js themes or Highlight.js themes, which offer plenty of customization options for the appearance of your code box.
Post a Comment