css根据元素中子元素的个数设置不同的样式

需求

一个div中图片的尺寸根据后台返回的个数决定,要求:

  1. 一张图片一行显示尺寸690px;
  2. 2张图片一行显示尺寸320px,4张图片两行显示,每行2张各占320px。
  3. 大于3张图片,每行3张排列,每张图片各占200px。

实现效果

一张图片
在这里插入图片描述
2张图片
在这里插入图片描述
3张图片
在这里插入图片描述
4张图片
在这里插入图片描述

9张图片
在这里插入图片描述

实现

    <div>
        <!-- 可逐个放开注释查看显示效果 -->
        <img src="https:\/\/images.dog.ceo\/breeds\/waterdog-spanish\/20180723_185544.jpg" alt="">
        <img src="https:\/\/images.dog.ceo\/breeds\/waterdog-spanish\/20180723_185544.jpg" alt="">
        <!-- <img src="https:\/\/images.dog.ceo\/breeds\/waterdog-spanish\/20180723_185544.jpg" alt="">
        <img src="https:\/\/images.dog.ceo\/breeds\/waterdog-spanish\/20180723_185544.jpg" alt="">
        <img src="https:\/\/images.dog.ceo\/breeds\/waterdog-spanish\/20180723_185544.jpg" alt="">
        <img src="https:\/\/images.dog.ceo\/breeds\/waterdog-spanish\/20180723_185544.jpg" alt="">
        <img src="https:\/\/images.dog.ceo\/breeds\/waterdog-spanish\/20180723_185544.jpg" alt="">
        <img src="https:\/\/images.dog.ceo\/breeds\/waterdog-spanish\/20180723_185544.jpg" alt="">
        <img src="https:\/\/images.dog.ceo\/breeds\/waterdog-spanish\/20180723_185544.jpg" alt=""> -->
    </div>
    </div>

css样式

        div {
    
    
            width: 750px;
            border: 2px solid gray;
        }
        /* 默认3张以上的样式(不包括4张) */
        div img {
    
    
            width: 200px;
            border: 2px solid red;
        }
        
        /* 当只有一张图片的样式 */
        div img:only-child {
    
    
            width: 690px;
            border: 2px solid red;
        }
        
        /* 既是倒数第二张又是第一张说明有两张图片 */
        div img:nth-last-child(2):first-child,
        /* ~表示同属于父类的所有img兄弟元素 */
        img:nth-last-child(2):first-child~img {
    
    
            width: 320px;
            border: 2px solid red;
        }
        
        /* 表示有四张图片 */
        div img:nth-last-child(4):first-child,
        img:nth-last-child(4):first-child~img {
    
    
            width: 320px;
            border: 2px solid red;
        }

Guess you like

Origin blog.csdn.net/weixin_43398820/article/details/121588455