Adam Prescott

Styling specific characters with unicode-range

This completely passed me by, even though 24 ways covered it.

Tucked into @font-face is a unicode-range property that lets you restrict the range of characters used by the specified font. So say you want ampersands with a flourish within your otherwise normal text, then — to steal from the 24 ways article — you can:

@font-face {
    font-family: 'Ampersand';
    src: local('Baskerville'), local('Palatino'), local('Book Antiqua');
    unicode-range: U+26;
}

Now instead of relying on <span class="ampersand">&</span> added with some JavaScript, you just use the Ampersand font in your font-family values:

p {
    font-family: Ampersand, Georgia, "Your Favourite Web Font", serif;
}

The Ampersand font is restricted to ampersand characters, so the browser will fall back to Georgia otherwise.

Web fonts and a lack of nested @font-face

If you’re thinking of using Google Web Fonts for your ampersand-only font, you can avoid transferring the entire set of characters by restricting it to just the & (which is %26 when encoded):

http://fonts.googleapis.com/css?family=WhateverFont&text=%26

But… with or without this, it won’t work.

The CSS returned by Google doesn’t use unicode-range (understandably), and unfortunately it seems you can’t chain @font-face font names. Imagine you’ve used WhateverFont from Google with a <script> (although @import has the same problem):

<link
 href='http://fonts.googleapis.com/css?family=WhateverFont&amp;text=%26'
 rel='stylesheet' type='text/css'>

You can’t refer to a web font, in this case WhateverFont, from within @font-face rule:

@font-face {
  font-family: "Ampersand";
  src: local("WhateverFont"); /* doesn't work! */
  unicode-range: U+26;
}

local() uses the locally installed fonts, and @font-face (which is what the above <script> or an @import give you) doesn’t actually install the font, it just makes it available. There’s simply no way to refer to “Whatever Font” as a src value. You have to control all the CSS for this to work.


Update: I proposed making something like this valid on the www-style mailing list:

/* Pull in the @font-face from Google */
@import(http://fonts.googleapis.com/css?family=WhateverFont)

/* Restrict "Whatever Font" to only ampersands. No src required: */
@font-face {
  font-family: "Whatever Font";
  unicode-range: U+26;
}

Or, allow @font-face “chaining” with renames:

@font-face {
  font-family-src: "Whatever Font";
  font-family: "Ampersand";
  unicode-range: U+26;
}

But without this, you can get around the problem by grabbing Google Web Font’s @font-face served up by http://fonts.googleapis.com/css?family=X and hoping it doesn’t break on you. Then you control all the CSS and you can add your own unicode-range property.