Adding a code box to your website or blog is an essential skill if you regularly share programming tutorials, scripts, or snippets. A code box separates code from regular content, making it easier to read and copy. In this article, we will explain how to add a code box by utilizing the head and body sections of your HTML page.
1. Understanding the </head> Paste Section
<!-- Highlight.js theme (LuxTechZone) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css" />
<style>
:root {
--cbg: #0f1117;
--ring: rgba(0, 0, 0, .08);
--border: rgba(255, 255, 255, .10);
--muted: #8b93a7;
--acc: #0ea5e9;
--text: #e6edf3;
--btn-bg: rgba(255, 255, 255, .06);
--btn-br: rgba(255, 255, 255, .12);
--btn-bg-h: rgba(255, 255, 255, .10);
/* tone scrollbar siêu nhẹ */
--sb-thumb: rgba(255, 255, 255, .22);
--sb-thumb-h: rgba(255, 255, 255, .32);
--sb-track: transparent;
}
.td-codeblock {
margin: 1rem 0;
border: 1px solid var(--border);
border-radius: 14px;
background: var(--cbg);
box-shadow: 0 6px 24px var(--ring);
overflow: hidden;
}
/* Header / Toolbar */
.td-codebar {
display: grid;
grid-template-columns: 1fr auto;
gap: .5rem;
align-items: center;
padding: .6rem .75rem;
background: linear-gradient(180deg, rgba(255, 255, 255, .06), transparent);
border-bottom: 1px solid var(--border);
}
.td-filemeta {
display: flex;
align-items: center;
gap: .55rem;
font: 600 12px/1.2 ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto;
color: var(--muted)
}
.td-dot {
width: .55rem;
height: .55rem;
border-radius: 999px;
background: #ff6b6b;
box-shadow: .9rem 0 0 #ffd93d, 1.8rem 0 0 #6bcB77;
margin-right: 1.4rem;
opacity: .95
}
.td-lang {
color: var(--acc);
font-weight: 700
}
.td-fname {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--muted)
}
.td-actions {
display: flex;
align-items: center;
gap: .5rem;
}
.td-btn {
display: inline-flex;
align-items: center;
gap: .45rem;
padding: .5rem .65rem;
border: 1px solid var(--btn-br);
background: var(--btn-bg);
color: var(--text);
border-radius: 12px;
cursor: pointer;
user-select: none;
font: 600 12px/1 ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto;
transition: background .15s ease, transform .1s ease;
}
.td-btn:hover {
background: var(--btn-bg-h)
}
.td-btn:active {
transform: translateY(1px)
}
.td-btn svg {
width: 15px;
height: 15px;
display: block
}
@media (max-width:640px) {
.td-btn .td-label {
display: none
}
/* di động: chỉ icon */
.td-fname {
display: none
}
}
/* Code area (auto height theo nội dung) */
.td-code {
position: relative;
overflow: auto
}
.td-code pre {
margin: 0;
padding: 1rem 1.1rem 1.25rem;
background: transparent
}
/* Scrollbar mảnh – chỉ lộ khi hover */
/* Firefox */
.td-code {
scrollbar-width: thin;
scrollbar-color: transparent var(--sb-track);
}
.td-code:hover {
scrollbar-color: var(--sb-thumb) var(--sb-track);
}
/* WebKit */
.td-code::-webkit-scrollbar {
height: 8px;
width: 8px;
background: var(--sb-track);
}
.td-code::-webkit-scrollbar-thumb {
background: transparent;
border-radius: 999px;
border: 2px solid transparent;
background-clip: padding-box;
}
.td-code:hover::-webkit-scrollbar-thumb {
background: var(--sb-thumb);
}
.td-code::-webkit-scrollbar-thumb:hover {
background: var(--sb-thumb-h);
}
.td-code::-webkit-scrollbar-corner {
background: transparent;
}
/* Line numbers (plugin) */
.hljs-ln td {
padding: 0 !important;
vertical-align: top
}
.hljs-ln .hljs-ln-numbers {
user-select: none;
text-align: right;
color: var(--muted);
padding: 0 .75rem 0 1rem !important;
border-right: 1px solid var(--border);
width: 2.75rem;
min-width: 2.75rem;
}
.hljs-ln .hljs-ln-code {
padding-left: .75rem !important;
}
/* Toast */
.td-codeblock {
position: relative;
margin: 1rem 0;
border: 1px solid var(--border);
border-radius: 14px;
background: var(--cbg);
box-shadow: 0 6px 24px var(--ring);
overflow: hidden;
}
.td-toast {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
background: rgba(20, 180, 120, .12);
color: #00c389;
border: 1px solid rgba(0, 195, 137, .35);
padding: .5rem .75rem;
border-radius: 10px;
display: none;
z-index: 3;
pointer-events: none;
}
.td-toast.show {
display: block;
animation: td-fade 1.6s ease forwards;
}
.td-toast {
left: auto;
right: 12px;
transform: none;
}
@keyframes td-fade {
0% {
opacity: 0;
transform: translateY(6px)
}
15%,
80% {
opacity: 1;
transform: translateY(0)
}
100% {
opacity: 0
}
}
</style>
The Syntax Highlighting by TruongDevs head section of your HTML document is where you include metadata, external resources, and styling for your page. To style a code box:
-
You add CSS styles in the head section.
-
CSS defines how your code box will look, including background color, text color, font, padding, borders, and scroll behavior.
-
Any additional styling, such as custom fonts or syntax highlighting, should also be included in the head.
By keeping the styles in the head section, you ensure that the design is applied consistently throughout your website. This also makes it easier to update the appearance of your code boxes in the future.
2. Using the </body> Paste Section
<!-- highlight.js core + line numbers plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.8.0/highlightjs-line-numbers.min.js"></script>
<script>
/*! LuxTechZone CodeBlock UX — Compact toolbar (Copy · Open · Download · CodePen), Lines ON */
(function(){
const LANGUAGE_MAP = {
'markup':'html','html':'html','xml':'xml','css':'css','scss':'scss','sass':'sass','less':'less','stylus':'styl',
'javascript':'js','js':'js','jsx':'jsx','typescript':'ts','ts':'ts','tsx':'tsx',
'json':'json','yaml':'yml','yml':'yml','toml':'toml','ini':'ini','properties':'properties',
'bash':'sh','shell':'sh','zsh':'sh','powershell':'ps1','ps':'ps1',
'sql':'sql','graphql':'graphql','gql':'graphql',
'python':'py','py':'py','java':'java','kotlin':'kt','swift':'swift',
'c':'c','cpp':'cpp','c++':'cpp','h':'h','hpp':'hpp',
'csharp':'cs','cs':'cs','vbnet':'vb','visual-basic':'vb',
'go':'go','golang':'go','rust':'rs','dart':'dart','php':'php','ruby':'rb',
'r':'r','matlab':'m','fortran':'f90','scala':'scala','haskell':'hs','clojure':'clj','lisp':'lisp','scheme':'scm','ocaml':'ml',
'elixir':'ex','erlang':'erl','fsharp':'fs','prolog':'pl','julia':'jl','groovy':'groovy','perl':'pl','lua':'lua','nim':'nim',
'docker':'dockerfile','dockerfile':'dockerfile','nginx':'nginx','apacheconf':'conf','makefile':'mk','cmake':'cmake','diff':'diff','git':'git',
'abap':'abap','actionscript':'as','ada':'ada','apl':'apl','applescript':'applescript','arduino':'ino','arff':'arff','asciidoc':'adoc',
'asm6502':'asm','aspnet':'cshtml','autohotkey':'ahk','autoit':'au3','basic':'bas','batch':'bat','bison':'bison','brainfuck':'b','bro':'bro',
'csp':'csp','css-extras':'css','d':'d','django':'jinja','eiffel':'e','elm':'elm','erb':'erb',
'flow':'js','gedcom':'ged','gherkin':'feature','glsl':'glsl','gml':'gml','haml':'haml','handlebars':'hbs','haxe':'hx','hpkp':'hpkp','hsts':'hsts',
'ichigojam':'ijm','icon':'icn','inform7':'ni','io':'io','j':'j','jolie':'ol','keyman':'kmn','latex':'tex','liquid':'liquid',
'livescript':'ls','lolcode':'lol','mel':'mel','mizar':'miz','monkey':'monkey','n4js':'n4js','nasm':'asm','nix':'nix','nsis':'nsi',
'objectivec':'m','opencl':'cl','oz':'oz','parigp':'gp','parser':'pegjs','pascal':'pas','plsql':'sql','processing':'pde','protobuf':'proto',
'pug':'pug','puppet':'pp','pure':'pure','q':'q','qore':'q','reason':'re','renpy':'rpy','rest':'rst','rip':'rip','roboconf':'graph',
'sas':'sas','smarty':'tpl','soy':'soy','tap':'tap','tcl':'tcl','textile':'textile','tt2':'tt2','twig':'twig','velocity':'vm','verilog':'v','vhdl':'vhd',
'vim':'vim','wiki':'wiki','xeora':'xeora','xojo':'xojo','xquery':'xq','wasm':'wasm'
};
const NORMALIZE = { 'htm':'html','shell':'bash','sh':'bash','plaintext':'text','plain':'text','objective-c':'objectivec','c#':'csharp','c++':'cpp' };
const icons = {
copy:'<svg viewBox="0 0 24 24" fill="none"><path d="M9 9.5A2.5 2.5 0 0 1 11.5 7H18a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-6.5A2.5 2.5 0 0 1 9 17.5v-8Z" stroke="currentColor" stroke-width="1.5"/><path d="M6 15.5A2.5 2.5 0 0 1 3.5 13V6a2 2 0 0 1 2-2H12a2 2 0 0 1 2 2" stroke="currentColor" stroke-width="1.5"/></svg>',
open:'<svg viewBox="0 0 24 24" fill="none"><path d="M14 5h5v5M10 14 19 5M13 10H6a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-7" stroke="currentColor" stroke-width="1.5"/></svg>',
download:'<svg viewBox="0 0 24 24" fill="none"><path d="M12 3v11m0 0 3-3m-3 3-3-3M4 21h16" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>',
codepen:'<svg viewBox="0 0 24 24" fill="none"><path d="M12 3 3 9v6l9 6 9-6V9l-9-6Zm0 0v18M3 9l9 6m9-6-9 6M3 15l9-6m9 6-9-6" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>'
};
function getLangAndExt(codeEl){
let lang = 'text';
for (const cls of codeEl.classList){ if (cls.startsWith('language-')){ lang = cls.replace('language-','').toLowerCase(); break; } }
lang = NORMALIZE[lang] || lang;
const ext = LANGUAGE_MAP[lang] || (lang==='text' ? 'txt' : lang);
return { lang, ext };
}
const esc = s => s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''');
function toast(wrap,msg){ const t = wrap.querySelector('.td-toast'); t.textContent = msg; t.classList.remove('show'); void t.offsetWidth; t.classList.add('show'); }
function enhance(code){
const pre = code.parentElement;
const wrap = document.createElement('div'); wrap.className = 'td-codeblock';
pre.replaceWith(wrap);
const {lang, ext} = getLangAndExt(code);
const fileName = code.dataset.filename || `snippet.${ext}`;
const bar = document.createElement('div');
bar.className = 'td-codebar';
bar.innerHTML = `
<div class="td-filemeta">
<span class="td-dot" aria-hidden="true"></span>
<span class="td-lang">${lang}</span>
<span class="td-fname" title="${fileName}">${fileName}</span>
</div>
<div class="td-actions">
<button class="td-btn td-copy" title="Copy" aria-label="Copy">${icons.copy}<span class="td-label">Copy</span></button>
<button class="td-btn td-open" title="Open in new tab" aria-label="Open">${icons.open}<span class="td-label">Open</span></button>
<button class="td-btn td-download" title="Download" aria-label="Download">${icons.download}<span class="td-label">Download</span></button>
<button class="td-btn td-codepen" title="Open on CodePen" aria-label="CodePen">${icons.codepen}<span class="td-label">CodePen</span></button>
</div>`;
const area = document.createElement('div'); area.className = 'td-code'; area.appendChild(pre);
const toastEl = document.createElement('div'); toastEl.className = 'td-toast'; toastEl.textContent = 'Copied!';
wrap.appendChild(bar); wrap.appendChild(area); wrap.appendChild(toastEl);
const originalText = code.textContent; // để copy/download không dính số dòng
// highlight + line numbers
if (window.hljs) hljs.highlightElement(code);
if (window.hljs && window.hljs.lineNumbersBlock){ try{ window.hljs.lineNumbersBlock(code); }catch(e){} }
// actions
bar.querySelector('.td-copy').addEventListener('click', async ()=>{
try{ await navigator.clipboard.writeText(originalText); toast(wrap,'Copied!'); }
catch{
const ta = document.createElement('textarea'); ta.value = originalText; document.body.appendChild(ta);
ta.select(); try{ document.execCommand('copy'); toast(wrap,'Copied!'); } catch{ toast(wrap,'Copy failed'); }
ta.remove();
}
});
bar.querySelector('.td-open').addEventListener('click', ()=>{
const w = window.open('', '_blank');
w.document.write(`<!doctype html><meta charset="utf-8"><title>${fileName}</title>
<style>body{margin:0;background:#0b1221;color:#e6edf3}
pre{white-space:pre-wrap;padding:16px;font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}</style>
<pre>${esc(originalText)}</pre>`);
w.document.close();
});
bar.querySelector('.td-download').addEventListener('click', ()=>{
const blob = new Blob([originalText],{type:'text/plain;charset=utf-8'});
const url = URL.createObjectURL(blob);
const a = Object.assign(document.createElement('a'),{href:url,download:fileName});
document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
});
bar.querySelector('.td-codepen').addEventListener('click', ()=>{
const lower = lang.toLowerCase();
const isHTML = ['markup','html','xml','svg','pug','haml'].includes(lower);
const isCSS = ['css','scss','sass','less','stylus','styl'].includes(lower);
const isJS = ['javascript','js','jsx','ts','typescript','tsx'].includes(lower);
const data = { title:`CodePen - ${lang} snippet`, html:'', css:'', js:'' };
if (isHTML) data.html = originalText;
else if (isCSS) data.css = originalText;
else if (isJS) data.js = ['ts','typescript','tsx'].includes(lower) ? `// TS/TSX snippet\n${originalText}` : originalText;
else data.html = `<pre>${esc(originalText)}</pre>`;
const form = document.createElement('form');
form.method='POST'; form.action='https://codepen.io/pen/define'; form.target='_blank';
const input = document.createElement('input'); input.type='hidden'; input.name='data'; input.value=JSON.stringify(data);
form.appendChild(input); document.body.appendChild(form); form.submit(); form.remove();
});
// double-click: select toàn bộ code
area.addEventListener('dblclick', ()=>{
const range = document.createRange(); range.selectNodeContents(code);
const sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range);
});
}
document.addEventListener('DOMContentLoaded', ()=>{
document.querySelectorAll('pre > code').forEach(enhance);
});
})();
</script>
The body section contains the actual content of your page. To display a code snippet:
-
You create a container for your code, usually using HTML elements that preserve formatting, such as a preformatted block or a semantic code element.
-
You place your actual code inside this container.
-
You can optionally add classes or IDs to the container to connect it with the styles defined in the head section.
This approach allows you to separate structure (body) from design (head), which is a good practice in web development.
3. Step-by-Step Process Make a code Box
-
Define Styles in the Head:
-
Decide on colors, font, and spacing for your code box.
-
Include any extra styling for scrolling, borders, or syntax highlighting.
-
Add Code in the Body:
-
Test on Different Devices:
4. Best Practices
-
Keep styling in the head to make maintenance easier.
-
Avoid inline styles directly in the body unless necessary.
-
Use a monospace font for proper code alignment.
-
Make the code box scrollable if lines are long.
-
Optionally, use external libraries for syntax highlighting if you frequently display large code snippets.
5. Conclusion
By separating the styling in the head and the content in the body, you can create a clean, professional code box for your website. This method enhances readability, keeps your code organized, and ensures that your website maintains a consistent look across all pages. Following these steps allows anyone to easily integrate stylish code boxes into their blogs or websites without disrupting the existing layout.