Is it possible to load an external font via inline CSS?
Note: I'm not talking about using an external CSS file with a @font-face
definition, but rather something like the following:
<h1 style="font-family:myfont;
src:('http://example.com/font/myfont.tff')">test</h1>
Yes, you can base64 encode a font or fonts as shown in this article from Stephen Scaff and drop them into a
style
block in your page to avoid the external request.It may also be possible to use this technique in the way you describe if the browser you're using supports it.
Every modern browser supports WOFF2, so you should probably use that and only that for the foreseeable future. Also, this technique will improve your page speed scores, but will degrade performance overall (even for first page loads), unless you're only base64-encoding critical page assets (e.g. glyphs of the font shown above the fold) and asynchronously load the rest.
Performance-wise your best bet right now is to use Brotli compression and pipe the webfont stylesheet down with HTTP/2 Server Push.
No, not that I know of. You will need to declare this kinds of things on a
<style>
block or an external CSS file.Though if you want something like this, it's very probable you're doing it wrong.
You cannot include a
@font-face
rule in astyle
attribute (which is “inline CSS” in the most narrow sense). By the HTML 4.01 specification, you cannot include such a rule inside thebody
element at all (“inline CSS” in a broader sense, which includesstyle
elements). But in practice it is possible.In practice, if you include a
style
element insidebody
, it will be processed by browsers just as if it were in the syntactically correct place, i.e. inside thehead
element. It even works “backwards”, effecting elements appearing before it.You can even make this approach – which should be used only if you cannot change the
head
– formally correct as per HTML5 CR. It allows astyle
element at the start of any element with flow content as its content model. Current browsers ignore thescoped
attribute.Update: the following is not relevant any more, since the validator bug has been fixed.
However, there is a bug in the W3C Markup Validator and in validator.nu: they disallow
style
at the start ofbody
. To overcome this bug, and to make your document validate in addition to being valid, you can use an extradiv
element:If you use @font-face, you should be able to do something like this:
CSS
}
Make sure to include the fonts - the above example has placed all of the fonts in a relative-path directory to the css file.
HTML
You should be able to find free web-based @font-face fonts here.