【问题标题】:Embedding a font into CSS, but the font does not show up in html file将字体嵌入到 CSS 中,但字体未显示在 html 文件中
【发布时间】:2022-01-04 20:35:09
【问题描述】:

这里的过程有点困惑,但我尝试将新字体嵌入到 html 网站的 CSS 文件中,但无论我尝试什么,该字体都不会出现在 html 网站上。我已经将字体通过转换器,然后将整个文件放入我的 CSS 文件夹中,该文件夹与我的 index.html 位于同一文件中,但无济于事。这是我放入 CSS 中的代码:

    font-family: 'Montserrat';
    src: url('Montserrat-SemiBold.woff2') format('woff2'),
        url('Montserrat-SemiBold.woff') format('woff'),
        url('Montserrat-SemiBold.ttf') format('truetype');
    font-weight: 600;
    font-style: normal;
    font-display: swap;

有什么办法可以让代码正确显示吗?

【问题讨论】:

    标签: html css font-embedding


    【解决方案1】:

    从这里开始: https://www.w3schools.com/cssref/css3_pr_font-face_rule.asp

    你好世界示例

    您应该添加一个CSS selector(选择元素)body,例如:

    <!DOCTYPE HTML>
    
    <html>
    
    <head>
        <style>
            @font-face {
                font-family: 'hello-font';
                font-weight: 600;
                /* Use chrome inspect and check if the path is correct */
                src: url(hello-font.woff2) format('woff2');
            }
            /* missing in your styles */
            body {
                font-family: 'hello-font', sans-serif;
            }
        </style>
        <title>Your Website</title>
    </head>
    
    <body>
        <h1>hello world</h1>
    </body>
    
    </html>
    

    “找不到文件”

    无论如何,如果您使用本地文件 - 无法知道路径/文件名是否正确没有实时 URL(Chrome 检查 red 错误) - 错误示例:

    选项 2(更好) - 通过 CDN 加载 google 字体

    ** 更好的速度性能/更易于维护。

    <html>
      <head>
        <link rel="stylesheet"
              href="https://fonts.googleapis.com/css?family=Tangerine">
        <style>
          body {
            font-family: 'Tangerine', serif;
            font-size: 48px;
          }
        </style>
      </head>
      <body>
        <div>Making the Web Beautiful!</div>
      </body>
    </html>

    【讨论】:

    • 非常感谢您帮助我!我很欣赏这些选项和解释,这非常有帮助。
    • 太棒了 :) 如果答案解决了您的问题,请将答案标记为“解决方案”。谢谢!
    【解决方案2】:

    您应该添加@font-face 关键字来导入字体 See this example

    【讨论】:

    • 感谢输入,但是添加后,字体仍然没有出现在html文件中。
    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多