Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 828
Imran Bughio Avatar asked Apr 24 '14 18:04

Imran Bughio


People also ask

How do I change dynamic variables in SCSS?

SCSS is compiled to CSS during compile time, and SCSS variables are replaced with resolved value during compile time, which means there is no way to change the variable during run time. However, CSS variables just sits there during run time, and you can dynamically CRUD them during run time with JavaScript (Web API).

What is the correct way to define a variable in Sass?

The basic syntax for defining a variable is simple: Just use a $ before the variable name and treat its definition like a CSS rule: Sass Variable Syntax: $<variable name>:<value>; The following declares a variable named large-font.

Can Sass use CSS variables?

Sass variables are all compiled away by Sass. CSS variables are included in the CSS output. CSS variables can have different values for different elements, but Sass variables only have one value at a time.

What character is used to denote variables in Sass?

Sass uses $ to distinguish variables (such as $highlight-color , $sidebar-width ). The dollar sign was chosen because it's visually distinctive, it's aesthetically pleasing, and it's not used elsewhere in CSS and thus doesn't come into conflict with any present or future CSS syntax.


2 Answers

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).

like image 74
cimmanon Avatar answered Oct 03 '22 03:10

cimmanon


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 */
}
like image 43
mpemburn Avatar answered Oct 03 '22 02:10

mpemburn