rows and cells. Add optional attributes like class, id, borders, and accessibility features.
Technical Details
Semantic structure: . Accessibility: scope="col/row" on headers, caption element, summary attribute (deprecated). CSS styling preferred over HTML attributes (border, cellpadding).
Common Use Cases
- Data Display: Convert spreadsheet data to HTML tables.
- Example:
CSV data → HTML table
- Documentation: Create tables for technical documentation.
- Email Templates: Generate HTML tables for email layouts.
- Static Sites: Create data tables for Jekyll, Hugo sites.
Code Examples
Generate HTML Table
function generateTable(data, headers, options = {}) {
const { className, id, border } = options;
let html = '<table';
if (className) html += ` class="${className}"`;
if (id) html += ` id="${id}"`;
if (border) html += ' border="1"';
html += '>\n';
// Headers
if (headers && headers.length) {
html += ' <thead>\n <tr>\n';
headers.forEach(header => {
html += ` <th scope="col">${escapeHtml(header)}</th>\n`;
});
html += ' </tr>\n </thead>\n';
}
// Body
html += ' <tbody>\n';
data.forEach(row => {
html += ' <tr>\n';
row.forEach(cell => {
html += ` <td>${escapeHtml(cell)}</td>\n`;
});
html += ' </tr>\n';
});
html += ' </tbody>\n</table>';
return html;
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Usage
const data = [
['Alice', '30', 'Engineer'],
['Bob', '25', 'Designer']
];
const headers = ['Name', 'Age', 'Role'];
generateTable(data, headers, { className: 'data-table' });
Generates accessible HTML table with proper structure. Escapes content to prevent XSS.
Tips & Best Practices
- Always use thead/tbody for proper semantics
- Add scope attribute to header cells
- Escape user content to prevent XSS
- Use CSS for styling, not HTML attributes
- Include caption for accessibility
Common Mistakes to Avoid
- Missing thead/tbody structure
- Using tables for page layout
- Not escaping cell content
- Overusing colspan/rowspan
- Ignoring mobile responsiveness
When to Use This Tool
Use HTML table generator when creating data tables from CSV/JSON, generating documentation tables, or building email templates.
Frequently Asked Questions
Should I use CSS or HTML attributes?
CSS is preferred. Avoid deprecated attributes like border, cellpadding, bgcolor. Use CSS for styling: border-collapse, padding, background-color. HTML attributes may be needed for email clients.
How do I make tables accessible?
Add for table title, scope="col/row" on headers, use / |