咨询Material Design Lite无法使用自定义字体的解决办法
Hey there, let's fix this custom font issue with Material Design Lite (MDL) together. The problem you're hitting is totally common—MDL's default styles have specific font-family rules that override your custom font when you include its CSS file. Here's how to resolve it step by step:
调整CSS引入顺序
CSS follows the "last defined wins" rule, so make sure your custom font's CSS file is included after MDL'smaterial.min.css. This way your font styles will take precedence over MDL's defaults. Example:<link rel="stylesheet" href="css/material.min%202.css" /> <!-- 你的自定义字体CSS放在MDL样式之后 --> <link rel="stylesheet" href="css/your-custom-font-styles.css" />提升自定义字体选择器的优先级
MDL uses specific selectors for its core elements (like buttons, inputs, and headings), so you need to make your font rules more specific to override them. You can target common MDL elements directly:/* 覆盖MDL核心元素的字体 */ body, h1, h2, h3, h4, h5, h6, button, input, textarea, .mdl-button, .mdl-textfield__input { font-family: '你的自定义字体名称', sans-serif; }If that still doesn't work, you can use
!importantas a last resort (though it's better to avoid overusing it):body { font-family: '你的自定义字体名称', sans-serif !important; }修改MDL的预编译变量(如果使用Sass/LESS版本)
If you're using MDL's pre-built Sass or Less files, you can replace the default font variables directly at the source, so you don't need to write override styles. For Sass:// 先定义你的自定义字体变量 $mdl-font-primary: '你的自定义字体名称', sans-serif; $mdl-font-secondary: '你的自定义字体名称', sans-serif; // 再引入MDL的核心样式 @import 'material-design-lite/src/material-design-lite';
Why this happens
MDL's default styles set font-family: 'Roboto', 'Helvetica', 'Arial', sans-serif; on many core elements (body, buttons, inputs, etc.). When you include MDL's CSS before your custom font styles, these rules overwrite your font settings. Adjusting the order and selector specificity fixes this conflict.
内容的提问来源于stack exchange,提问作者Ade Guntoro

