【问题标题】:Why does the appended text's font family change in an editable div?为什么附加文本的字体系列在可编辑的 div 中会发生变化?
【发布时间】:2021-10-10 16:03:36
【问题描述】:
* {
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 字体。很烦人,两者都解决了问题。还有什么办法吗?
【问题讨论】:
标签:
html
css
contenteditable
font-family
【解决方案1】:
> 选择直系子级。创建新行时,您会注意到 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>
【解决方案2】:
问题在于,通过定义.sample>*,字体将仅应用于直接子级,不包括所有其他子级。如果你检查跳转到新行并写东西的结果,你会看到它创建了一个新的 div 和一个新的 span 层,这就是你的 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>