Adaptyvi plytelė su tarpais CSS
Dabar sukurkime plytelę su tarpais. Štai pavyzdys, ką turėtume gauti:
Pirmiausia sukurkime stilius tėviniam elementui:
.parent {
display: flex;
flex-wrap: wrap;
width: 95%;
margin: 50px auto;
}
Dabar nustatykime stilius pačiems blokams, nenustatydami jiems pločio, bet nustatydami apatinę paraštę procentais:
.child {
box-sizing: border-box;
height: 100px;
padding: 20px;
margin-bottom: 1.5%;
border: 1px solid green;
}
Dabar parašykime kodą, kuris išdėstys keturis blokus iš eilės, nustatydamas atitinkamas tarpus:
@media (min-width: 1000px) {
.child {
width: calc(100% / 4 - 1.5% * 3 / 4);
}
.child:not(:nth-child(4n)) {
margin-right: 1.5%;
}
}
Dabar išdėstykime tris blokus iš eilės:
@media (min-width: 700px) and (max-width: 1000px) {
.child {
width: calc(100% / 3 - 1.5% * 2 / 3);
}
.child:not(:nth-child(3n)) {
margin-right: 1.5%;
}
}
Dabar išdėstykime du blokus iš eilės:
@media (min-width: 400px) and (max-width: 700px) {
.child {
width: calc(100% / 2 - 1.5% * 1 / 2);
}
.child:not(:nth-child(2n)) {
margin-right: 1.5%;
}
}
Vienas blokas iš eilės:
@media (max-width: 400px) {
.child {
width: 100%;
}
}
Sujungkime visą kodą kartu:
.parent {
display: flex;
flex-wrap: wrap;
width: 95%;
margin: 50px auto;
}
.child {
box-sizing: border-box;
height: 100px;
padding: 20px;
margin-bottom: 1.5%;
border: 1px solid green;
}
@media (max-width: 400px) {
.child {
width: 100%;
}
}
@media (min-width: 400px) and (max-width: 700px) {
.child {
width: calc(100% / 2 - 1.5% * 1 / 2);
}
.child:not(:nth-child(2n)) {
margin-right: 1.5%;
}
}
@media (min-width: 700px) and (max-width: 1000px) {
.child {
width: calc(100% / 3 - 1.5% * 2 / 3);
}
.child:not(:nth-child(3n)) {
margin-right: 1.5%;
}
}
@media (min-width: 1000px) {
.child {
width: calc(100% / 4 - 1.5% * 3 / 4);
}
.child:not(:nth-child(4n)) {
margin-right: 1.5%;
}
}
Sukurkite plytelę, kuri, mažinant ekraną,
pirmiausia turės aštuonis elementus iš eilės,
po to keturis elementus iš eilės, po to du elementus
iš eilės. Tegul tarpas tarp elementų sudaro
0.75%.
Modifikuokite ankstesnę užduotį taip, kad
tarpas tarp elementų būtų fiksuota
reikšmė 20px.