search

Home  >  Q&A  >  body text

How to use a calculator correctly?

:root {
    --offset: 30px;
  }

  .grid-cols-custom {
    /* 使用自定义属性和calc()计算列宽 */
    grid-template-columns: calc((424px / (100% - var(--offset))) * 100%)  calc((608px / (100% - var(--offset))) * 100%);

In a grid, I have two items, one is 424px and the other is 608px. I want them to be responsive. But padding and gaps can cause visual errors. So I want a percentage with calculation:

Logic: ((424px / (full width of div - 30px)) * 100%) so that our divs will always resize their width

please help me. Here's a problem reported by the CSS validator: "An operand must be a number"

I have been doing this for 4 hours: {

P粉046878197P粉046878197430 days ago725

reply all(1)I'll reply

  • P粉733166744

    P粉7331667442023-09-20 09:56:43

    Based on the values ​​you use, this seems to be the right thing to do. It's responsive and basically the same size with a 30px gap between them. I think your solution is too complex and fragile, especially on the responsive side.

    Your number:

    • 30px interval
    • First column width of 424px
    • Second column width of 608px
    • Basic total width: 1062px

    This is roughly a ratio of 40% to 60%. Using 4fr 6fr or better yet 2fr 3fr should be close enough.

    .grid {
      display: grid;
      grid-template-columns: 2fr 3fr;
      gap: 30px;
      height: 300px;
    }
    
    .col {
    background: lightseagreen;
    }
    <div class="grid">
      <div class="col">第一列:2fr</div>
      <div class="col">第二列:3fr</div>
    </div>

    If you prefer, we can get closer by using 424fr 608fr. This is an odd number, but it will be the exact value you are looking for. Of the total width, use 424 scores for the first column and 608 scores for the second column. Then add intervals.

    .grid {
      display: grid;
      grid-template-columns: 424fr 608fr;
      gap: 30px;
      height: 300px;
    }
    
    .col {
    background: lightseagreen;
    }
    <div class="grid">
      <div class="col">第一列:424fr</div>
      <div class="col">第二列:608fr</div>
    </div>

    reply
    0
  • Cancelreply