Last active
March 2, 2023 11:58
-
-
Save aaronsummers/3177a01a0803134f29a3738b0871ad6e to your computer and use it in GitHub Desktop.
Conditional CSS widths using nth-child
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://grack.com/blog/2015/01/09/abusing-css3-selectors/ | |
// https://grack.com/assets/2015/01/nth-child/image-count.html | |
/* One */ | |
img:only-child { | |
max-width: 100%; | |
} | |
/* Two */ | |
img:first-child:nth-last-child(2) ~ img, img:first-child:nth-last-child(2) { | |
max-width: 49.5%; | |
margin-right: 1%; | |
} | |
/* Three */ | |
img:first-child:nth-last-child(3) ~ img, img:first-child:nth-last-child(3) { | |
max-width: 32.6%; | |
margin-right: 1%; | |
} | |
/* Four */ | |
img:first-child:nth-last-child(4) ~ img, img:first-child:nth-last-child(4) { | |
max-width: 24.25%; | |
margin-right: 1%; | |
} | |
/* Last image doesn't need a margin, regardless of count */ | |
img:nth-last-of-type(1) { | |
margin-right: 0 !important; | |
} | |
/* Five, eight, eleven, ... */ | |
/* First two are half-sized (99% / 2) */ | |
img:first-child:nth-last-child(3n+5) ~ img, img:first-child:nth-last-child(3n+5) { | |
max-width: 49.5%; | |
margin-right: 1%; | |
} | |
/* Last n - 2 are (98% / 3) */ | |
img:first-child:nth-last-child(3n+5) + img ~ img { | |
max-width: 32.6%; | |
margin-right: 1%; | |
} | |
/* But second, fifth, eighth, ... have no right margin */ | |
img:first-child:nth-last-child(3n+5) ~ img:nth-child(3n+2) { | |
margin-right: 0; | |
} | |
/* Six, nine, twelve, ... */ | |
/* Six, nine, twelve, ... are all (98% / 3) */ | |
img:first-child:nth-last-child(3n+6) ~ img, img:first-child:nth-last-child(3n+6) { | |
max-width: 32.6%; | |
margin-right: 1%; | |
} | |
/* Every third one of these has no right margin. */ | |
img:first-child:nth-last-child(3n+6) ~ img:nth-child(3n) { | |
margin-right: 0; | |
} | |
/* Seven, ten, thirteen, ... */ | |
/* First four are half-sized (99% / 2) */ | |
img:first-child:nth-last-child(3n+7) ~ img, img:first-child:nth-last-child(3n+7) { | |
max-width: 49.5%; | |
margin-right: 1%; | |
} | |
/* Last n - 4 are (98% / 3) */ | |
img:first-child:nth-last-child(3n+7) + img + img + img ~ img { | |
max-width: 32.6%; | |
margin-right: 1%; | |
} | |
/* The second and fourth, seventh, tenth, ... have no right margin */ | |
img:first-child:nth-last-child(3n+7) + img, | |
img:first-child:nth-last-child(3n+7) ~ img:nth-child(3n+4) { | |
margin-right: 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment