RAHUL KUNDU
RAHUL KUNDU

Reputation: 955

Creating a sass mixin with optional arguments

I am trying to create scss mixin for text styles, which includes color, font size, font weight, line height and font family. this is what i have done -

$color-gray-6: #777777;
$font-serif: 'Barlow', sans-serif;
$font-sans: 'Playfair Display', serif;


    @mixin font-style(
        $colour: $color-gray-6,
        $size: 1.6,
        $weight: 400,
        $line: $size * 1.5,
        $family: serif
    ) {
        @if $size {
            font-size: ($size * 1) + px;
            font-size: ($size / 10) + rem;
        }
        @if $line == 1 {
            line-height: 1;
        } @else {
            line-height: ($line * 1) + px;
            line-height: ($line / 10) + rem;
        }
        @if $colour {
            color: $colour;
        }
        @if $weight {
            font-weight: $weight;
        }
        @if $family == serif {
            font-family: $font-serif;
        } @else {
            font-family: $font-sans;
        }
    }

I am using the mixing as - @include font-style(#000000, 14, 400, sans)

Problem - When I am not passing line height getting this error - Undefined operation "sans * 1. I think when line height is not present it is treating font family as 4th parameter.

Question - Is there any way to make the 4th parameter optional, or if there is any better way please sugges.

Upvotes: 0

Views: 1274

Answers (1)

Nathan Dawson
Nathan Dawson

Reputation: 19338

The fourth parameter or your font-style() mixin is $line. You haven't skipped over it when you pass in sans as the argument. Instead you've taken what should be the fifth argument and made it the fourth.

The best approach you can take is to use "keyword arguments": https://sass-lang.com/documentation/at-rules/mixin#keyword-arguments

Essentially you need to tell the mixin which argument it is that you're supplying.

Example:

@include font-style(#000, 14, 400, $family: sans);

Upvotes: 1

Related Questions