resting
resting

Reputation: 17467

Underscores font-size mixin

I'm using the underscores starter theme for wordpress.

They have this mixin which I've no idea what it's trying to do.

// Rem output with px fallback
@mixin font-size($sizeValue: 1) {
    font-size: ($sizeValue * 16) * 1px;
    font-size: $sizeValue * 1rem;
}

Can someone explain the math behind this?
How can I make use of it if I'm given font sizes in px?

Upvotes: 0

Views: 1110

Answers (2)

wellagain
wellagain

Reputation: 409

It just outputs your font size in rem with pixel fallback ('16' is the base font size here). If you use @include font-size(1.2), it will output:

font-size: 19.2px; // fallback for those with no rem support
font-size: 1.2rem;

This mixin is not suitable for converting font-size in pixels to rem.
If you want to write your code in pixels and have them converted to rem, the mixin should look something like this:

@mixin font-size-px-to-rem($value: 12) {
  font-size: $value * 1px;
  font-size: $value / 16 * 1rem;
}

then use it:

.test {
  @include font-size-px-to-rem(14);
}

which outputs to:

.test {
  font-size: 14px;
  font-size: 0.875rem;
}

Upvotes: 2

Karl Dawson
Karl Dawson

Reputation: 977

Blimey, that's a bit more abstraction than is needed. It's a little bit of work to swap out, but this is the mixin I use:

$base-font-size: 16;

@mixin font-size-rems($target-px-size) {
    $rem-size: $target-px-size / $base-font-size;
    font-size: $target-px-size * 1px;
    font-size: $rem-size * 1rem;
}

I then use it like this:

.example {
    @include font-size-rems(24);
}

Which outputs:

.example {
   font-size: 24px;
   font-size: 1.5rem;
}

Upvotes: 0

Related Questions