Variable Declaration and Assignment in Stylus: `$variable = value

In Stylus's variable system, the core operator is the $ symbol, which is used to reference variable names. The language adopts a simplified declaration and assignment mechanism, allowing developers to complete both definition and initialization processes directly through the = operator. This design results in code that is both concise and easy to maintain, making it particularly suitable for scenarios requiring frequent reuse of values.

The standard variable declaration format is as follows:

$variableName = value

In this syntax, $variableName represents the identifier for the variable, while value is the specific value assigned to that variable. Stylus supports multiple data types, including numbers, strings, colors, and boolean values, among others. Upon executing an assignment operation, the variable becomes immediately effective within its current scope and can be referenced in subsequent style calculations.

To better understand this mechanism, we can compare the assignment methods for different data types:

  • Numeric Types: Can be assigned directly as integers or floating-point numbers, such as $count = 10 or $radius = 3.5px.
  • String Types: Typically used to store text content, like $message = "Hello World".
  • Color Types: This is one of the most common scenarios in Stylus; hexadecimal codes, HSL format, or standard CSS names can be used directly, for example, $primaryColor = #3498db or $accentColor = hsl(210, 100%, 50%).

It is worth noting that Stylus variable names follow naming conventions, typically starting with a letter and followed by letters, numbers, or underscores. While certain relaxed modes may allow other characters, it is recommended to strictly adhere to this rule in production environments to avoid potential parsing errors. Furthermore, variable names are case-sensitive; therefore, $count and $Count are considered two completely different identifiers.
Understanding variable scope is key to writing robust Stylus code. Stylus's variable scope follows the classic "block-level scope" principle, meaning variables are only valid within the code block where they are defined (the area enclosed by curly braces {}). This feature is crucial for handling complex nested structures.

When declaring variables within nested code blocks, variables defined in the outer block cannot be directly accessed by the inner block, and vice versa. This isolation mechanism prevents naming conflicts and ensures logical independence. Here is a typical nested example:

$outerValue = 100

div
  $innerValue = 200
  // Attempting to use $outerValue here will result in an error or invalid behavior
  height: $innerValue * 2

In the code above, $outerValue is defined in the root block, while $innerValue is defined inside the div block. If we attempt to reference $outerValue within the inner layer, the Stylus compiler will treat it as an undefined variable and throw an error. This requires developers to explicitly understand the lifecycle scope of variables when writing nested styles.

However, Stylus provides the concept of a global scope to break through this limitation. Variables defined at the top level of the file will apply to any block-level code within the entire file. This is very useful for defining theme colors, base dimensions, or universal constants. For example:

// Global variables that can be used anywhere in the file
$themeColor = #ff5733
$baseSize = 16px

body
  color: $themeColor
  font-size: $baseSize

header
  // Global variables can also be used here
  background: $themeColor

This mechanism greatly enhances code maintainability, allowing style sheets to organize data similarly to configuration files.

Advanced Applications and Best Practices

After mastering the basic declaration, we can further explore advanced application scenarios for variables in Stylus. In Stylus, variables are not only used for simple assignments but can also participate in complex expression calculations, conditional judgments, and combination with other functions.

First, Stylus supports embedding variables directly into CSS property values for mathematical operations. Since Stylus includes a powerful built-in calculation engine, developers do not need to manually concatenate strings to achieve dynamic styles. For example, automatically adjusting padding based on container width:

$containerWidth = 800px
$padding = ($containerWidth - 640px) / 2

.page
  width: $containerWidth
  padding: $padding

This code automatically calculates the padding value to be 80px and applies it directly to the .page element. This dynamic calculation capability makes the implementation of responsive layouts more intuitive and efficient.

Second, variables play a core role in conditional statements (such as if, else if). Stylus's conditional logic allows for different style decisions based on variable values. Combined with ternary operators or nested if blocks, complex logical branches can be implemented:

$isActive = true

div.item
  if $isActive
    display: block
    opacity: 1
  else
    display: none
    opacity: 0.5

Additionally, in actual development, the following best practices are recommended to improve code quality:

  1. Naming Conventions: Use descriptive variable names and avoid single-letter abbreviations (such as $w, $h) unless the context is very clear. It is recommended to use underscores to separate words, for example, $itemWidth or $mainColor.
  2. Single Responsibility: Try to keep the purpose of a variable singular, avoiding one variable carrying too much meaning, which helps reduce cognitive load on the code.
  3. Timely Cleanup: When defining temporary variables inside loops or functions, ensure they exist only within the necessary scope to minimize the risk of global pollution.

By flexibly utilizing the basic syntax $variable = value and deeply understanding its scope rules and calculation capabilities, developers can build a Stylus style system that is structurally clear, logically rigorous, and highly reusable. This not only simplifies daily development work but also provides a solid foundation for handling complex UI requirements.