使用CSS实现微信朋友圈的九宫格图片自适应 您所在的位置:网站首页 微信朋友圈照片缩小 使用CSS实现微信朋友圈的九宫格图片自适应

使用CSS实现微信朋友圈的九宫格图片自适应

2024-06-18 18:15| 来源: 网络整理| 查看: 265

大家应该都发过微信朋友圈,它最多发9张图片,不知大家有没有思考过,微信朋友圈的九宫格构图是怎么实现的,本篇博客将带领大家采用CSS就实现朋友圈这一功能。

四种情况

朋友圈发送1~9张不等数量的图片的时候,样式会有所变化,大体可分为以下4种情况。

一张图片,此时会完整的将整张图片展示出来

微信图片_20211222182657.jpg

2~3张图片,每张图片都会进行缩小,且大小一样,且在第一排依次排开(一排最多3张)

微信图片_20211222182651.jpg 微信图片_20211222182641.jpg

4张图片,每张图片都会进行缩小,且大小一样,每排各2张

微信图片_20211222182632.jpg

5~9张图片,每张图片都会进行缩小,且大小一样,每排各3张图,依次排列。

微信图片_20211222182645.jpg 代码分析

\color{#4285f4}{**css选择器**}

采用nth-child() 和nth-last-child()选择器

:nth-child(n) /* 选择器匹配属于其父元素的第 N 个子元素,不论元素的类型。 n 可以是数字、关键词或公式。 */ :nth-last-child(n) /* 选择器匹配属于其元素的第 N 个子元素的每个元素,不论元素的类型,从最后一个子元素开始计数。 n 可以是数字、关键词或公式。 */

\color{#4285f4}{**1张图片**}

一张图片的时候,我们直接将图片展示出来就可以了

.box { display: flex; flex-wrap: wrap; } .imageBox { position: relative; overflow: hidden; margin-bottom: 2%; width: 300px; } 1.jpg

\color{#4285f4}{**2 ~ 3张图片**}

2或3张图片时,图片排列在同一行

/* 2/3 */ .imageBox img:nth-child(1):nth-last-child(2), .imageBox img:nth-child(2):nth-last-child(1), .imageBox img:nth-child(1):nth-last-child(3), .imageBox img:nth-child(2):nth-last-child(2), .imageBox img:nth-child(3):nth-last-child(1) { width: 32%; } 2.jpg 3.jpg

\color{#4285f4}{**4张图片**}

每一行只有两个图片,且两张图片各占一半左右的宽度

/* 4 */ .imageBox img:nth-child(1):nth-last-child(4), .imageBox img:nth-child(2):nth-last-child(3), .imageBox img:nth-child(3):nth-last-child(2), .imageBox img:nth-child(4):nth-last-child(1) { width: 49%; } 4.jpg

\color{#4285f4}{**5~9张图片**}

和3种图片的时候排版是一样的,但是我们可以简化写法

/* 5~9 */ .imageBox img:nth-child(1):nth-last-child(n + 5), .imageBox img:nth-child(1):nth-last-child(n + 5)~img { width: 32%; } 9.jpg

\color{#4285f4}{**全部代码**}

模拟微信朋友圈九宫格排版 .box { display: flex; flex-wrap: wrap; } .imageBox { position: relative; overflow: hidden; margin-bottom: 2%; width: 300px; } /* 2/3 */ .imageBox img:nth-child(1):nth-last-child(2), .imageBox img:nth-child(2):nth-last-child(1), .imageBox img:nth-child(1):nth-last-child(3), .imageBox img:nth-child(2):nth-last-child(2), .imageBox img:nth-child(3):nth-last-child(1) { width: 32%; } /* 4 */ .imageBox img:nth-child(1):nth-last-child(4), .imageBox img:nth-child(2):nth-last-child(3), .imageBox img:nth-child(3):nth-last-child(2), .imageBox img:nth-child(4):nth-last-child(1) { width: 49%; } /* 5张以上图片 */ .imageBox img:nth-child(1):nth-last-child(n + 5), .imageBox img:nth-child(1):nth-last-child(n + 5)~img { width: 32%; }

\color{#4285f4}{**最后**}

如果本文能对大家有所帮助的话,点个\color{#ea4335}{赞}再走吧~ 欢迎大家 \color{#ea4335}{留言}交流~



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有