See el­e­ment quan­ti­ties us­ing CSS coun­ters

net magazine - - PROJECTS -

CSS coun­ters can be used to de­ter­mine the quan­tity of any set of el­e­ments that can be tar­geted with CSS. To use a counter, first ini­tialise it in the par­ent us­ing counter-re­set: boxes where boxes can be any name you like. Then add coun­ter­in­cre­ment: boxes to the selec­tor that matches the el­e­ments you want to count. For in­stance, we can show the el­e­ment count con­cate­nated with text in each el­e­ment’s ::after pseudo-el­e­ment: . par­ent { counter- re­set: boxes; } . box { counter- in­cre­ment: boxes; } . box:: after { con­tent: “box “counter( boxes); }

We can also show the to­tal count in the par­ent us­ing the ::after el­e­ment of the last child, po­si­tioned ab­so­lutely to ap­pear in­side the par­ent. To han­dle plu­ral­i­sa­tion we can show dif­fer­ent mes­sages based on el­e­ment quan­tity by adding a sin­gu­lar case mes­sage to :only-of-type::after, and a plu­ral case to :nth-of-type(n+2):last-oftype::after, which matches el­e­ments that are last and also sec­ond or higher in their set: . par­ent { counter- re­set: boxes; po­si­tion: rel­a­tive; } . box { counter- in­cre­ment: boxes; } . box:: after { po­si­tion: ab­so­lute; left: 0; top: 0; } . box: only- of-type:: after { con­tent: counter( boxes) “box”; } . box: nth- of-type(n+2): last- of-type:: after { con­tent: counter( boxes) “boxes”; }

Quan­tity-spe­cific text: The num­ber of el­e­ments and quan­tity-spe­cific text can be dis­played in their par­ent us­ing coun­ters and pseudo-el­e­ments

Newspapers in English

Newspapers from Australia

© PressReader. All rights reserved.