Ivan Viper Navarro
Ivan Viper Navarro

Reputation: 11

Custom font with css not work in Sphinx project

I maked a Sphinx (Readthedocs) project with custom font.

Exported - http://1ra-manual-dentrenament-basic-de-combat.readthedocs.io/ca/latest/

Github - https://github.com/CavallersDelCel/1RA_EBC/blob/master/docs/index.rst

Custom font in _static/fonts/LinBiolinum_Kah.ttf

I have a _static/css/custom.css with:

@font-face {
    font-family: "Linux Biolinum Keyboard";
    src: url(../fonts/LinBiolinum_Kah.ttf);
}

.keys {
  font-family: "Linux Biolinum Keyboard", sans-serif;
}

In conf.py i have:

def setup(app):
    app.add_stylesheet('css/custom.css')

And in one page i write:

<span class="keys">FM</span>

But the result is a plain text with the tags, not text with the custom font:

html result

Upvotes: 1

Views: 1236

Answers (2)

Harry Howard
Harry Howard

Reputation: 111

There is a simpler and more precise way to do this.

Let me review the background, mostly from the question:

  1. Transfer the font to the fonts folder. In my set-up, it is found in the build folder, build/_static/fonts.

  2. In source/_static/css/, create or edit a file custom.css.

  3. Add the lines:

     @font-face {
         font-family: "Linux Biolinum Keyboard";
         src: url(../fonts/LinBiolinum_Kah.ttf);
     }
    
     .keys {
         font-family: "Linux Biolinum Keyboard", sans-serif;
     }
    
  4. Assuming that you want HTML output, make sure that conf.py has these lines under "Options of HTML output":

     html_css_files = ['css/custom.css',]
     html_static_path = ['_static']
    

Now for the trick.

  1. In conf.py, define a role for the font in rst.prolog:

     rst_prolog = """
        .. role:: LBK
            :class: keys
     """
    
  2. This role can be invoked in any document in the project, in one of two ways:

a. by applying the role to a bit of text, eg.

    :LBK:`FM`

b. by appending the class option to a body element, eg.

    .. list-table:: My Table
        :header-rows: 1
        :widths: 20 20
        :class: keys

Upvotes: 0

Steve Piercy
Steve Piercy

Reputation: 15055

You have two issues.

  1. Docutils (the library that Sphinx uses to convert reStructuredText to HTML) converts quotes to their localized typographical version. In this case " gets converted to ».
  2. You expect that text does not get HTML-encoded, but Sphinx will convert HTML entities (< and >) from plain text to their HTML-encoded entities &lt; and &gt;.

To correct the issue in this case, you probably want to use the .. raw:: directive, like so:

.. raw:: html

    <span class="keys">FM</span>

...and then Sphinx should allow the HTML code to render properly.

Additionally if you want to show the source HTML code inline:

.. code-block:: html

    <span class="keys">FM</span>

Upvotes: 1

Related Questions