
概要
本文是在實(shí)際的電子商城項(xiàng)目開(kāi)發(fā)中分類中商品櫥窗展示中遇到的問(wèn)題以及解決的辦法。
主要有兩個(gè)方面:
第一、使用flex的方法實(shí)現(xiàn)自動(dòng)排列;
第二、正方形的CSS實(shí)現(xiàn)方法;
第一、是比較容易實(shí)現(xiàn)的,難點(diǎn)是在正方形的CSS實(shí)現(xiàn)方法。
如果要實(shí)現(xiàn)自適應(yīng)的正方形,難度是較大的。必須要讓width=hight。但是一般在流式布局的情況下,height要等于width,一般都必須使用js的方法。
這個(gè)時(shí)候就要用到一些巧妙的方法,讓height可以等于width。
使用Flex實(shí)現(xiàn)自動(dòng)排列,功能每行排三個(gè)
這個(gè)比較簡(jiǎn)單,直接上代碼
<div class="list" style="width:300px">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
<style>
.list{
display: flex;
flex-wrap: wrap;
flex-direction: row;
border: solid 1px black;
}
.list .item{
flex: 0 1 auto;
width: 33%;
text-align:center;
}
</style>
效果為:

正方形CSS的實(shí)現(xiàn)
第一種方法,使用paddint-bottom
設(shè)置padding-bottom撐開(kāi)容器,關(guān)鍵點(diǎn):padding可以用百分比,百分比是根據(jù)它包含塊的width來(lái)確定的,也就是父級(jí)元素的width。
也就是用padding-bottom:100%,這個(gè)100%是采用的width的值,自然就實(shí)現(xiàn)了寬和長(zhǎng)的相等。
具體代碼實(shí)現(xiàn):
<div style="border: solid 1px blue;width:80px">
<div class="square2">我和我的祖國(guó),一刻也不能分離</div>
</div>
<style>
.square2{
border:solid 1px red;
padding-bottom:100%;
height:0px;
}
</style>
關(guān)鍵部分:
- padding-bottom:100% 等于width;
- height: 0;如果不設(shè)置,div的內(nèi)容會(huì)把表格撐開(kāi);
第二種方法,使用兩個(gè)div,一個(gè)是外層的relative,一個(gè)是內(nèi)層的absolute,利用絕對(duì)定位消除空間占比。
實(shí)際上這個(gè)方法和上一個(gè)方法類似,依然是使用padding-bottom的屬性。
<div style="border: solid 1px red;width:80px">
<div class="square1" style="border: solid 1px blue;">
<div class="square2">我和我的祖國(guó),一刻也不能分離</div>
</div>
</div>
<style>
.square1{
position: relative;
padding-bottom:100%;
height: 0;
width: 100%;
}
.square2{
position: absolute;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
}
</style>
在此使用第二種方法實(shí)現(xiàn)櫥窗效果,其中將第二個(gè)內(nèi)層的absolute的div標(biāo)簽替換為img,在我的代碼中的具體實(shí)現(xiàn)為:
<div class="box-border flex-initial text-center" style="width:33.3%;padding:10px;" v-for="(item_1, index_1) in item.categorys" :key="index_1">
<!-- 正方形第一層 -->
<div style="display:block;border:0px;position:relative;padding: 50% 0px 50% 0px">
<!-- 正方形第二層 -->
<img style="position:absolute;top:0px;left:0px;width:100%;height:100%;vertical-align:top" :src="'' + $oss + '/' + item_1.url + ''" />
</div>
<!-- 分類名稱 -->
<div class="w-full text-center" style="font-size:12px;margin-top:5px;">{{ item_1.name }}</div>
</div>
具體實(shí)現(xiàn)效果:

總結(jié)
正方形的實(shí)現(xiàn)很巧妙,使用padding-bottom可以很容易實(shí)現(xiàn)。在具體的編碼中,多去學(xué)習(xí)前輩的經(jīng)驗(yàn),自己多聯(lián)系,就能達(dá)到逐步熟練,達(dá)到好的設(shè)計(jì)效果。