Using FEWER loops to create column classes on Twitter - What is their functionality?

Bootstrap utilizes various LESS mixins to create its column classes, along with other classes;

.make-grid-columns() {
  // Common styles for all sizes of grid columns, widths 1-12
  .col(@index) when (@index = 1) { // initial
    @item: ~".col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}";
    .col((@index + 1), @item);
  }
  .col(@index, @list) when (@index =< @grid-columns) { // general; "=<" isn't a typo
    @item: ~".col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}";
    .col((@index + 1), ~"@{list}, @{item}");
  }
  .col(@index, @list) when (@index > @grid-columns) { // terminal
    @{list} {
      position: relative;
      // Prevent columns from collapsing when empty
      min-height: 1px;
      // Inner gutter via padding
      padding-left:  (@grid-gutter-width / 2);
      padding-right: (@grid-gutter-width / 2);
    }
  }
  .col(1); // kickstart it
}

The use of LESS mixin guards helps in creating loops, as demonstrated in the LESS documentation examples;

.loop(@counter) when (@counter > 0) {
  .loop((@counter - 1));    // next iteration
  width: (10px * @counter); // code for each iteration
}

div {
  .loop(5); // launch the loop
}

Understanding the intricate nested guard expressions used by Bootstrap can be challenging. Would appreciate a detailed comment on the above Bootstrap code to shed more light on its functionality.

Answer №1

The main objective of the .make-grid-columns() mixin is to dynamically generate multiple selectors that share common properties. It's crucial for this list to be generated dynamically as the number of columns (@grid-columns) may vary and cannot be hardcoded into the code.

You provided a good example illustrating how loops work in Less within your question.

To fully grasp mixins, it's important to understand that Less allows you to use the same mixin name multiple times. All 'matching' mixins will be included in the final CSS output. Using mixin guards like when () allows you to set conditions for when a particular mixin should be compiled. If the condition isn't met, the mixin won't be included. Additionally, pattern matching can be employed to match values based on different criteria:

.mixin1(a,@width){}
.mixin1(b,@width){}

When calling .mixin(a,20px);, only the first mixin will be matched. Matching can also be based on the number of arguments passed (arity). For instance, .col(@index) when (@index = 1) doesn't require a guard because it has only one argument. Therefore, .col(1); will only match based on arity, not the guard condition. The .col(@index) mixin calls the .col(@index, @list) mixin(s). In cases where two mixins are needed instead of an if/else statement, Less supports the usage of multiple mixins to achieve the desired result.

Alternatively, a mixin with additional arguments can be utilized:

.mixin(@iterator; @item:~""; @seperator:~"") when (@iterator < 5){
@list: ~"@{item} @{seperator} @{iterator}";
.mixin((@iterator + 1); @list; ",");
}
.mixin(@iterator; @list; @seperator) when (@iterator = 5){
.selector{
@{list}: value;
}
}
.mixin(1);

In this setup, the @seperator variable changes between iterations to reflect the appropriate joining character needed within the selector list.

Selector interpolation is used in @{list} { } to incorporate the list of selectors along with their respective properties. Understanding and implementing these concepts is vital in working effectively with mixins in Less.

For more insights, I recommend reading the informative blog post by @seven-phases-max on generating selector lists using such structures.

Lastly, Bootstrap relies on an extensive list of selectors to avoid attribute selectors partially or entirely. The recommended CSS/Less approach offers an alternative way to handle column styling without relying heavily on attribute selectors, which could impact performance in certain situations.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for presenting text based on the chosen Select Option?

