为什么附加文本的字体系列会在可编辑 div 中发生变化?

Why does the appended text's font family change in an editable div?

* {
  font-family: sans-serif;
}

.sample {
  font-family: monospace !important;
}

.sample>* {
  font-family: monospace !important;
}
<div class="sample" contenteditable>
  This is not inside span. <span>Go to the next line and append some text to see inconsistent effects.</span>
</div>

尝试做更多的编辑只会暴露出更多的不一致性。如何解决?如何将monospace字体设置为div内的所有文字?我尝试删除 !important,但无济于事。

删除 <span> 是一个选项,但我不能在我正在处理的原始项目中这样做,因为这些元素具有特定的格式。我也不能删除 * 规则声明,因为我想要 div 之外的 sans-serif 字体。很烦人,两者都解决了问题。还有其他方法吗?

> 选择直系子代。创建新行时,您会注意到 span 标记被包裹在 div.

相反,您可以尝试选择 .sample 的所有 span 个子元素:

* {
  font-family: sans-serif;
}

.sample {
  font-family: monospace !important;
}

.sample span {
  font-family: monospace !important;
}
<div class="sample" contenteditable>
  This is not inside span. <span>Go to the next line and append some text to see inconsistent effects.</span>
</div>

问题在于,通过定义 .sample>* 字体将仅应用于直接子项,不包括所有其他子项。如果你检查跳转到新行并写东西的结果,你会看到它创建了一个新的 div 和一个新的跨度层,这就是你的 CSS 没有被应用的原因。如果您只是将 .sample>* 更改为 .sample *,它将按预期工作。

* {
  font-family: sans-serif;
}

.sample {
  font-family: monospace !important;
}

.sample * {
  font-family: monospace !important;
}
<div class="sample" contenteditable>
  This is not inside span. <span>Go to the next line and append some text to see inconsistent effects.</span>
</div>