css如何使用repeat()函数

2023-05-15,

这篇文章将为大家详细讲解有关css如何使用repeat()函数,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

repeat()

repeat函数用来批量处理网格,接收2个参数,第一个参数表示执行次数,第二个参数表示长度。看下面例子

    <div class="repeat-wrapper">
      <div class="repeat-item">test1 3</div>
      <div class="repeat-item">test2 23</div>
      <div class="repeat-item">test3 444</div>
    </div>

      .repeat-wrapper {
        margin-top: 100px;
        display: grid;
        grid-template-columns: repeat(3, 100px);
        grid-gap: 10px;
      }

效果

grid-template-columns: repeat(3, 100px) 等价于 grid-template-columns: 100px 100px 100px;

auto-fill,auto-fit

第一个参数除了指明具体次数外,repeat还接收这几个参数 auto-fill,auto-fit,下面讲一讲这两个参数的概念。

auto-fill

auto-fill表示由浏览器自动根据项目填充次数。当容器很宽的时候,会自动留出剩余格子的宽度。如果网格容器在相关轴上具有确定的大小或最大大小,则重复次数是最大可能的正整数,不会导致网格溢出其网格容器。

    <div class="repeat-wrapper">
      <div class="repeat-item">test1 3</div>
      <div class="repeat-item">test2 23</div>
      <div class="repeat-item">test3 444</div>
      <div class="repeat-item">test3 4444</div>
      <div class="repeat-item">test3 444</div>
      <div class="repeat-item">test3 444</div>
    </div>

grid-template-columns: repeat(auto-fill, minmax(100px,1fr));

效果

auto-fit

auto-fit也会自动计算,但是与auto-fill不同的是,auto-fit不会保留剩余的空格子,会将auto-fill剩余的空格子重新分配到每个格子中。看下面示例

    <div class="repeat-wrapper">
      <div class="repeat-item">test1 3</div>
      <div class="repeat-item">test2 23</div>
      <div class="repeat-item">test3 444</div>
      <div class="repeat-item">test3 4444</div>
      <div class="repeat-item">test3 444</div>
      <div class="repeat-item">test3 444</div>
    </div>

grid-template-columns: repeat(auto-fit, minmax(100px,1fr));

效果

兼容性

最新版本的主流浏览器基本都能支持,依旧不支持ie。

关于“css如何使用repeat()函数”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

《css如何使用repeat()函数.doc》

下载本文的Word格式文档,以方便收藏与打印。