Search code examples
cssresponsive-designsassmedia-queries

In SCSS, how to refer the value in outer scope/block?


Following is the snippet in SCSS:

.element-a {
  position: absolute;
  right: 0;
  width: 216px;
  height: 232px;
  @media (max-width: 1000px) {
    right: 0;      // Half of 0
    width: 118px;  // Half of 216 px
    height: 116px; // Half of 232 px
  }
}

.element-b {
  position: absolute;
  width: 140px;
  height: 152px;
  right: 216px + 10px;
  @media (max-width: 1000px) {
    width: 70px; // Half of 140px
    height: 76px; // Half of 152px
    right: 113px; // Half of 226px
  }
}

As can be seen, if the media-query max-width:1000px is satisfied. The attributes right, width and height should be half of its original values. However, it looks not good practice to hardcode the value by calculating it manually..

Is there a better way to write this in SASS/SCSS? Or is there a way to refer the value in outer scope?


Solution

  • Use variables, here's an example:

    $b-width: 140px;
    
    .element-b {
        width: $b-width;
        @media (max-width: 1000px) {
            width: $b-width/2 // Half of $b-width
        }
    }