Aanpasbare Tegel met Spasiëring in CSS
Laat ons nou 'n tegel met spasiëring maak. Hier is 'n voorbeeld van wat ons moet kry:
Laat ons eers die style vir die ouerblok maak:
.parent {
display: flex;
flex-wrap: wrap;
width: 95%;
margin: 50px auto;
}
Nou stel ons style vir die blokke self, sonder om hul breedte te gee, maar deur 'n onderste spasiëring in persentasie te gee:
.child {
box-sizing: border-box;
height: 100px;
padding: 20px;
margin-bottom: 1.5%;
border: 1px solid green;
}
Nou skryf ons die kode wat vier blokke in 'n ry sal plaas, met die bybehorende spasiëring:
@media (min-width: 1000px) {
.child {
width: calc(100% / 4 - 1.5% * 3 / 4);
}
.child:not(:nth-child(4n)) {
margin-right: 1.5%;
}
}
En nou plaas ons drie blokke in 'n ry:
@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%;
}
}
En nou plaas ons twee blokke in 'n ry:
@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%;
}
}
Een blok in 'n ry:
@media (max-width: 400px) {
.child {
width: 100%;
}
}
Kom ons saam die hele kode:
.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%;
}
}
Maak 'n tegel wat, wanneer die skerm verklein word,
eers agt elemente in 'n ry sal hê,
dan vier elemente in 'n ry, dan twee elemente
in 'n ry. Laat die spasiëring tussen elemente
0.75% wees.
Verander die vorige taak sodat die
spasiëring tussen elemente 'n vaste
waarde van 20px is.