CSS实现动态图片的九宫格布局

2,803 阅读3分钟

前提条件:content="width=750"

<meta name="viewport" content="width=750,user-scalable=no,target-densitydpi=device-dpi,viewport-fit=cover">

效果图如下:

效果图

需求分析

高宽:

  • 1张图【宽320,高320】[2倍稿尺寸]
  • 2张图时【宽332,高332】
  • 3张图、4张图、6张图,7张图、9张图时【宽220,高220】
  • 5张图、8张图时【第4、第5张宽高332】,【其余220】

间距:

  • 2张时,【最后一张】只有left方向margin
  • 3张时,【第2张】左右margin
  • 4张时,【第2张】和【最后一张】都只有left方向的margin,【3,4】有top方向的margin
  • 5张时,【最后一张】只有left方向margin
  • 6张、7张时,【第2张、第4张】有左右margin,从【第4张起】top有
  • 8张时,【第2张、第4张】时左右margin,从【第4张起】top有,【最后一张】只有left
  • 9张时,【第2张、第4张、第8张】有左右margin

圆角10:

  • 1张图时【都有】圆角
  • 2张图时、3张图-【第1张左上、左下】,【最后一张右上,右下】
  • 4张图时【第1张左上】,【第2张右上】,【第3张左下】,【最后一张右下】
  • 5张图时【第1张左上】,【第3张右上】,【第4张左下】,【最后一张右下】
  • 6张图时【第1张左上】,【第3张右上】,【第4张左下】,【最后一张右下】
  • 7张图时【第1张左上】,【第3张右上】,【第7张左下、右下】
  • 8张图时【第1张左上】,【第3张右上】,【第7张左下】,【最后一张右下】
  • 9张图时【第1张左上】,【第3张右上】,【第7张左下】,【最后一张右下】

归纳法

大家在中学的时候都学过数学的归纳法,就是一个命题先求出n=1的时候成立,然后假设n=k成立,证明n=k+1也成立,从而证得命题在n=k【k=任意实数】的时候都成立。

代码

<div class="grid-img-box">
    <van-image class='grid-img' v-for="value in data.photo" :key="value"  fit="cover" :src="value" />
</div>
.grid-img{

  /**
  宽高
    1. 3n+1且是倒数第2张时
    2. 3n+1且是最后一张时
      以上两种情况图片的宽高均应为320;
      剩余两种情况是:
    3. 只有一张时宽高320;
    4. 其余的情况和索引宽高都为220;
  */
  display: inline-block;
  width: 220px;
  height: 220px;
  &:only-child{
    width: 320px;
    height: 320px;
  }

  &:nth-child(3n+1):nth-last-child(2),
  &:nth-child(3n+2):last-child{
    width: 332px;
    height: 332px;
  }

  /**
  间距/布局
   */

  &:nth-child(3n+2){
    margin: 0 6px;
  }
  &:nth-child(n+4){
    margin-top: 6px;
  }

  &:first-child{
    border-top-left-radius: 10px;
  }

  &:last-child{
    margin-right: 0;
    border-bottom-right-radius: 10px;
  }

  /**
  圆角
   */

  //左下圆角:最后一行第一个
  &:nth-child(3n+1){
    &:last-child,
    &:nth-last-child(2),
    &:nth-last-child(3){
      border-bottom-left-radius: 10px;
    }
  }

  //处理四个布局
  //增大第二个margin讲第三个挤到下一行
  &:nth-child(2):nth-last-child(3){
    margin-right: 220px;
  }
  //重置第二个圆角
  &:nth-child(2):nth-last-child(3){
    border-top-right-radius: 10px;
  }

  //重置第三个的margin和radius
  &:nth-child(3):nth-last-child(2){
    margin-top: 6px;
    margin-right: 6px;
    border-radius: 0 0 0 10px;
  }
  //重置第4个的圆角
  &:nth-child(4):last-child{
     border-radius: 0 0 10px 0;
  }
}

参考文献 CSS实现自适应九宫格布局