Adaptiivne plokikujuline paigutus vahedega CSS-is
Teeme nüüd plokikujulise paigutuse vahedega. Siin on näide sellest, mida meil peaks saama:
Alustame, tehes plokkide vanemale stiilid:
.parent {
display: flex;
flex-wrap: wrap;
width: 95%;
margin: 50px auto;
}
Nüüd määrame plokkidele endile stiilid, andes neile laiuse, kuid andes alumise marginaali protsentides:
.child {
box-sizing: border-box;
height: 100px;
padding: 20px;
margin-bottom: 1.5%;
border: 1px solid green;
}
Nüüd kirjutame koodi, mis paneb neli plokki ritta, andes vastavad vahed:
@media (min-width: 1000px) {
.child {
width: calc(100% / 4 - 1.5% * 3 / 4);
}
.child:not(:nth-child(4n)) {
margin-right: 1.5%;
}
}
Nüüd paneme kolm plokki ritta:
@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%;
}
}
Nüüd paneme kaks plokki ritta:
@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%;
}
}
Üks plokk reas:
@media (max-width: 400px) {
.child {
width: 100%;
}
}
Paneme kogu koodi kokku:
.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%;
}
}
Tehke plokikujuline paigutus, mis ekraani vähenemisel
esmalt näitab kaheksat elementi reas,
siis nelja elementi reas, seejärel kahte elementi
reas. Olgu elementide vahe
0.75%.
Muutke eelmist ülesannet nii, et
elementide vahel oleks fikseeritud
väärtus 20px.