skip to Main Content

This is the code I’ve written out, but there has to be a more condensed, elegant, and effective way to write media queries for scaling screens, right?

selector { padding-left: 19% }

@media only screen and (min-width: 1300px) {
  selector { padding-left: 17% }
}

@media only screen and (min-width: 1420px) {
  selector { padding-left: 17% }
}

@media only screen and (min-width: 1480px) {
  selector { padding-left: 16.5% }
}

@media only screen and (min-width: 1520px) {
  selector { padding-left: 16% }
}

@media only screen and (min-width: 1585px) {
  selector { padding-left: 15.5% }
}

@media only screen and (min-width: 1620px) {
  selector { padding-left: 15% }
}

@media only screen and (min-width: 1720px) {
  selector { padding-left: 14% }
}

@media only screen and (min-width: 1820px) {
  selector { padding-left: 13% }
}

@media only screen and (min-width: 1920px) {
  selector { padding-left: 12% }
}

2

Answers


  1. You can combine similar values and reduce
    last set of media queries, the padding value had a bit of variation, so I used the calc() function to handle it.

    
    @media only screen and (min-width: 1300px) {
      selector { padding-left: 17% }
    }
    
    @media only screen and (min-width: 1420px),
           only screen and (min-width: 1480px) {
      selector { padding-left: 16.5% }
    }
    
    @media only screen and (min-width: 1520px),
           only screen and (min-width: 1585px),
           only screen and (min-width: 1620px) {
      selector { padding-left: 16% }
    }
    
    @media only screen and (min-width: 1720px),
           only screen and (min-width: 1820px),
           only screen and (min-width: 1920px) {
      selector { padding-left: calc(14% - 1%); }
    }
    
    Login or Signup to reply.
  2. If you want to change padding based on the screen-width scaling linearly between 1420px and 1920px from 17% to 12% (though your code is not, it seems like that’s what you’re trying to achieve as shown below), you can use calc to calculate the growing proportion of padding based on both 100vw and pixel difference.

    enter image description here

    .wrapper {
      width: 100px;
      height: 100px;
    }
    
    .padding-box {
      padding-left: 19%;
      outline: 1px solid red;
    }
    
    @media only screen and (min-width: 1420px) {
      .padding-box {
        padding-left: calc(17% - (100vw - 1420px) * (17 - 12) / (1920 - 1420));
      }
    }
    
    @media only screen and (min-width: 1920px) {
      .padding-box {
        padding-left: 12%;
      }
    }
    <div class="wrapper">
      <div class="padding-box">
        123
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search