Stylus : CSS Preprocessor Language
= CSS Preprocessor languages (like, less, sass, SCSS, etc...) are useful to make your styles more readable and more maintainable and easier to write style sheets for complex layouts or you can build your own CSS framework like, Bootstrap ( Based on less), and Foundation ( Based on Sass).
= So, You want to learn, What Stylus is and How it is so powerful.
= Before start learning Stylus Language, let's discuss what is offers and how to use those features.
= Stylus Syntax Rules:-
=> In Stylus, you are allowed to use the Syntax of either CSS or Stylus itself.
=> If You are using Stylus syntax, then there, curly braces, semi-colons, colons are optional.
Although you can use if you like them. Stylus dropped them because it's syntax is based on Indentation, just like in Python.
=>> You can use Stylus interactive REPL shell, that is great to play with Stylus functions.
=>> You can write a full Stylus code to Terminal and Stylus compile that and print to terminal. First run Stylus executable and then write your stylus code to terminal, when complete HIT the CTRL-D key, now you can see the compiled output. This technique is basically same as that (php -a) (PHP Interactive mode)
=>> If you want help regarding any CSS property, then you can use, This will open up a browser with a reference to that property from Mozilla website.
=> first learn the theory of Stylus and then we will take a look at its examples and demos.
= Comments in Stylus Style-sheet ( In compressed CSS comments and white-space will be removed.)
= Single line comments
( just like a JavaScript comments ( using '//' ), and will not be in resulting CSS)
= Multi-line Comments
( just like a regular CSS multi-line comment ( using '/* This is a CSS comment*/'))
= Multi-line buffered Comments
( Just like multi-line comments, but start with '/*! This is a buffered comment */')
= Multi-line buffered comment will be there in output CSS even if you had passed a compress flag for Stylus compiler.
= Defining ans using variable in Stylus Style-sheet (So, that you can use them later)
= A Stylus variable may be a single value (like, font = 12px) or a expression (like, font = "sans") or a expression list (like, font = 15px, "sans-serif")
= You can use a '$' prefix for Stylus variable name or functions names (like, $font = "sans-serif")
= Property reference ( Using the '@' operator)
= Stylus has a awesome feature so that you can refer properties defined earlier without defining the variable.
= Just append the '@' character before the Property name that you want to refer.
= returns 'nil' if property does not exists.
= Using CSS selectors and how to nesting of Selectors works
= Stylus use Indentation instead of curly-braces.
= You can nest as many as selectors you want.
= You can use multiple selectors at a time either use a comma ',' to separate them or in Stylus you can use a newline character.
= Parent Selectors Reference using '&' Operator
= You can refer to parent selectors using '&' operator.
= There may be one or more than one parent selectors based on Scope.
= Understand the difference between the indented parent selectors and parent selectors separated using Comma or newline.
= Indentation means nested selectors, and newline ( or comma) means multiple selectors.
= Root Selector Reference using '/' operator
= This is simply tell us, protect this selector from parent reference, use this as root context.
= Using selector() built-in function
= this built-in function returns the current compiled selector that can be used inside a mixin or function.
= Using the unquote() built-in function
= this return the value without quote, so that Stylus can process that values.
= Using Stylus built-in Operators (addition, subtraction, etc...)
= Unary Operators ( !, not, -, +, ~ )
= Binary Operators
= Additive ( +, - )
= Multiplicative ( /, *, % )
= Exponent ( **)
= Equality and Relational ( ==, !=, <=, >=, >, < )
= Logical Operator ( &&, ||, and, or )
= Existence Operator ( in )
= Conditional Assignment
( if variable exists than there is no need to reassign variable)
= These are equivalent.
color := white
color ?= white
color = color is defined ? color : white
= Instance check ( is a )
( example, 15 is a 'unit') ( means we are checking that does 15 belongs to unit class)
= Variable Definition ( is defined ) ( Does this variable is defined earlier)
= Ternary Operator ( $a = (conditional_expression) ? true : false )
= Color Operations
( rgb() or rgba() built-in function) (or we can simply use +, -, *, 12%, 45deg etc... operations)
= s() built-in function ( using '%' operator) ( same as sprintf() function is C/C++)
'X::Microsoft::Crap(%s)' % #fc0
// => X::Microsoft::Crap(#fc0)
= subscript Operator "[]"
( allow you to grab a value via index ( Zero-based), and negative index means start from end)
list = 1 2 3 4 5 6
tuple = (1 2 3 4)
tuple = (100px 200px)
list[0]
// 1
= Inclusive and Exclusive Ranges
1..5
// 1 2 3 4 5
1...5
// 1 2 3 4
5..1
// 5 4 3 2 1
= Stylus Interpolation Rules
= Stylus supports interpolation by using the {} characters to surround an expression.
= values inside this braces will be treated as Identifier.
= Conditionals statements (like, if, if else, unless )
= unless is basically opposite of if statement, and equal to if(!(condition_expression))
= Post-fix Conditionals
= note that if and unless both works as operator, means when right-hand expression/operand is truthy, they evaluates the left hand-expression/operand. this helps us to write one line conditional expressions.
= Using Hashes in Stylus (like, Dictionary in Python )
= You can define a hash using curly braces and comma to separate keys and values, note that keys should be either proper indented or a string value.
= if you want to add any key/value pair to pre-defined hash, then you can use brackets with string key.
= To get a value of any key from Hash you can use a dot (.) operator with hash name.
= hashes used inside a curly braces (means for interpolation) just returns hash values that can be used as CSS rules.
= Built-in length() function just returns its length.
= keys() and values() built-in functions, just returns a list of keys and values respectively.
= merge() or extend() are used to merge two hashes.
= Iteration or Loop functions in Stylus (like, for )
= Stylus Allow you to iterate expressions using for/in construct
= Syntax:-
for <value_name> [, <key_name>] in <expression>
body
for num in 1 2 3 4
foo num
body
for num in (1..5)
foo num
= Note that likewise if/unless, for also behaves post-fix operator.
= Using Mixins in Stylus style-sheets ( reusable block of CSS code that can optionally take parameters)
= Both mixins and functions are defined in same manner, but they are applied in different ways.
= When mixin is invoked within a selector, the properties are expanded and copied into the selector.
= Stylus Introspection API, Whenever you call a mixin, then a local variable name 'mixin' is automatically created with a string value 'root', this help you to find whether a function is invoked as a mixin or as a function.
= Using Transparent Mixins ( Mixins with unknown number of parameters )
= mixin defined without any parameters but uses the local variable 'arguments' variable that contain expression passes to it.
= thus allowing multiple values to be passed.
= Using Block Mixins
= You can pass blocks to mixins by calling the mixin with + prefix.
= use a local variable 'block' inside curly brackets to access passed blocks.
= Nesting Mixins inside Mixins
= Mixins can utilize other mixins, build upon their own selectors and properties.
= Defining and Using Functions ( function that can return a value )
= Function that can return value
add(a,b)
a + b
= Functions with default arguments
add(a, b=a) // b = a until you explicitly define a value for b
a + b
= Functions with named parameters
subtract(a, b)
a - b
subtract(b: 10, a: 25)
= Function that returns multiple values
= Stylus functions can return multiple values as you assign multiple value to a variable.
sizes = 15px 10px // Stylus variable with multiple values
sizes() // stylus function that return multiple values
15px 10px
= While returning multiple values from function either use parenthesis for values or use a return statement before them.
= Function with different name ( function Aliasing)
plus = add
plus(1,2) // returns 3
= Stylus Anonymous functions ( Using '@() {}' syntax)
= local variable 'arguments' is available to all function bodies, and contain all the arguments passed.
= Functions with Rest parameters (like, curry functions in Haskell)
= Stylus supports rest parameters in the form of 'name...' These params consume the remaining arguments passed to a mixin or function.
= Stylus Built-in Functions for you ( In Stylus there are over 60 Built-in function for you to use)
= red(color[, value])
return the red component of the given color, or set the red component to given value.
= green(color[, value])
return the green component of the given color, or set the green component to given value.
= blue(color[, value])
return the blue component of the given color, or set the blue component to given value.
= alpha(color[, value])
return the alpha component of the given color, or set the alpha component to given value.
= dark(color)
check if color is dark
= light(color)
Check if color is light
= hue(color[, value])
Return the hue of the given color or set the hue component to the optional argument value.
= saturation(color[, value])
Return the saturation of the given color or set the saturation component to the optional argument value.
= lightness(color[, value])
Return the lightness of the given color or set the lightness component to the optional argument value.
= push(expr, args...)
Push the given args to expr
= unshift(expr, args...)
Unshift the given args to expr
= keys(pairs)
Return keys in the given pair
= values(pairs)
Return the values in given pair
= list-separator(list)
Return the separator of the given list (for example, white-space, or a comma)
= typeof(node)
Return the type of node as a string
= unit(unit[, type])
Return a string for the type of unit or an empty string, or assign the given type without unit conversion.
unit(15in) // returns 'in' [inch]
= match(pattern, string)
Test if string matches the given pattern
= abs(unit) // absolute value
= ceil(unit) // nearest upper integer
= floor(unit) // nearest lower integer
= round(unit[, precision])
= sin(angle)
without any unit angle will be assumed as radians, you can explicitly use degrees as 45deg
= cos(angle)
= tan(angle)
= min(a, b) // comma separated two values
= max(a, b)
= even(unit)
= odd(unit)
= sum(nums)
supply a white-space separated list of numbers
= avg(nums)
= base-convert(num, base, width)
num, that you want to convert, base, with this base, and with this width
= join(delim, vals...)
= hsla(color | h,s,l,a)
Convert the given color to an HSLA node or h, s, l ,a component values.
= hsl(color | h, s, l)
= rgba(color | r,g, b, a)
Return RGBA from the r, g, b, a channels or provide a color to tweak the alpha.
= rgb(color | r, g, b)
= blend(top[, bottom])
Blends the given top color over the bottom one using the normal blending. The bottom argument is optional and is defaulted to #fff
= lighten(color, amount)
Lighten the given color by amount. This function is unit-sensitive. for example supporting percentages.
= darken(color, amount)
Darken the given color by amount, This function is unit-sensitive, for example supporting percentages.
= desaturate(color, amount)
Desaturate the given color by amount.
= saturate(color, amount)
Saturate the given color by amount.
= complement(color)
Gives the complementary color Equals to spinning HUE to 180deg.
= invert(color)
Inverts the color. The red, green, and blue values are inverted, while the opacity is left alone.
= grayscale(color)
Gives the grayscale equivalent of the given color, Equals to desaturate by 100%
= tint(color, amount)
Mix the given color with white.
= shade(color, amount)
Mix the given color with black.
= luminosity(color)
Returns the relative luminance of the given color.
= constrast(top[, bottom])
Returns the contrast ratio object between top and bottom colors,
The second argument is optional and is defaulted to #fff.
= transparentify(top[, bottom, alpha])
Returns the transparent version of the given top color, as if it was blend over the given bottom color
The second argument is optional and is defaulted to #fff.
= unquote(str | ident)
Unquote the given str and returned as a Literal node.
= convert(str)
Like unquote() but tries to convert the given str to a Stylus node.
= s(fmt, ...)
= basename(path[, ext])
Returns the basename of path, (optionally) with ext extension removed.
= dirname(path)
Returns the dirname of path
= extname(path)
Return the filename extension of path including the dot
= pathjoin(...)
Perform a path join
= called-from property
called-from property contains the list of the functions the current function was called from in the reverse order (the first item is the deepest function).
= current-media()
returns the string of the current block’s @media rule or '' if there is no @media above the block.
= +cache(keys...)
allows you to create your own “cachable” mixins.
= +prefix-classes(prefix)
Stylus comes with a block mixin prefix-classes that can be used for prefixing the classes inside any given Stylus’ block
= lookup(name)
Allows to lookup a variable with a given name, passed as a string. Returns null if the variable is undefined.
= define(name, expr)
Allows to create or overwrite a variable with a given name, passed as a string, onto current scope.
= operate(op, left, right)
Perform the given op on the left and right operands
= length([expr])
= selector()
Returns the compiled current selector or & if called at root level.
= warn(msg)
Warn with the given error msg, does not exit.
= error(msg)
Exits with the given error msg.
= last(expr)
Return the last value in the given expr
= p(expr)
Inspect the given expr
= opposite-position(positions)
Return the opposites of the given positions.
= image-size(path)
Returns the width and height of the image found at path
= add-property(name, expr)
Adds property name, with the given expr to the closest block.
= use(path)
You can use any given js-plugin at given path with use() function right inside your ‘.styl’ files
= Undefined Functions
Undefined functions will output as literals
@import and @require
= Using @import statement you can import either standard CSS file or a stylus style-sheet.
@import 'mystyle.css' // for importing standard CSS file
@import 'mystyle' // without extension, assuming you want to import Stylus style-sheet
= @import works by iterating an array of directories, and checking if this file lives in any of them. This array defaults to a single path, which is derived from the 'filename' option's dirname'
= @require works same as @import statement, but you can require a file only once.
= Stylus supports block level import, means you can use @import not only at root level, but also nested inside other selectors or at-rules.
= @import multiple files at once, using FILE GLOBING ( Using a mask)
@import 'product/*'
@media
= The @media queries work the same way as in standard CSS, But in Stylus you can use them using Stylus Syntax.
= Nesting Media queries, ( Media Query Bubbling), when expanded they wrap the context in which they are used.
.width
padding 10px
@media screen and (min-width: 600px)
padding 20px
.width {
padding: 10px;
}
@media screen and (min-width: 600px) {
.width {
padding: 20px;
}
}
@font-face
= Allows you to define your own font rules.
@keyframes
= works as same in CSS3, This is basically CSS3 based technique to create animations without any JavaScript Code.
= You need a @ rule with an Identifier in this case, that is 'keyframes' and some nested rules sets for frames.
= In Stylus you can use loops/Interpolation/Variable that helps you a lot.
$keyframe-name = pulse //This is our animation name
@keyframes {$keyframe-name}
for i in 0..10
{10% * i}
opacity (i/10)
= Other @-Stylus rules
= their is nothing special about CSS3 'at rules', use them as you use there is CSS3, but you can use nesting/Interpolation/Loops/Conditions/variables.
@extend ( Inherit CSS rules from other selector or Mixins)
= You can extend pre-existing Selector or nested one.
= You can extend multiple selectors, just separate them using comma.
= Extending placeholder selectors, name starts with a '$' character and not yielded in the resulting CSS, but you can still extend them. They offers you a powerful way to create your own libraries, and still compact output.
@block
= Assigning a name for a block of code and use them later, either pass it to function or use in Interpolation expression.
foo =
width: 20px
height: 20px
foo @block {
width: 20px
height: 20px
}
= url()
= This function replaces the literal url() function inside CSS. This allow you to conditionally inline them using base64 Data URLs.
= Limit bytesize limit defaulting to 30kb, use false to disable it.
= CSS Literal
= if there is some code that you want to write in literal CSS, you can always use Stylus @css tag with wrapped CSS rules inside parenthesis.
@css {
body {
font: 14px;
}
}
= CSS Style Syntax ( we can mix CSS style code and Stylus style code)
= Character Escaping (use '\' character to escape any character)
= Connect Middleware ( useful in Express )
= what is a Middleware?
= So, you got a request, but there is a Middleware defined for response, so, Middleware will get executed before processing the actual request and returning response.
= for auto-Compiling the Stylus sheets whenever modified.
= CSS3 Extensions with Nib ( library with useful Stylus mixins and functions)
= Stylus mixins, utilities, components, and gradient image generation.
= JavaScript API
= Simply require the module and call render() with the given Stylus code and optional 'options' Object.
.set(setting, value)
= Apply settings such as 'filename' or import 'paths'
.include(path)
= An alternative to .set('paths', ...) is include() , this is ideal for when exposing external Stylus libraries which expose a path.
.import(path)
= Dynamically import a stylus library file for your code.
.define(name, node)
= This is useful for defining Global variable that may help you to dynamically generate style sheet.
.define(name, fn)
= This allows you to define a JavaScript function to Stylus, this if for you when there is something that you can not do directly in Stylus but you can do using JavaScript.
.use(fn)
= when called the given function 'fn' is invoked with renderer, allowing all of the methods above to be used.
=> This is a Simple Example of Stylus using CSS Syntax.
//- FILE: mystyle.styl
body {
font: 14px/1.5 Helvetica, Arial, sans-serif;
#logo {
border-radius: 15px;
}
}
=>> In This example we nest selectors.
//- FILE: mystyle.css
body {
font: 14px/1.5 Helvetica, arial, sans-serif;
}
body #logo {
border-radius: 15px;
}
=> Stylus Syntax
If you want to select multiple selectors, just put them on a newline or use comma to separate them.
//- FILE: mystyle.styl
body
font 14px/1.4 Helvetica, arial, sans-serif
button
button.button
input[type='button']
input[type='submit']
border-radius 5px
//- FILE: mystyle.css
body {
font: 14px/1.4 Helvetica, arial, sans-serif;
}
body button,
body button.button,
body input[type='button'],
body input[type='submit'] {
border-radius: 5px;
}
=> Parent Reference (So, You want to use its parent for this style)
There are two syntax for referring parent selectors,
use & after the pre-defined selectors.
So, that all parent will be nested after your defined selector.
use & before the pre-defined selectors.
So, that all parents will be nested before your defined selector.
//- FILE: mystyle.styl
ul
li a
display block
color blue
padding 5px
html.ie &
padding 6px
&:hover
color red
//- FILE: mystyle.css
ul li a {
display: block;
color: #00f;
padding: 5px;
}
html.ie ul li a {
padding: 6px;
}
ul li a:hover {
color: #f00;
}
=> Mixins (So, you want to define your own CSS templates)
Mixins are reusable blocks of code that can optionally take arguments.
//- FILE: mystyle.styl
border-radius(val)
-webkit-border-radius val
-moz-border-radius val
border-radius val
button
border-radius(5px)
//- FILE: mystyle.css
button {
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
=> Transparent Mixins (Mixin with unknown number of parameters)
Transparent Mixins are unique to Stylus, and are great powerful way to enhance your style-sheets, Here all parameters passed are simply assigned to three properties.
//- FILE: mystyle.styl
border-radius()
-webkit-border-radius arguments
-moz-border-radius arguments
border-radius arguments
button
border-radius 5px 10px
//- FILE: mystyle.css
button {
-webkit-border-radius: 5px 10px;
-moz-border-radius: 5px 10px;
border-radius: 5px 10px;
}
=> Variables (So, you want to define and use variables in Stylus)
Stylus variables behaves as you would expect in any other language and may be optionally be prefixed by the "$" character.
//- FILE: mystyle.styl
#prompt
position absolute
top 150px
left 50%
width $w = 200px
margin-left -($w / 2)
//- FILE: mystyle.css
#prompt {
position: absolute;
top: 150px;
left: 50%;
width: 200px;
margin-left: -100px;
}
=> Block property access (So, You want to access some pre-defined values in current code block)
Stylus property access provides easy access to values defined within the current block. Simply prefix the name of property with "@" to reference the value.
//- FILE: mystyle.styl
#prompt
position absolute
top 150px
left 50%
width 200px
margin-left -( @width / 2 )
//- FILE: mystyle.css
#prompt {
position: absolute;
top: 150px;
left: 50%;
width: 200px;
margin-left: -100px;
}
=> Robust feature rich language
Lets use the concept of transparent mixins and Stylus built-in functions and rich features.
You can write cross-browser supported CSS.
//- FILE: mystyle.styl
-pos(type, args)
i = 0
position unquote(type)
{args[i]} args[i + 1] is a 'unit' ? args[i += 1] : 0
{args[i += 1]} args[i + 1] is a 'unit' ? args[i += 1] : 0
absolute()
-pos('absolute', arguments)
fixed()
-pos('fixed', arguments)
#prompt
absolute top 150px left 5px
width 200px
margin-left -(@width / 2)
#logo
fixed top left
//- FILE: mystyle.css
#prompt {
position: absolute;
top: 150px;
left: 5px;
width: 200px;
margin-left: -100px;
}
#logo {
position: fixed;
top: 0;
left: 0;
}
=> List Iteration in Stylus
//- FILE: mystyle.styl
table
for row in 1 2 3 4 5
tr:nth-child({row})
height 10px * row
//- FILE: mystyle.css
table tr:nth-child(1) {
height: 10px;
}
table tr:nth-child(2) {
height: 20px;
}
table tr:nth-child(3) {
height: 30px;
}
table tr:nth-child(4) {
height: 40px;
}
table tr:nth-child(5) {
height: 50px;
}
=> Interpolation
//- FILE: mystyle.styl
vendores = webkit moz o ms official
border-radius()
for vendor in vendors
if vendor == official
border-radius arguments
else
-{vendor}-border-radius arguments
#content
border-radius 5px
//- FILE: mystyle.css
#content {
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
-o-border-radius: 5px;
-ms-border-radius: 5px;
border-radius: 5px;
}
=> Stylus Built-in Operators
//- FILE: mystyle.styl
body
foo 5px + 10
foo 2 ** 8
foo 5px * 2
foo foo and bar and baz
foo foo or bar or baz
foo 1..5
foo 1...5
foo 'foo' is a 'string'
foo (1 2 3) == (1 2 3)
foo (1 2 3) == (1 2)
foo ((one 1) (two 2)) == ((one 1) (two 2))
foo ((one 1) (two 2)) == ((one 1) (two))
foo 3 in (1 2 3 4)
//- FILE: mystyle.css
body {
foo: 15px;
foo: 256;
foo: 10px;
foo: baz;
foo: foo;
foo: 1 2 3 4 5;
foo: 1 2 3 4;
foo: true;
foo: true;
foo: false;
foo: true;
foo: false;
foo: true;
}
=> Style Type coercion feature
//- FILE: mystyle.styl
body
foo foo + bar
foo 'foo' + bar
foo 'foo' + 'bar'
foo 'foo' + 5px
foo 2s - 500ms
foo 5000ms == 5s
foo 50deg
//- FILE: mystyle.css
body {
foo: foobar;
foo: 'foobar';
foo: 'foobar';
foo: 'foo5px';
foo: 1.5s;
foo: true;
foo: 50deg;
}
=> Stylus sprintf Operator
The powerful "%" Operator when used with strings behaves like sprintf with each argument compiled through the stylus compiler, producing a literal value.
//- FILE: mystyle.styl
body
foo '%s / %s' % (5px 10px)
foo 'MS:WeirdStuff(opacity=%s)' % 1
foo unquote('MS:WeirdStuff(opacity=1)')
//- FILE: mystyle.css
body {
foo: 5px / 10px;
foo: MS:WeirdStuff(opacity=1);
foo: MS:WeirdStuff(opacity=1);
}
=> Stylus Color Operations
Operations against colors are especially useful when adding or subtracting by a percentage the color lightness may be adjusted, or the hue may be adjusted with deg.
//- FILE: mystyle.styl
body
foo white - 50%
foo black + 50%
foo #eee - #f00
foo #eee - rgba(black, .5)
foo #cc0000 + 30deg
//- FILE: mystyle.css
body {
foo: #808080;
foo: #808080;
foo: #0ee;
foo: rgba(238,238,238,0.5);
foo: #c60;
}
=> Stylus Functions
Stylus Functions may be defined in the same manner as mixins, however their usage differs as they return values.
//- FILE: mystyle.styl
sum(nums...)
n = 0
n += num for num in nums
body
foo sum(1,2,3,4)
//- FILE: mystyle.css
body {
foo: 10;
}
=> Stylus Functions with Keyword arguments
//- FILE: mystyle.styl
fade-out(color, amount=50%)
color - rgba(0,0,0,amount)
body
foo fade-out(#eee)
foo fade-out(#eee, 20%)
foo fade-out(#eee, amount=40%)
foo fade-out(#eee, amount: 40%)
foo fade-out(color: #eee, amount=40%)
foo fade-out(amount: 40%, color: #eee)
//- FILE: mystyle.css
body {
foo: rgba(238,238,238,0.5);
foo: rgba(238,238,238,0.8);
foo: rgba(238,238,238,0.6);
foo: rgba(238,238,238,0.6);
foo: rgba(238,238,238,0.6);
foo: rgba(238,238,238,0.6);
}
=> Stylus Built-in Functions
Stylus is packed with over 60 built-in functions for manipulating colors, checking variable types, math, list operations, and many more.
//- FILE: mystyle.styl
body
foo red(#fc0)
foo green(#fc0)
foo blue(#fc0)
foo alpha(#fff)
foo alpha(rgba(#fff, .5))
//- FILE: mystyle.css
body {
foo: 255;
foo: 204;
foo: 0;
foo: 1;
foo: 0.5;
}
=> Stylus Color BIFs
The Color built-in functions allow you to adjust lightness, hue, and saturation, check if colors are light or dark or more.
//- FILE: mystyle.styl
body
foo light(#eee)
foo dark(#eee)
foo dark(#333)
foo darken(#eee, 50%)
foo lighten(black, 50%)
foo #eee - 50%
foo black + 50%
//- FILE: mystyle.css
body {
foo: true;
foo: false;
foo: true;
foo: #777;
foo: #808080;
foo: #777;
foo: #808080;
}
= CSS Preprocessor languages (like, less, sass, SCSS, etc...) are useful to make your styles more readable and more maintainable and easier to write style sheets for complex layouts or you can build your own CSS framework like, Bootstrap ( Based on less), and Foundation ( Based on Sass).
= So, You want to learn, What Stylus is and How it is so powerful.
= Before start learning Stylus Language, let's discuss what is offers and how to use those features.
= Stylus Syntax Rules:-
=> In Stylus, you are allowed to use the Syntax of either CSS or Stylus itself.
=> If You are using Stylus syntax, then there, curly braces, semi-colons, colons are optional.
Although you can use if you like them. Stylus dropped them because it's syntax is based on Indentation, just like in Python.
=> Using stylus from Command-line
ssp@ssp-pc /media/ssp/Win/Stylus CSS Pre-processor/tuts $ stylus --help
Usage: stylus [options] [command] [< in [> out]]
[file|dir ...]
Commands:
help [<type>:]<prop> Opens help info at MDN for <prop> in
your default browser. Optionally
searches other resources of <type>:
safari opera w3c ms caniuse quirksmode
Options:
-i, --interactive Start interactive REPL
-u, --use <path> Utilize the Stylus plugin at <path>
-U, --inline Utilize image inlining via data URI support
-w, --watch Watch file(s) for changes and re-compile
-o, --out <dir> Output to <dir> when passing files
-C, --css <src> [dest] Convert CSS input to Stylus
-I, --include <path> Add <path> to lookup paths
-c, --compress Compress CSS output
-d, --compare Display input along with output
-f, --firebug Emits debug infos in the generated CSS that
can be used by the FireStylus Firebug plugin
-l, --line-numbers Emits comments in the generated CSS
indicating the corresponding Stylus line
-m, --sourcemap Generates a sourcemap in sourcemaps v3 format
--sourcemap-inline Inlines sourcemap with full source text in base64 format
--sourcemap-root <url> "sourceRoot" property of the generated sourcemap
--sourcemap-base <path> Base <path> from which sourcemap and all sources are relative
-P, --prefix [prefix] prefix all css classes
-p, --print Print out the compiled CSS
--import <file> Import stylus <file>
--include-css Include regular CSS on @import
-D, --deps Display dependencies of the compiled file
--disable-cache Disable caching
-r, --resolve-url Resolve relative urls inside imports
-V, --version Display the version of Stylus
-h, --help Display help information
=>> You can use Stylus interactive REPL shell, that is great to play with Stylus functions.
ssp@ssp-pc ~ $ stylus -i
>
aliceblue antiquewhite aqua aquamarine azure
beige bisque black blanchedalmond blue
blueviolet brown burlywood cadetblue chartreuse
chocolate coral cornflowerblue cornsilk crimson
cyan darkblue darkcyan darkgoldenrod darkgray
darkgreen darkgrey darkkhaki darkmagenta darkolivegreen
darkorange darkorchid darkred darksalmon darkseagreen
darkslateblue darkslategray darkslategrey darkturquoise darkviolet
deeppink deepskyblue dimgray dimgrey dodgerblue
firebrick floralwhite forestgreen fuchsia gainsboro
ghostwhite gold goldenrod gray green
greenyellow grey honeydew hotpink indianred
indigo ivory khaki lavender lavenderblush
lawngreen lemonchiffon lightblue lightcoral lightcyan
lightgoldenrodyellow lightgray lightgreen lightgrey lightpink
lightsalmon lightseagreen lightskyblue lightslategray lightslategrey
lightsteelblue lightyellow lime limegreen linen
magenta maroon mediumaquamarine mediumblue mediumorchid
mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise
mediumvioletred midnightblue mintcream mistyrose moccasin
navajowhite navy oldlace olive olivedrab
orange orangered orchid palegoldenrod palegreen
paleturquoise palevioletred papayawhip peachpuff peru
pink plum powderblue purple red
rosybrown royalblue saddlebrown salmon sandybrown
seagreen seashell sienna silver skyblue
slateblue slategray slategrey snow springgreen
steelblue tan teal thistle tomato
turquoise violet wheat white whitesmoke
yellow yellowgreen rebeccapurple called-from vendors
-string(arg) require-color(color) require-unit(n) require-string(str) abs(n)
min(a, b) max(a, b) PI radians-to-degrees(angle) degrees-to-radians(angle)
sin(n) cos(n) ceil(n, precision) floor(n, precision) round(n, precision)
sum(nums) avg(nums) remove-unit(n) percent-to-decimal(n) odd(n)
even(n) light(color) dark(color) desaturate(color, amount) saturate(color, amount)
darken(color, amount) lighten(color, amount) fade-out(color, amount) fade-in(color, amount) spin(color, amount)
mix(color1, color2, weight) invert(color) complement(color) grayscale(color) tint(color, percent)
shade(color, percent) last(expr) keys(pairs) values(pairs) join(delim, vals)
add-property-function add-property(name, expr) prefix-classes(prefix) $stylus_mixin_cache cache()
> red(#fff)
=> 255
>
=>> You can write a full Stylus code to Terminal and Stylus compile that and print to terminal. First run Stylus executable and then write your stylus code to terminal, when complete HIT the CTRL-D key, now you can see the compiled output. This technique is basically same as that (php -a) (PHP Interactive mode)
ssp@ssp-pc ~ $ stylus body color red font 14px Arial, sans-serif body { color: #f00; font: 14px Arial, sans-serif; } ssp@ssp-pc ~ $
=>> If you want help regarding any CSS property, then you can use, This will open up a browser with a reference to that property from Mozilla website.
stylus help box-shadow // this works in Linux/Unix
=>> If you want to use any external stylus style-sheet, then stylus must know about it, so add the path to Stylus lookup path using --include flag.
$ stylus < test.styl --include ../nib/lib
=> first learn the theory of Stylus and then we will take a look at its examples and demos.
= Comments in Stylus Style-sheet ( In compressed CSS comments and white-space will be removed.)
= Single line comments
( just like a JavaScript comments ( using '//' ), and will not be in resulting CSS)
= Multi-line Comments
( just like a regular CSS multi-line comment ( using '/* This is a CSS comment*/'))
= Multi-line buffered Comments
( Just like multi-line comments, but start with '/*! This is a buffered comment */')
= Multi-line buffered comment will be there in output CSS even if you had passed a compress flag for Stylus compiler.
= Defining ans using variable in Stylus Style-sheet (So, that you can use them later)
= A Stylus variable may be a single value (like, font = 12px) or a expression (like, font = "sans") or a expression list (like, font = 15px, "sans-serif")
= You can use a '$' prefix for Stylus variable name or functions names (like, $font = "sans-serif")
= Property reference ( Using the '@' operator)
= Stylus has a awesome feature so that you can refer properties defined earlier without defining the variable.
= Just append the '@' character before the Property name that you want to refer.
= returns 'nil' if property does not exists.
= Using CSS selectors and how to nesting of Selectors works
= Stylus use Indentation instead of curly-braces.
= You can nest as many as selectors you want.
= You can use multiple selectors at a time either use a comma ',' to separate them or in Stylus you can use a newline character.
= Parent Selectors Reference using '&' Operator
= You can refer to parent selectors using '&' operator.
= There may be one or more than one parent selectors based on Scope.
= Understand the difference between the indented parent selectors and parent selectors separated using Comma or newline.
= Indentation means nested selectors, and newline ( or comma) means multiple selectors.
= Root Selector Reference using '/' operator
= This is simply tell us, protect this selector from parent reference, use this as root context.
= Using selector() built-in function
= this built-in function returns the current compiled selector that can be used inside a mixin or function.
= Using the unquote() built-in function
= this return the value without quote, so that Stylus can process that values.
= Using Stylus built-in Operators (addition, subtraction, etc...)
= Unary Operators ( !, not, -, +, ~ )
= Binary Operators
= Additive ( +, - )
= Multiplicative ( /, *, % )
= Exponent ( **)
= Equality and Relational ( ==, !=, <=, >=, >, < )
= Logical Operator ( &&, ||, and, or )
= Existence Operator ( in )
= Conditional Assignment
( if variable exists than there is no need to reassign variable)
= These are equivalent.
color := white
color ?= white
color = color is defined ? color : white
= Instance check ( is a )
( example, 15 is a 'unit') ( means we are checking that does 15 belongs to unit class)
= Variable Definition ( is defined ) ( Does this variable is defined earlier)
= Ternary Operator ( $a = (conditional_expression) ? true : false )
= Color Operations
( rgb() or rgba() built-in function) (or we can simply use +, -, *, 12%, 45deg etc... operations)
= s() built-in function ( using '%' operator) ( same as sprintf() function is C/C++)
'X::Microsoft::Crap(%s)' % #fc0
// => X::Microsoft::Crap(#fc0)
= subscript Operator "[]"
( allow you to grab a value via index ( Zero-based), and negative index means start from end)
list = 1 2 3 4 5 6
tuple = (1 2 3 4)
tuple = (100px 200px)
list[0]
// 1
= Inclusive and Exclusive Ranges
1..5
// 1 2 3 4 5
1...5
// 1 2 3 4
5..1
// 5 4 3 2 1
= Stylus Interpolation Rules
= Stylus supports interpolation by using the {} characters to surround an expression.
= values inside this braces will be treated as Identifier.
= Conditionals statements (like, if, if else, unless )
= unless is basically opposite of if statement, and equal to if(!(condition_expression))
= Post-fix Conditionals
= note that if and unless both works as operator, means when right-hand expression/operand is truthy, they evaluates the left hand-expression/operand. this helps us to write one line conditional expressions.
= Using Hashes in Stylus (like, Dictionary in Python )
= You can define a hash using curly braces and comma to separate keys and values, note that keys should be either proper indented or a string value.
= if you want to add any key/value pair to pre-defined hash, then you can use brackets with string key.
= To get a value of any key from Hash you can use a dot (.) operator with hash name.
= hashes used inside a curly braces (means for interpolation) just returns hash values that can be used as CSS rules.
= Built-in length() function just returns its length.
= keys() and values() built-in functions, just returns a list of keys and values respectively.
= merge() or extend() are used to merge two hashes.
= Iteration or Loop functions in Stylus (like, for )
= Stylus Allow you to iterate expressions using for/in construct
= Syntax:-
for <value_name> [, <key_name>] in <expression>
body
for num in 1 2 3 4
foo num
body
for num in (1..5)
foo num
= Note that likewise if/unless, for also behaves post-fix operator.
= Using Mixins in Stylus style-sheets ( reusable block of CSS code that can optionally take parameters)
= Both mixins and functions are defined in same manner, but they are applied in different ways.
= When mixin is invoked within a selector, the properties are expanded and copied into the selector.
= Stylus Introspection API, Whenever you call a mixin, then a local variable name 'mixin' is automatically created with a string value 'root', this help you to find whether a function is invoked as a mixin or as a function.
= Using Transparent Mixins ( Mixins with unknown number of parameters )
= mixin defined without any parameters but uses the local variable 'arguments' variable that contain expression passes to it.
= thus allowing multiple values to be passed.
= Using Block Mixins
= You can pass blocks to mixins by calling the mixin with + prefix.
= use a local variable 'block' inside curly brackets to access passed blocks.
= Nesting Mixins inside Mixins
= Mixins can utilize other mixins, build upon their own selectors and properties.
= Defining and Using Functions ( function that can return a value )
= Function that can return value
add(a,b)
a + b
= Functions with default arguments
add(a, b=a) // b = a until you explicitly define a value for b
a + b
= Functions with named parameters
subtract(a, b)
a - b
subtract(b: 10, a: 25)
= Function that returns multiple values
= Stylus functions can return multiple values as you assign multiple value to a variable.
sizes = 15px 10px // Stylus variable with multiple values
sizes() // stylus function that return multiple values
15px 10px
= While returning multiple values from function either use parenthesis for values or use a return statement before them.
= Function with different name ( function Aliasing)
plus = add
plus(1,2) // returns 3
= Stylus Anonymous functions ( Using '@() {}' syntax)
= local variable 'arguments' is available to all function bodies, and contain all the arguments passed.
= Functions with Rest parameters (like, curry functions in Haskell)
= Stylus supports rest parameters in the form of 'name...' These params consume the remaining arguments passed to a mixin or function.
= Stylus Built-in Functions for you ( In Stylus there are over 60 Built-in function for you to use)
= red(color[, value])
return the red component of the given color, or set the red component to given value.
= green(color[, value])
return the green component of the given color, or set the green component to given value.
= blue(color[, value])
return the blue component of the given color, or set the blue component to given value.
= alpha(color[, value])
return the alpha component of the given color, or set the alpha component to given value.
= dark(color)
check if color is dark
= light(color)
Check if color is light
= hue(color[, value])
Return the hue of the given color or set the hue component to the optional argument value.
= saturation(color[, value])
Return the saturation of the given color or set the saturation component to the optional argument value.
= lightness(color[, value])
Return the lightness of the given color or set the lightness component to the optional argument value.
= push(expr, args...)
Push the given args to expr
= unshift(expr, args...)
Unshift the given args to expr
= keys(pairs)
Return keys in the given pair
= values(pairs)
Return the values in given pair
= list-separator(list)
Return the separator of the given list (for example, white-space, or a comma)
= typeof(node)
Return the type of node as a string
= unit(unit[, type])
Return a string for the type of unit or an empty string, or assign the given type without unit conversion.
unit(15in) // returns 'in' [inch]
= match(pattern, string)
Test if string matches the given pattern
= abs(unit) // absolute value
= ceil(unit) // nearest upper integer
= floor(unit) // nearest lower integer
= round(unit[, precision])
= sin(angle)
without any unit angle will be assumed as radians, you can explicitly use degrees as 45deg
= cos(angle)
= tan(angle)
= min(a, b) // comma separated two values
= max(a, b)
= even(unit)
= odd(unit)
= sum(nums)
supply a white-space separated list of numbers
= avg(nums)
= base-convert(num, base, width)
num, that you want to convert, base, with this base, and with this width
= join(delim, vals...)
= hsla(color | h,s,l,a)
Convert the given color to an HSLA node or h, s, l ,a component values.
= hsl(color | h, s, l)
= rgba(color | r,g, b, a)
Return RGBA from the r, g, b, a channels or provide a color to tweak the alpha.
= rgb(color | r, g, b)
= blend(top[, bottom])
Blends the given top color over the bottom one using the normal blending. The bottom argument is optional and is defaulted to #fff
= lighten(color, amount)
Lighten the given color by amount. This function is unit-sensitive. for example supporting percentages.
= darken(color, amount)
Darken the given color by amount, This function is unit-sensitive, for example supporting percentages.
= desaturate(color, amount)
Desaturate the given color by amount.
= saturate(color, amount)
Saturate the given color by amount.
= complement(color)
Gives the complementary color Equals to spinning HUE to 180deg.
= invert(color)
Inverts the color. The red, green, and blue values are inverted, while the opacity is left alone.
= grayscale(color)
Gives the grayscale equivalent of the given color, Equals to desaturate by 100%
= tint(color, amount)
Mix the given color with white.
= shade(color, amount)
Mix the given color with black.
= luminosity(color)
Returns the relative luminance of the given color.
= constrast(top[, bottom])
Returns the contrast ratio object between top and bottom colors,
The second argument is optional and is defaulted to #fff.
= transparentify(top[, bottom, alpha])
Returns the transparent version of the given top color, as if it was blend over the given bottom color
The second argument is optional and is defaulted to #fff.
= unquote(str | ident)
Unquote the given str and returned as a Literal node.
= convert(str)
Like unquote() but tries to convert the given str to a Stylus node.
= s(fmt, ...)
= basename(path[, ext])
Returns the basename of path, (optionally) with ext extension removed.
= dirname(path)
Returns the dirname of path
= extname(path)
Return the filename extension of path including the dot
= pathjoin(...)
Perform a path join
= called-from property
called-from property contains the list of the functions the current function was called from in the reverse order (the first item is the deepest function).
= current-media()
returns the string of the current block’s @media rule or '' if there is no @media above the block.
= +cache(keys...)
allows you to create your own “cachable” mixins.
= +prefix-classes(prefix)
Stylus comes with a block mixin prefix-classes that can be used for prefixing the classes inside any given Stylus’ block
= lookup(name)
Allows to lookup a variable with a given name, passed as a string. Returns null if the variable is undefined.
= define(name, expr)
Allows to create or overwrite a variable with a given name, passed as a string, onto current scope.
= operate(op, left, right)
Perform the given op on the left and right operands
= length([expr])
= selector()
Returns the compiled current selector or & if called at root level.
= warn(msg)
Warn with the given error msg, does not exit.
= error(msg)
Exits with the given error msg.
= last(expr)
Return the last value in the given expr
= p(expr)
Inspect the given expr
= opposite-position(positions)
Return the opposites of the given positions.
= image-size(path)
Returns the width and height of the image found at path
= add-property(name, expr)
Adds property name, with the given expr to the closest block.
= use(path)
You can use any given js-plugin at given path with use() function right inside your ‘.styl’ files
= Undefined Functions
Undefined functions will output as literals
@import and @require
= Using @import statement you can import either standard CSS file or a stylus style-sheet.
@import 'mystyle.css' // for importing standard CSS file
@import 'mystyle' // without extension, assuming you want to import Stylus style-sheet
= @import works by iterating an array of directories, and checking if this file lives in any of them. This array defaults to a single path, which is derived from the 'filename' option's dirname'
= @require works same as @import statement, but you can require a file only once.
= Stylus supports block level import, means you can use @import not only at root level, but also nested inside other selectors or at-rules.
= @import multiple files at once, using FILE GLOBING ( Using a mask)
@import 'product/*'
@media
= The @media queries work the same way as in standard CSS, But in Stylus you can use them using Stylus Syntax.
= Nesting Media queries, ( Media Query Bubbling), when expanded they wrap the context in which they are used.
.width
padding 10px
@media screen and (min-width: 600px)
padding 20px
.width {
padding: 10px;
}
@media screen and (min-width: 600px) {
.width {
padding: 20px;
}
}
@font-face
= Allows you to define your own font rules.
@keyframes
= works as same in CSS3, This is basically CSS3 based technique to create animations without any JavaScript Code.
= You need a @ rule with an Identifier in this case, that is 'keyframes' and some nested rules sets for frames.
= In Stylus you can use loops/Interpolation/Variable that helps you a lot.
$keyframe-name = pulse //This is our animation name
@keyframes {$keyframe-name}
for i in 0..10
{10% * i}
opacity (i/10)
= Other @-Stylus rules
= their is nothing special about CSS3 'at rules', use them as you use there is CSS3, but you can use nesting/Interpolation/Loops/Conditions/variables.
@extend ( Inherit CSS rules from other selector or Mixins)
= You can extend pre-existing Selector or nested one.
= You can extend multiple selectors, just separate them using comma.
= Extending placeholder selectors, name starts with a '$' character and not yielded in the resulting CSS, but you can still extend them. They offers you a powerful way to create your own libraries, and still compact output.
@block
= Assigning a name for a block of code and use them later, either pass it to function or use in Interpolation expression.
foo =
width: 20px
height: 20px
foo @block {
width: 20px
height: 20px
}
= url()
= This function replaces the literal url() function inside CSS. This allow you to conditionally inline them using base64 Data URLs.
= Limit bytesize limit defaulting to 30kb, use false to disable it.
= CSS Literal
= if there is some code that you want to write in literal CSS, you can always use Stylus @css tag with wrapped CSS rules inside parenthesis.
@css {
body {
font: 14px;
}
}
= CSS Style Syntax ( we can mix CSS style code and Stylus style code)
= Character Escaping (use '\' character to escape any character)
= Connect Middleware ( useful in Express )
= what is a Middleware?
= So, you got a request, but there is a Middleware defined for response, so, Middleware will get executed before processing the actual request and returning response.
= for auto-Compiling the Stylus sheets whenever modified.
= CSS3 Extensions with Nib ( library with useful Stylus mixins and functions)
= Stylus mixins, utilities, components, and gradient image generation.
= JavaScript API
= Simply require the module and call render() with the given Stylus code and optional 'options' Object.
.set(setting, value)
= Apply settings such as 'filename' or import 'paths'
.include(path)
= An alternative to .set('paths', ...) is include() , this is ideal for when exposing external Stylus libraries which expose a path.
.import(path)
= Dynamically import a stylus library file for your code.
.define(name, node)
= This is useful for defining Global variable that may help you to dynamically generate style sheet.
.define(name, fn)
= This allows you to define a JavaScript function to Stylus, this if for you when there is something that you can not do directly in Stylus but you can do using JavaScript.
.use(fn)
= when called the given function 'fn' is invoked with renderer, allowing all of the methods above to be used.
=> This is a Simple Example of Stylus using CSS Syntax.
//- FILE: mystyle.styl
body {
font: 14px/1.5 Helvetica, Arial, sans-serif;
#logo {
border-radius: 15px;
}
}
=>> In This example we nest selectors.
//- FILE: mystyle.css
body {
font: 14px/1.5 Helvetica, arial, sans-serif;
}
body #logo {
border-radius: 15px;
}
=> Stylus Syntax
If you want to select multiple selectors, just put them on a newline or use comma to separate them.
//- FILE: mystyle.styl
body
font 14px/1.4 Helvetica, arial, sans-serif
button
button.button
input[type='button']
input[type='submit']
border-radius 5px
//- FILE: mystyle.css
body {
font: 14px/1.4 Helvetica, arial, sans-serif;
}
body button,
body button.button,
body input[type='button'],
body input[type='submit'] {
border-radius: 5px;
}
=> Parent Reference (So, You want to use its parent for this style)
There are two syntax for referring parent selectors,
use & after the pre-defined selectors.
So, that all parent will be nested after your defined selector.
use & before the pre-defined selectors.
So, that all parents will be nested before your defined selector.
//- FILE: mystyle.styl
ul
li a
display block
color blue
padding 5px
html.ie &
padding 6px
&:hover
color red
//- FILE: mystyle.css
ul li a {
display: block;
color: #00f;
padding: 5px;
}
html.ie ul li a {
padding: 6px;
}
ul li a:hover {
color: #f00;
}
=> Mixins (So, you want to define your own CSS templates)
Mixins are reusable blocks of code that can optionally take arguments.
//- FILE: mystyle.styl
border-radius(val)
-webkit-border-radius val
-moz-border-radius val
border-radius val
button
border-radius(5px)
//- FILE: mystyle.css
button {
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
=> Transparent Mixins (Mixin with unknown number of parameters)
Transparent Mixins are unique to Stylus, and are great powerful way to enhance your style-sheets, Here all parameters passed are simply assigned to three properties.
//- FILE: mystyle.styl
border-radius()
-webkit-border-radius arguments
-moz-border-radius arguments
border-radius arguments
button
border-radius 5px 10px
//- FILE: mystyle.css
button {
-webkit-border-radius: 5px 10px;
-moz-border-radius: 5px 10px;
border-radius: 5px 10px;
}
=> Variables (So, you want to define and use variables in Stylus)
Stylus variables behaves as you would expect in any other language and may be optionally be prefixed by the "$" character.
//- FILE: mystyle.styl
#prompt
position absolute
top 150px
left 50%
width $w = 200px
margin-left -($w / 2)
//- FILE: mystyle.css
#prompt {
position: absolute;
top: 150px;
left: 50%;
width: 200px;
margin-left: -100px;
}
=> Block property access (So, You want to access some pre-defined values in current code block)
Stylus property access provides easy access to values defined within the current block. Simply prefix the name of property with "@" to reference the value.
//- FILE: mystyle.styl
#prompt
position absolute
top 150px
left 50%
width 200px
margin-left -( @width / 2 )
//- FILE: mystyle.css
#prompt {
position: absolute;
top: 150px;
left: 50%;
width: 200px;
margin-left: -100px;
}
=> Robust feature rich language
Lets use the concept of transparent mixins and Stylus built-in functions and rich features.
You can write cross-browser supported CSS.
//- FILE: mystyle.styl
-pos(type, args)
i = 0
position unquote(type)
{args[i]} args[i + 1] is a 'unit' ? args[i += 1] : 0
{args[i += 1]} args[i + 1] is a 'unit' ? args[i += 1] : 0
absolute()
-pos('absolute', arguments)
fixed()
-pos('fixed', arguments)
#prompt
absolute top 150px left 5px
width 200px
margin-left -(@width / 2)
#logo
fixed top left
//- FILE: mystyle.css
#prompt {
position: absolute;
top: 150px;
left: 5px;
width: 200px;
margin-left: -100px;
}
#logo {
position: fixed;
top: 0;
left: 0;
}
=> List Iteration in Stylus
//- FILE: mystyle.styl
table
for row in 1 2 3 4 5
tr:nth-child({row})
height 10px * row
//- FILE: mystyle.css
table tr:nth-child(1) {
height: 10px;
}
table tr:nth-child(2) {
height: 20px;
}
table tr:nth-child(3) {
height: 30px;
}
table tr:nth-child(4) {
height: 40px;
}
table tr:nth-child(5) {
height: 50px;
}
=> Interpolation
//- FILE: mystyle.styl
vendores = webkit moz o ms official
border-radius()
for vendor in vendors
if vendor == official
border-radius arguments
else
-{vendor}-border-radius arguments
#content
border-radius 5px
//- FILE: mystyle.css
#content {
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
-o-border-radius: 5px;
-ms-border-radius: 5px;
border-radius: 5px;
}
=> Stylus Built-in Operators
//- FILE: mystyle.styl
body
foo 5px + 10
foo 2 ** 8
foo 5px * 2
foo foo and bar and baz
foo foo or bar or baz
foo 1..5
foo 1...5
foo 'foo' is a 'string'
foo (1 2 3) == (1 2 3)
foo (1 2 3) == (1 2)
foo ((one 1) (two 2)) == ((one 1) (two 2))
foo ((one 1) (two 2)) == ((one 1) (two))
foo 3 in (1 2 3 4)
//- FILE: mystyle.css
body {
foo: 15px;
foo: 256;
foo: 10px;
foo: baz;
foo: foo;
foo: 1 2 3 4 5;
foo: 1 2 3 4;
foo: true;
foo: true;
foo: false;
foo: true;
foo: false;
foo: true;
}
=> Style Type coercion feature
//- FILE: mystyle.styl
body
foo foo + bar
foo 'foo' + bar
foo 'foo' + 'bar'
foo 'foo' + 5px
foo 2s - 500ms
foo 5000ms == 5s
foo 50deg
//- FILE: mystyle.css
body {
foo: foobar;
foo: 'foobar';
foo: 'foobar';
foo: 'foo5px';
foo: 1.5s;
foo: true;
foo: 50deg;
}
=> Stylus sprintf Operator
The powerful "%" Operator when used with strings behaves like sprintf with each argument compiled through the stylus compiler, producing a literal value.
//- FILE: mystyle.styl
body
foo '%s / %s' % (5px 10px)
foo 'MS:WeirdStuff(opacity=%s)' % 1
foo unquote('MS:WeirdStuff(opacity=1)')
//- FILE: mystyle.css
body {
foo: 5px / 10px;
foo: MS:WeirdStuff(opacity=1);
foo: MS:WeirdStuff(opacity=1);
}
=> Stylus Color Operations
Operations against colors are especially useful when adding or subtracting by a percentage the color lightness may be adjusted, or the hue may be adjusted with deg.
//- FILE: mystyle.styl
body
foo white - 50%
foo black + 50%
foo #eee - #f00
foo #eee - rgba(black, .5)
foo #cc0000 + 30deg
//- FILE: mystyle.css
body {
foo: #808080;
foo: #808080;
foo: #0ee;
foo: rgba(238,238,238,0.5);
foo: #c60;
}
=> Stylus Functions
Stylus Functions may be defined in the same manner as mixins, however their usage differs as they return values.
//- FILE: mystyle.styl
sum(nums...)
n = 0
n += num for num in nums
body
foo sum(1,2,3,4)
//- FILE: mystyle.css
body {
foo: 10;
}
=> Stylus Functions with Keyword arguments
//- FILE: mystyle.styl
fade-out(color, amount=50%)
color - rgba(0,0,0,amount)
body
foo fade-out(#eee)
foo fade-out(#eee, 20%)
foo fade-out(#eee, amount=40%)
foo fade-out(#eee, amount: 40%)
foo fade-out(color: #eee, amount=40%)
foo fade-out(amount: 40%, color: #eee)
//- FILE: mystyle.css
body {
foo: rgba(238,238,238,0.5);
foo: rgba(238,238,238,0.8);
foo: rgba(238,238,238,0.6);
foo: rgba(238,238,238,0.6);
foo: rgba(238,238,238,0.6);
foo: rgba(238,238,238,0.6);
}
=> Stylus Built-in Functions
Stylus is packed with over 60 built-in functions for manipulating colors, checking variable types, math, list operations, and many more.
//- FILE: mystyle.styl
body
foo red(#fc0)
foo green(#fc0)
foo blue(#fc0)
foo alpha(#fff)
foo alpha(rgba(#fff, .5))
//- FILE: mystyle.css
body {
foo: 255;
foo: 204;
foo: 0;
foo: 1;
foo: 0.5;
}
=> Stylus Color BIFs
The Color built-in functions allow you to adjust lightness, hue, and saturation, check if colors are light or dark or more.
//- FILE: mystyle.styl
body
foo light(#eee)
foo dark(#eee)
foo dark(#333)
foo darken(#eee, 50%)
foo lighten(black, 50%)
foo #eee - 50%
foo black + 50%
//- FILE: mystyle.css
body {
foo: true;
foo: false;
foo: true;
foo: #777;
foo: #808080;
foo: #777;
foo: #808080;
}
No comments :
Post a Comment