Adaptīva flīžu režģis ar atstarpēm CSS
Tagad izveidosim flīžu režģi ar atstarpēm. Lūk, piemērs tam, kas mums vajadzētu izveidot:
Vispirms izveidosim stilus bloku vecākam elementam:
.parent {
display: flex;
flex-wrap: wrap;
width: 95%;
margin: 50px auto;
}
Tagad noteiksim stilus pašiem blokiem, nenotekot tiem platumu, bet nosakot apakšējo atkāpi procentos:
.child {
box-sizing: border-box;
height: 100px;
padding: 20px;
margin-bottom: 1.5%;
border: 1px solid green;
}
Tagad uzrakstīsim kodu, kas novietos četrus blokus pēc kārtas, nosakot atbilstošās atstarpes:
@media (min-width: 1000px) {
.child {
width: calc(100% / 4 - 1.5% * 3 / 4);
}
.child:not(:nth-child(4n)) {
margin-right: 1.5%;
}
}
Un tagad novietosim trīs blokus pēc kārtas:
@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%;
}
}
Un tagad novietosim divus blokus pēc kārtas:
@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%;
}
}
Vienu bloku pēc kārtas:
@media (max-width: 400px) {
.child {
width: 100%;
}
}
Apvienosim visu kodu kopā:
.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%;
}
}
Izveidojiet flīžu režģi, kas, samazinot ekrāna izmēru,
sākumā rādīs astoņus elementus pēc kārtas,
tad četrus elementus pēc kārtas, tad divus elementus
pēc kārtas. Lai atstarpe starp elementiem būtu
0.75%.
Modificējiet iepriekšējo uzdevumu tā, lai
atstarpe starp elementiem būtu fiksēta
vērtība 20px.