CKEditor 4.x表格数据冗余空间问题及单元格上下空白去除方法
Hey there! I've dealt with this exact issue in CKEditor 4.x a bunch of times—those extra vertical spaces in table cells can be super frustrating. Let me walk you through the most reliable fixes to get rid of them:
CKEditor 4 comes with built-in padding, margin, and line-height styles for tables that often cause extra spacing. You can override these with custom CSS:
- Open your CKEditor configuration file (usually
config.js) - Add this line to load your custom styles into the editor's content area:
config.contentsCss = '/path/to/your/custom-table-styles.css'; - In your
custom-table-styles.cssfile, add these rules to strip excess spacing:
Note: Thetable td, table th { padding: 0 !important; margin: 0 !important; line-height: 1.2em !important; /* Tweak this if text still feels spaced out */ } table { border-collapse: collapse !important; border-spacing: 0 !important; }!importantflag helps overwrite CKEditor's default styles, but if you load your CSS after the editor's default styles, you might not need it.
If you don't want a global fix, you can tweak individual tables through the editor's UI:
- Right-click the problematic table in CKEditor
- Select Table Properties from the menu
- Switch to the Cells tab
- Set both Cell padding and Cell spacing to
0 - Hit OK to apply the changes
Often, extra vertical space comes from CKEditor automatically wrapping cell content in <p> tags (which have default margins). You can fix this with two approaches:
- Global change: Make the enter key insert
<br>instead of<p>everywhere in the editor:config.enterMode = CKEDITOR.ENTER_BR; - Targeted change: Only prevent
<p>tags inside table cells (safer if you need<p>tags elsewhere):
Warning: The global enter mode change might alter how content behaves outside tables—test it first if you go that route.config.protectedSource.push(/<td[^>]*>[\s\S]*?<\/td>/gi); config.forcePasteAsPlainText = true; // Also prevents <p> tags when pasting content
If you already have tables with unwanted <p> tags or spacing, use CKEditor's content filter to strip them automatically:
- Add this to your
config.jsto remove<p>tags inside table cells:config.filteredHtmlRules = { elements: { td: function(element) { for (let i = 0; i < element.children.length; i++) { const child = element.children[i]; if (child.name === 'p') { element.children.splice(i, 1, ...child.children); i--; } } return element; } } };
内容的提问来源于stack exchange,提问作者sam

