How to calc() the number of rows in a grid template?

前端 未结 1 741
予麋鹿
予麋鹿 2021-01-18 15:54

I\'d like to calculate the number of rows in a grid template using calc(), but trying to get the repeat count with division isn\'t working:

1条回答
  •  北海茫月
    2021-01-18 16:24

    When using division with calc the result will be a number and not an integer thus it won't work because the repeat() expect an interger

    The generic form of the repeat() syntax is, approximately,

    repeat( [ | auto-fill | auto-fit ] , )ref

    And

    At /, check that the right side is . If the left side is , resolve to . Otherwise, resolve to the type of the left side.ref

    And

    Number values are denoted by , and represent real numbers, possibly with a fractional component.ref

    Even if we both know that the result will be an integer the browser will still consider it as a number.

    You can have the same issue with multiplication in case you have a number in one of the sides

    .grid {
      display: grid;
      grid-gap: 10px;
      grid-template-columns: 1fr;
      margin-bottom: 10px;
      background: rgba(0, 0, 0, 0.2);
    }
    
    .grid>div {
      background: tomato;
      width: 20px;
      text-align: center;
      margin: auto;
    }
    
    .grid.no-calc {
      grid-template-columns: repeat(3, 30px);
      border-bottom:3px solid red;
    }
    
    .grid.multiplication {
      grid-template-columns: repeat(calc(3 * 1.0), 30px); /*will fail*/
      border-bottom:calc(3px * 1.0) solid red;
    }
    
    .grid.division {
      grid-template-columns: repeat(calc(6 / 2), 30px);
      border-bottom:calc(6px / 2) solid red; /*this will work because border accept numbers*/
    }
    1
    2
    3
    1
    2
    3
    1
    2
    3


    Firefox is behaving differently and never fail even if we explicitely specify numbers. In all the cases Fiferox will try to round the result of calc() to a positive integer one.

    All the examples below will fail on Chrome and will work on Firefox:

    .grid {
      display: grid;
      grid-gap: 10px;
      grid-template-columns: 1fr;
      margin-bottom: 10px;
      background: rgba(0, 0, 0, 0.2);
    }
    
    .grid>div {
      background: tomato;
      width: 20px;
      text-align: center;
      margin: auto;
    }
    
    .grid.no-calc {
      grid-template-columns: repeat(calc(2.8), 30px); /*will be converted to 3*/
      border-bottom:calc(calc(2.8) * 1px) solid red;
    }
    
    .grid.multiplication {
      grid-template-columns: repeat(calc(3 * 1.55), 30px);  /*will be converted to 4*/
      border-bottom:calc(calc(3 * 1.55) * 1px) solid red;
    }
    
    .grid.division {
      grid-template-columns: repeat(calc(6 / 2.8), 30px); /*will be converted to 2*/
      border-bottom:calc(calc(6 / 2.8) * 1px) solid red;
      
    }
    1
    2
    3
    4
    1
    2
    3
    4
    1
    2
    3
    4

    0 讨论(0)
提交回复
热议问题