css3实现图片九宫格布局

转载自公众号前端印象

用到了css3中的:nth-child( n )选择器,以及:not(......)选择器和~兄弟选择器


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>微信朋友圈图片九宫格排版自适应(改编版)</title>
  <style>
    .pictures-adaptive {
      display: flex;
      flex-wrap: wrap;
    }

    .wrap {
      position: relative;
      overflow: hidden;
      margin-bottom: 2%;
    }

    /*  3张图片  */
    .wrap:nth-child(1):nth-last-child(3),
    .wrap:nth-child(2):nth-last-child(2),
    .wrap:nth-child(3):nth-last-child(1) 
    {
      width: 32%;
      padding-bottom: 32%;
    }

    /*  间隔  */
    .wrap:nth-child(2):nth-last-child(2),
    .wrap:nth-child(3):nth-last-child(1) 
    {
      margin-left: 2%;
    }

    .wrap:not(:nth-child(1):nth-last-child(1)) img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    /*  2张图片  */
    .wrap:nth-child(1):nth-last-child(2),
    .wrap:nth-child(2):nth-last-child(1),
    /*  4张图片  */
    .wrap:nth-child(1):nth-last-child(4),
    .wrap:nth-child(2):nth-last-child(3),
    .wrap:nth-child(3):nth-last-child(2),
    .wrap:nth-child(4):nth-last-child(1)
    {
      width: 49%;
      padding-bottom: 49%;
    }

    /* 每行的两张图片中间间隔2%的宽度 */
    /*  2张图片  */
    .wrap:nth-child(2):nth-last-child(1),
    /*  4张图片  */
    .wrap:nth-child(2):nth-last-child(3),
    .wrap:nth-child(4):nth-last-child(1)
    {
      margin-left: 2%;
    }

    /*  5张以上图片  */
    .wrap:nth-child(n + 5),
    .wrap:nth-child(1):nth-last-child(n + 5),
    .wrap:nth-child(1):nth-last-child(n + 5) ~ .wrap
    {
      width: 32%;
      padding-bottom: 32%;
    }

    .wrap:nth-child(n + 5):not(:nth-child(3n + 1)),
    .wrap:nth-child(1):nth-last-child(n + 5) ~ .wrap:not(:nth-child(3n + 1))
    {
      margin-left: 2%;
    }
  </style>
</head>
<body>
  <div class="pictures-adaptive">
    <div class="wrap">
      <img src="src1">
      <img src="src2">
      <img src="src3">
    </div>
  </div>
</body>
</html>
posted @ 2021-12-15 09:48  Bravo_Jack  阅读(327)  评论(0编辑  收藏  举报