Search code examples
cssstylesless

How to simplify my less file without repeating statement with different value?


There are five less statements, and they're all the same except the value for padding-right. Instead of repeating the statement five times, is there a way to simplify it into one statement?

h1 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 100px;
    }
  }
}
h3 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 50px;
    }
  }
}
h4 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 50px;
    }
  }
}
h5 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 25px;
    }
  }
}

Solution

  • Use mixins to reuse and not repeat the line of code.

    Mixins are a way of including ("mixing in") a bunch of properties from one rule-set into another rule-set.

    Exemple:

    item {
      a[href^="http://"], a[href^="https://"] {
        &:hover {
          background: 
            url(../../resources/icon/external-link-alt.svg)
            no-repeat 
            right;
        }
      }
    }
    

    And we want to use these properties inside other rule-sets. Well, we just have to drop in the name of the class where we want the properties, like so:

    h1 { 
      item();
      padding-right: 100px;
    }
    
    h3 { 
      item();
      padding-right: 75px;
    }
    
    h4 { 
      item();
      padding-right: 50px;
    }
    
    h5 { 
      item();
      padding-right: 25px;
    }
    
    

    This is very helpful if you want to change something in the future, as you only need to modify the mixins in one place 😉.