Search code examples
htmlcssmedia-queries

Is there a way to create a @media rule with kind of formula that describes the dependency between element CSS padding and max-width property?


There is a div that changes its padding-left CSS value depending on the page width. The padding value increases when page width decreases. If the page width is 1800px then the padding is 0px, if width=1700px then padding=10px, in other words:

|N| Page width | padding-left |
|-| -----------| ------------ |
|1| 1800px     | 0px          |
|2| 1700px     | 10px         |
|3| 1600px     | 20px         |
|.| ...        | ...          |
|9| 1000px     | 80px         |

For that, there were created 9 @media rules as shown below

@media (max-width: 1800px) {
    .my-padding {
        padding-left: 0px;
    }
}

@media (max-width: 1700px) {
    .my-padding {
        padding-left: 10px;
    }
}
...
...
@media (max-width: 1000px) {
    .my-padding {
        padding-left: 80px;
    }
}

Question: is there a way to create only one @media rule but to include a kind of formula that describes the dependency between CSS padding and max-width property? One solution can be to generate a separate CSS file programmatically with 9 desired @media rules

The formula for calculating the padding-left value can be the following:

padding-left = ((1800px - current_page_width) / 100) * 10

The problem is I do not know how to apply it


Solution

  • padding-left = ((1800 - current_page_width)/100)*10

    Could be : padding-left: calc( (1800px - 100vw ) * 0.1 );

    demo

    body {
      margin: 0;
      padding-left: calc( (1800px - 100vw) * 0.1);
      background: repeating-linear-gradient(to right, gray 0 10px, transparent 10px 20px);
    }
    <div style="border:solid;">div</div>