Skip to content

Instantly share code, notes, and snippets.

@aaronsummers
Last active March 2, 2023 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronsummers/3177a01a0803134f29a3738b0871ad6e to your computer and use it in GitHub Desktop.
Save aaronsummers/3177a01a0803134f29a3738b0871ad6e to your computer and use it in GitHub Desktop.
Conditional CSS widths using nth-child
// 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