Imran Bughio
Imran Bughio

Reputation: 4941

Sass - Check which kind of value a variable has

Suppose i have a variable:

$var: 5px;

but somewhere in code its value have changed in to possible color, number, em, rm etc.

Is there any function to detect which type of value it has?

i.e

@if is-color($var) { //do something }

I know there is no is-color function in sass but are there other methods to do this or function?

Upvotes: 24

Views: 24053

Answers (2)

mpemburn
mpemburn

Reputation: 2884

To be a little clearer, here's how you might use type-of:

@if type-of($my-variable) == string {
    /* do something */
}

In addition to the types shown in the docs, type-of will also return 'map' if passed a SASS map object:

$font-sizes: (
    small: rem-calc(18px),
    medium: rem-calc(20px),
    large: rem-calc(22px)
);

@if type-of($font-sizes) == map {
    /* do map-related thing */
} @else {
    /* do other thing */
}

Upvotes: 13

cimmanon
cimmanon

Reputation: 68339

From the Sass documentation:

type_of($value)

Returns the type of a value.

Examples:

type-of(100px)  => number
type-of(asdf)   => string
type-of("asdf") => string
type-of(true)   => bool
type-of(#fff)   => color
type-of(blue)   => color

http://sass-lang.com/documentation/Sass/Script/Functions.html#type_of-instance_method

(note that - and _ is interchangeable in Sass functions).

Upvotes: 43

Related Questions