Introduction to Stylus
Stylus is a powerful preprocessor scripting language that facilitates faster and more efficient CSS writing. Stylus brings the advantages of programming to CSS, with features like variables, mixins, functions, and nesting. This brief guide will elucidate various Stylus APIs to help you harness its full potential.
Basic Features
Variables
Variables in Stylus are used to store values that can be reused throughout your stylesheet.
color = #b4d455
body
color: color
Nesting
Nesting allows you to write CSS in a nested hierarchy to reflect the HTML structure.
nav
ul
margin: 0
padding: 0
Mixins
Mixins are blocks of stylus code that can be reused multiple times throughout your CSS.
border-radius(radius)
-webkit-border-radius: radius
-moz-border-radius: radius
border-radius: radius
.box
border-radius(10px)
Interpolation
Interpolation allows embedding of variables in selectors and property names.
n = 5
.item-{n}
width: 200px
Conditionals
Conditionals in Stylus use logical statements to apply styles based on conditions.
size = "large"
body
if size == "large"
font-size: 20px
else
font-size: 12px
Functions
Functions allow the creation of reusable blocks of code that can be called with different arguments.
add(a, b)
a + b
margin = add(10px, 15px)
body
margin: margin
Example Application
Here is an example of a simple web page styled using Stylus:
HTML
Stylus Example
Content Box
Stylus
color = #b4d455
nav
ul
margin: 0
padding: 0
li
display: inline-block
margin-right: 20px
a
color: color
text-decoration: none
border-radius(radius)
-webkit-border-radius: radius
-moz-border-radius: radius
border-radius: radius
.box
border-radius(10px)
padding: 20px
background-color: #eee
With this setup, you have a styled navigation bar and a content box with rounded corners using Stylus’s features.