css 伪类来确定子元素个数 实现不同个数的不同展示效果
- element:first-child:nth-last-child(2) 有两个子元素 即第一个元素也是倒数第二个元素
- element:first-child:nth-last-child(n) 有n个子元素
- father:has(son:nth-last-child(n):first-child) son 统一设置
例子:微信朋友圈上传图片展示效果纯css 完成
h2,p,ul,li{
padding:0;
margin:0;
}
/* 标签样式 */
ul,li{
list-style: none;
}
/* 页面样式 */
.vessel{
width:400px;
/* 高度有内容决定 因为图片数量不确定 */
height: fit-content;
border:1px solid blue;
/* 左右两栏布局 */
display: flex;
flex-flow: row nowrap;
background-color: #000;
margin:auto;
}
.left_box{
width:80px;
height:100%;
img{
/* 图片的大小设置*/
width:60px;
height:60px;
/* 等比例缩放图片居中 */
object-fit:cover;
object-position: center;
/* 去除底部留白 */
vertical-align: middle;
/* 圆形边框 */
border-radius: 8px ;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
/* 在右边显示 auto起作用需块级元素 */
display: block;
margin:10px 5px 0px auto;
}
}
.flex_row_line{
display: flex;
flex-flow: row wrap;
justify-content: space-between;
align-items: center;
gap:8px;
}
.flex_column_line{
display: flex;
flex-flow: column nowrap;
justify-content: space-between;
align-items: start;
gap:8px;
}
.right_box{
/* 宽度剩余空间高度100% */
flex-grow: 1;
height:100%;
font-size:16px;
}
.username{
width:100%;
height:2em;
line-height: 2em;
color:#9AD9CA;
margin:10px 0px 0px;
font-size:inherit;
font-weight: 700;
}
.text{
/* 中文换行 会在标点符号或者空格换行 */
width:100%;
height:fit-content;
line-height:1.5em;
word-break: keep-all;
color:#F1FAEE;
}
.img_box{
width:96%;
/* 占剩余的高度大侠 */
flex-grow: 1;
/* background-color:#fff; */
margin-bottom:10px;
}
img{
width:100%;
height:100%;
object-fit:cover;
object-position: center;
vertical-align: middle;
}
/* 一张图片 ul 判断有一个li元素 */
.img_box:has(.item:last-child:first-child) .item{
width:100%;
height:260px;
}
/* 两张图片 */
.img_box:has(.item:nth-last-child(2):first-child) .item{
width: 48%;
height:200px;
}
/* 三张图 */
.img_box:has(.item:nth-last-child(3):first-child) .item{
width:30%;
height:180px;
}
/* 四张图 */
.img_box:has(.item:nth-last-child(4):first-child) .item{
width:48%;
height:150px;
}
/* 五张图 */
.img_box:has(.item:nth-last-child(5):first-child)
.item:nth-child(-n+3){
width:30%;
height:150px;
}
.img_box:has(.item:nth-last-child(5):first-child)
.item:nth-child(n+4){
width:48%;
height:150px;
}
/* 六张图 */
.img_box:has(.item:nth-last-child(6):first-child) .item{
width:30%;
height:100px;
}
<aside class="vessel">
<div class="left_box">
<img src="/00img/卡通头像.jpg" alt="头像">
</div>
<div class="right_box flex_column_line">
<h2 class="username">勿忘心安</h2>
<p class="text">打破我对百香果的认知,酸酸甜甜真的很好吃,一口气炫了三个😄</p>
<ul class="img_box flex_row_line">
<li class="item"><img src="/00img/敦煌舞.webp" alt="图片1"></li>
<li class="item"><img src="/00img/旗袍美女.webp" alt="图片1"></li>
<li class="item"><img src="/00img/旗袍美女.webp" alt="图片1"></li>
<li class="item"><img src="/00img/旗袍美女.webp" alt="图片1"></li>
</ul>
</div>
</aside>