Less - Parent Selectors
LESS - Parent Selectors
Section titled “LESS - Parent Selectors”The parent selector, represented by the ampersand (&), is a powerful feature in LESS that refers to the complete chain of parent selectors of a nested rule. It is primarily used to modify the current selector, apply pseudo-classes or pseudo-elements, or to change the relationship between the nested rule and its parent.
Using & allows for more concise and readable stylesheets, especially when following naming conventions like BEM (Block, Element, Modifier) or when styling states like :hover or :focus.
The following table shows common use cases and behaviors of the parent selector:
| ID | Use Case & Description | Example Snippet & Compiled CSS |
|---|---|---|
| 1 | Applying Pseudo-classes/elements The most common use: &:hover, &:focus, &::before, &::after. | a { color: blue; &:hover { color: red; } }Compiles to: a { color: blue; } a:hover { color: red; } |
| 2 | Appending Classes (Modifiers or States) Used for BEM-style modifiers or state classes: &.active, &--modifier. | .button { background: grey; &.primary { background: blue; } }Compiles to: .button { background: grey; } .button.primary { background: blue; } |
| 3 | Prepending Selectors (Contextual Styling) When & is not the first part of a selector within a nested rule, it can be used to prepend the parent selector to another selector. Useful for contextual styling. | .element { .ancestor & { color: green; } }Compiles to: .ancestor .element { color: green; } |
| 4 | Multiple & (Referencing Outer Parents)You can use & multiple times to reference further up the parent chain, though this is less common and can make selectors complex. Each & usually refers to the full current parent selector string. | .grandparent { .parent { .child { && { color: red; } } } }Compiles to: .grandparent .parent .child.grandparent .parent .child { color: red; } (Often not the desired outcome; usually, one & is sufficient for current parent context). A more practical use of multiple & is in combinatorial scenarios. |
| 5 | Changing Selector Order / Sibling Combinators Placing & after another selector in a nested rule, or using it with sibling combinators (+, ~). | li { &:hover + li { background: lightgray; } &:last-child { margin-right: 0; } }Compiles to: li:hover + li { background: lightgray; } li:last-child { margin-right: 0; } |
| 6 | Combinatorial Explosion (& with comma-separated lists)When & is used with selectors that are comma-separated lists, it generates all possible permutations. This can be powerful but also lead to many selectors if not used carefully. | .alert, .message { strong& { font-weight:bold; } }Compiles to: strong.alert, strong.message { font-weight:bold; } (Here & refers to each selector in the parent list).Another: p, div { &:hover, &:focus { color: red; } } would generate p:hover, p:focus, div:hover, div:focus { ... } |
Example: Using Parent Selectors for States and Modifiers
Section titled “Example: Using Parent Selectors for States and Modifiers”HTML (parent_selector_example.html):
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Parent Selector Example</title> <link rel="stylesheet" type="text/css" href="style.css"></head><body> <a href="#" class="button">Default Button</a> <a href="#" class="button button--primary">Primary Button</a> <a href="#" class="button button--large is-active">Large Active Button</a> <ul class="menu"> <li>Item 1</li> <li>Item 2</li> </ul></body></html>LESS (style.less):
style.less
Section titled “style.less”@primary-color: #007bff;@default-bg: #f0f0f0;
.button { display: inline-block; padding: 10px 15px; background-color: @default-bg; color: #333; text-decoration: none; border-radius: 4px; transition: background-color 0.3s ease;
&:hover { background-color: darken(@default-bg, 10%); }
&--primary { // BEM-style modifier background-color: @primary-color; color: white;
&:hover { background-color: darken(@primary-color, 10%); } }
&--large { padding: 15px 25px; font-size: 1.2em; }
// State class combined with parent selector &.is-active { box-shadow: 0 0 5px rgba(0,0,0,0.5) inset; }}
.menu { list-style: none; padding-left: 0; li { padding: 5px; // When .menu has class .dark, then li changes color .dark& { color: white; background-color: #333; } }}Compile style.less to style.css:
lessc style.less style.cssThe compiled style.css will be:
style.css
Section titled “style.css”.button { display: inline-block; padding: 10px 15px; background-color: #f0f0f0; color: #333; text-decoration: none; border-radius: 4px; transition: background-color 0.3s ease;}.button:hover { background-color: #d6d6d6; /* darken(#f0f0f0, 10%) */}.button--primary { background-color: #007bff; color: white;}.button--primary:hover { background-color: #0056b3; /* darken(#007bff, 10%) */}.button--large { padding: 15px 25px; font-size: 1.2em;}.button.is-active { box-shadow: 0 0 5px rgba(0, 0, 0, 0.5) inset;}.menu { list-style: none; padding-left: 0;}.menu li { padding: 5px;}.dark.menu li { color: white; background-color: #333;}The parent selector & is indispensable for writing clean, structured, and maintainable LESS, especially when dealing with component states, modifiers, and pseudo-classes.
Output
Section titled “Output”Opening parent_selector_example.html will display buttons with various styles applied through the use of the parent selector for hover states, modifier classes (--primary, --large), and state classes (is-active). The .dark.menu li example shows how & can be used to change context.
For more advanced uses and understanding of how & interacts with complex selectors, the official LESS documentation is a valuable resource.
LESS - Misc Functions
Section titled “LESS - Misc Functions”LESS includes several miscellaneous (misc) functions that provide utility for various tasks, such as type conversion, data URI embedding, unit manipulation, and accessing image dimensions. These functions don’t fit neatly into categories like Math or Color but offer valuable capabilities.
The following table lists some key miscellaneous functions in LESS:
| ID | Function & Description | Example & Conceptual Output |
|---|---|---|
| 1 | color(string)Parses a string representation of a color (e.g., "#FF0000" or "blue") and returns a LESS color object. Useful when color values are stored as strings. | @my-color-string: "#3498db"; .element { background-color: color(@my-color-string); }Output: .element { background-color: #3498db; } |
| 2 | image-size(filePath)Returns the dimensions (width and height) of an image file. Requires LESS compiler to have file system access. Returns a list like 100px 50px. | @path: "images/logo.png"; .logo { width: extract(image-size(@path), 1); height: extract(image-size(@path), 2); }If logo.png is 120x60px: .logo { width: 120px; height: 60px; } (This function is less common in modern workflows with responsive images and CSS sizing). |
| 3 | image-width(filePath)Returns the width of an image file. Similar to image-size but only for width. | @path: "images/icon.svg"; .icon { width: image-width(@path); } |
| 4 | image-height(filePath)Returns the height of an image file. Similar to image-size but only for height. | @path: "images/banner.jpg"; .banner { height: image-height(@path); } |
| 5 | convert(numberWithUnit, targetUnit)Converts a number from one unit to another compatible unit (e.g., pixels to ems, inches to cm). | @length-in-px: 16px; .text { font-size: convert(@length-in-px, em); }Output depends on base font size context, but converts e.g. 16px to 1em if base is 16px. |
| 6 | data-uri(filePath, mimeType?)Embeds a file directly into the stylesheet as a Base64 encoded data URI. Optionally, you can specify the MIME type. This can reduce HTTP requests but increase CSS file size. Useful for small icons or fonts. | .icon-disk { background-image: data-uri('images/disk-icon.png'); }Output: .icon-disk { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFerKKAUZAAAAAElFTkSuQmCC'); } (actual Base64 string will vary). |
| 7 | default()A special function used only within mixin guards. It evaluates to true if no other guarded mixin (of the same name) with a condition that evaluates to true has been matched. Acts as an ‘else’ or fallback condition. | .mixin(@a) when (@a > 10) { /* styles for >10 */ } .mixin(@a) when (default()) { /* styles for <=10 */ } |
| 8 | unit(dimension, newUnit?)Changes or removes the unit of a dimension. If newUnit is provided, it converts the dimension to that unit (if compatible, similar to convert but can also be used to strip units). If newUnit is omitted, it removes the unit, returning a unitless number. | @value: 20px; .element { line-height: unit(@value); /* 20 */ padding: unit(@value, em); /* e.g., 1.25em */ } |
| 9 | get-unit(dimension)Returns the unit(s) of a dimension as a keyword or a list of keywords (for complex units like px/s). | @length: 100px; @duration: 5s; ispixel(get-unit(@length)) // true (px)This is typically used within guard conditions or with other functions. |
| 10 | svg-gradient(direction, colorStop1, colorStop2, ...)Generates an SVG gradient string, often for use as a background image. This is a more specialized function. | .gradient-bg { background-image: svg-gradient(to right, #FF0000 0%, #0000FF 100%); }Output: .gradient-bg { background-image: url('data:image/svg+xml,...'); } (SVG data URI) |
These miscellaneous functions provide added flexibility for handling various data types and external resources within your LESS stylesheets.