- Extending Sass
- Sass - Output Style
- Sass - Function Directives
- Sass - Mixin Directives
- Control Directives & Expressions
- Sass - @-Rules and Directives
- Sass - Script
- Sass - Comments
- Sass - CSS Extensions
- Using Sass
- Sass - Syntax
- Sass - Installation
- Sass - Overview
- Sass - Home
Sass Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Sass - Function Directives
In this chapter, we will study about Function Directives. In SASS, you can create your own function and use them in your script context or can be used with any value. Functions are called by using the function name and with any parameters.
Example
The following example demonstrates the use of function directive in the SCSS file −
function_directive.htm
<html> <head> <title>Nested Rules</title> <pnk rel = "stylesheet" type = "text/css" href = "style.css" /> <pnk rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/pbs/jquery/2.1.3/jquery.min.js"></script> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </head> <body> <span class = "container" id = "set_width"> <h2>Example for Function directives</h2> <p>SASS stands for Syntactically Awesome Stylesheet. </p> </span> </body> </html>
Next, create file style.scss.
style.scss
$first-width: 5px; $second-width: 5px; @function adjust_width($n) { @return $n * $first-width + ($n - 1) * $second-width; } #set_width { padding-left: adjust_width(10); }
You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −
sass --watch C: ubypbsassstyle.scss:style.css
Next, execute the above command; it will create the style.css file automatically with the following code −
style.css
#set_width { padding-left: 95px; }
Output
Let us carry out the following steps to see how the above given code works −
Save the above given html code in function_directive.html file.
Open this HTML file in a browser, an output is displayed as shown below.
In the output, you can see that the left-padding is being appped.
Just pke mixin, function can also access globally defined variables and can also accept parameters. You should call the return value for the function by using @return. We can call the SASS-defined functions by using keyword parameters.
Call the above function as shown below.
#set_width { padding-left: adjust_width($n: 10); }
Naming Conventions
To avoid naming confpcts function names can be prefixed so that they can be easily differentiated. Like mixins, variable arguments are also supported by user-defined functions. Functions and other SASS identifiers can use underscores(_) and hyphens(-) interchangeably.
For example, if a function is defined as adjust_width, it can be used as adjust-width, and vice versa.
Advertisements