I attempted to achieve this using hrefs and ids, but it did not meet my requirements. This is the desired format: div.selectcountry { margin-bottom: 10px; font-family: arial; font-size: 12px; } div.countrydepartment { font-family: ...

What makes text-decoration a crucial element of the foreground design?

<span>Educating children on unlocking their creative and intellectual potential through the world of Computer Science.</span> Here is the HTML code provided above along with the corresponding CSS: span { text-decoration: underline; color: red ...

CSS - Make the entire div clickable while leaving a specific area non-clickable

I have a block containing some information. Within this div is a hidden button labeled .remove. Clicking on the main block will take you to another page, while hovering over the div will reveal the button. However, clicking the button also navigates you aw ...

What causes the element to load with a transparent appearance? And why is my JavaScript code overriding the hover effect on it?

My goal is to have an element fade out when clicked and then fade back in when its space is clicked again. I also want the opacity of the element to be 0.9 instead of 1 when visible. I've encountered two issues with my code. First, the hover selector ...

What is the best way to create a button that can cycle through various divs?

Suppose I want to create a scroll button that can navigate through multiple div elements. Here is an example code snippet: <div id="1"></div> <div id="2"></div> <div id="3"></div> <div id="4"></div> <div ...

Enhance the appearance of the table footer by implementing pagination with Bootstrap Angular6 Datatable styling

I utilized the angular 6 datatable to paginate the data in a table format. https://www.npmjs.com/package/angular-6-datatable Everything is functioning properly, but I am struggling with styling the footer of mfBootstrapPaginator. The items appear stack ...

Using Selenium ChromeDriver with Python to create a looped YouTube video playback feature

I have already tried looking for similar questions but haven't been able to find a solution. Does anyone know how to loop YouTube videos using Python Selenium ChromeDriver? Thank you in advance! ...

Arranging two printed shapes next to each other with a space in between each shape

My task is to display two diamond shapes side by side, with the number of rows specified by the user being half the size of each diamond. The issue I'm facing is that the middle rows of both diamonds are touching each other, and I need them to be sepa ...

Ideas for displaying or hiding columns, organizing rows, and keeping headers fixed in a vast data table using jQuery

My data table is massive, filled with an abundance of information. Firstly, I am looking to implement show/hide columns functionality. However, as the number of columns exceeds 10-12, the performance significantly decreases. To address this issue, I have ...

Implementing a JavaScript function that directs to the current page

I have set up my index page with a link that looks like this: <li onClick="CreateUser()"> <a href="#CreateUser">CreateUser</a> </li> When the "Create User" list item is clicked, the main page content is populated as follows: fun ...

Whenever I adjust the zoom on my HTML page, it either scrolls upwards or downwards

Is there a way to prevent the page from scrolling when using zoom-in or zoom-out? I attempted using overflow: hidden in the body, but it did not work. <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...

What is the best way to incorporate component-specific CSS styles in React?

This is the layout that I am attempting to replicate (originally from react-boilerplate): component |Footer |style.css |Footer.js In Footer.js, the styles are imported in a very elegant manner like this: import React from 'react'; im ...

Change the CSS property to override the text-overflow with ellipsis

In my specific scenario, I need to override the default ellipsis behavior that adds '...' to text when using 'text-overflow: ellipsis', and instead use two stars **. Is there a way to achieve this using only Pure CSS? It is important t ...

What strategies can be used to effectively structure CSS and JavaScript in a project for optimal organization?

In my NetBeans project, I currently have a large web project with CSS files included in the header. Some CSS codes are needed on all pages, while others are only necessary for specific pages. I am looking to optimize high-traffic pages by removing any ...

Raphael JS Path Animation: Wiping Away

I have successfully created a line animation using RaphaelJS, which can be viewed on this jsfiddle link - http://jsfiddle.net/7n040zdu/. My next challenge is to create an erasing animation that follows the initial one. This erasing animation should mimic t ...

Creating an appealing navbar in React by skillfully integrating the image logo and brand name for a

Having some trouble positioning my logo on the top left corner of the navbar. It keeps ending up in an awkward spot alongside the brand name. https://i.stack.imgur.com/XZjV9.png If anyone has any tips on how to properly align the logo and brand on the na ...

Setting the CSS position to fixed for a dynamically generated canvas using JavaScript

My goal is to fix the position style of the canvas using JavaScript in order to eliminate scroll bars. Interestingly, I can easily change the style using Chrome Inspector with no issues, but when it comes to implementing it through JS, I face difficulties. ...

CSS - selecting elements that are greater than a specific criteria N

I have multiple <p> tags in the body of my HTML. I want to display only the first two paragraphs and hide all the paragraphs that come after. However, the code I'm using doesn't seem to work as expected. <html> <head> < ...

Located at the lower section of the parent container

In my flex container, I have two boxes arranged side by side (collapsing into one column on smaller screens). I've ensured that these boxes have the same height when displayed together, as shown in the image below: Now, my goal is to position the ED ...

How can I retrieve the value of a <span> element for a MySQL star rating system?

Source: GitHub Dobtco starrr JS plugin Implementing this plugin to allow users to evaluate a company in various categories and store the feedback in a MySQL database. Enhancement: I have customized the javascript file to enable the use of star ratings fo ...