用css完成根據子元素不同書寫樣式
阿新 • • 發佈:2018-12-27
我們需要達到的效果:
需要什麼
1張圖片的, 2張圖片的, 3張圖片的樣式各不相同。可以使用js完成子元素的判斷,但是這裡我使用css來完成
核心知識點
使用css選擇器完成子元素的判斷
例子:
- 用css選擇器匹配只有一個元素
div {
&:last-child:nth-child(1) {
// 相關樣式
}
}
很好理解:div下面即是最後一個元素也是第一個元素不就是隻有一個子元素嗎?
- 用css選擇器匹配只有兩個子元素
div{ &:last-nth-child(2):nth-child(2) { } }
依樣畫瓢:最後第二個元素也是第二個元素不就代表,這個div下只有兩個元素嗎
完成樣式
- html部分
<div class="box" v-for="(item,index) in list" :key="index"> <div class="header"> <img :src="item.userImage" alt=""> <span>{{item.name}}</span> </div> <div class="content"> <img :src="v" alt="" v-for="(v, i) in item.imageUrl" :key="i"> </div> <div class="bottom"> <span class="left-icon">{{item.createTime}}</span> <div class="right"> <img src="./img/6.1.png" alt=""> <span>{{item.fabulousNumber}}</span> </div> </div> </div>
- css部分
.box { padding: 0.26rem; .header { display: flex; align-items: center; img { width: 0.58rem; height: 0.58rem; margin-right: 0.17rem; } } .bottom { display: flex; justify-content: space-between; align-items: center; color: #999999; font-size: 0.17rem; img { width: 0.17rem; height: 0.17rem; } } .content { display: flex; margin: 0.17rem 0; img { flex: 1; height: 1.37rem; width: 0; margin-right: 0.09rem; &:last-child { margin-right: 0; } &:last-child:nth-child(1) { height: 2.75rem; } } } }