2019-05-01+net

(Brent) #1
COMBINING
JAVASCRIPT AND
VARIABLE FONTS

We can make use of JavaScript events for
situations where we want more fine-tuned
control or to change the font based on
events that we cannot access with CSS
alone. A simple example would be matching
our font weight to the size of our viewport –
as the viewport gets smaller, the font weight
gets heavier.
In order to create the fluid scale, we must
align two sets of values and units – the font
weight and the viewport size. We can access
the current viewport width using window.
innerWidth and create a new percentage-
based scale by converting it to a range of
0–0.99. By including the minimum and
maximum viewport sizes we can control the
range of the effect.

var viewportScale =
(window.innerWidth - minWindowSize) /
(maxWindowSize - minWindowSize);

We then determine the font weight based on
our viewport size.

var fontWeightScale = viewportScale
* (minFontWeight - maxFontWeight) +
maxFontWeight;

Using CSS custom properties, we can use
our JavaScript value to update the font
weight in our CSS.
p.style.setProperty(“--weight”,
fontWeightScale);

When this is combined into a function and
attached to the resize event listener, we can
update the font weight based on the new
size of the window.
With this basic approach, we’re able to
modify our typography based on all manner
of events and experiences. Where the
viewport is wide we can have more detail;
conversely, when it’s smaller and in a more
confined space, we might look at reducing
the font width or increasing the weight,
providing better control of our content and
typography in terms of legibility, usability
and design.

View the code for this on CodePen (https://
Opposite With codepen.io/mandymichael/pen/oPoaEL).
variable fonts, different
weights are contained
within one file


Top Variable fonts
make it possible to use
CSS to achieve various
text effects

Middle Weight
variations are defined
on an axis, from light
(200) to black (900)

Above Variable
fonts enable smooth
transitions from, say, a
thin to a bold weight

Variable fonts

Free download pdf