CSS verpakt: 2023!

CSS-omhulde header

CSS verpakt: 2023!

Wauw! 2023 was een geweldig jaar voor CSS!

Van #Interop2023 tot vele nieuwe landingen in de CSS- en UI-wereld die mogelijkheden bieden die ontwikkelaars ooit onmogelijk achtten op het webplatform. Nu ondersteunt elke moderne browser containerquery's, subgrids, de :has() selector en een hele reeks nieuwe kleurruimten en functies . We hebben ondersteuning in Chrome voor CSS-only scroll-gestuurde animaties en vloeiende animaties tussen webweergaven met weergaveovergangen . En als klap op de vuurpijl zijn er talloze nieuwe primitieven geland voor betere ontwikkelaarservaringen, zoals CSS-nesting en scoped styles.

Wat een jaar was het! En daarom willen we dit mijlpaaljaar afsluiten met een eerbetoon aan en erkenning voor al het harde werk van browserontwikkelaars en de webcommunity dat dit allemaal mogelijk heeft gemaakt.

Architectonische fundamenten

Laten we beginnen met updates van de kern-CSS-taal en -mogelijkheden. Dit zijn functies die fundamenteel zijn voor de manier waarop je stijlen maakt en organiseert, en die de ontwikkelaar veel mogelijkheden bieden.

Trigonometrische functies

Browser Support

  • Chroom: 111.
  • Rand: 111.
  • Firefox: 108.
  • Safari: 15.4.

Source

Chrome 111 heeft ondersteuning toegevoegd voor de trigonometrische functies sin() , cos() , tan() , asin() , acos() , atan() en atan2() , waardoor deze beschikbaar zijn in alle belangrijke engines. Deze functies zijn erg handig voor animatie- en lay-outdoeleinden. Het is bijvoorbeeld nu veel eenvoudiger om elementen op een cirkel rond een gekozen middelpunt te plaatsen.

Demo van trigonometrische functies

Leer meer over de trigonometrische functies in CSS .

Complexe n-* selectie

Browser Support

  • Chroom: 111.
  • Rand: 111.
  • Firefox: 113.
  • Safari: 9.

Met de pseudo-klasseselector :nth-child() is het mogelijk om elementen in de DOM te selecteren op basis van hun index. Met de An+B microsyntaxis krijgt u nauwkeurige controle over welke elementen u wilt selecteren.

Standaard houden de pseudo's :nth-*() rekening met alle onderliggende elementen. Vanaf Chrome 111 kun je optioneel een selectorlijst doorgeven aan :nth-child() en :nth-last-child() . Zo kun je de lijst met onderliggende elementen alvast filteren voordat An+B zijn werk doet.

In de volgende demo wordt de 3n+1 logica alleen toegepast op de kleine poppen door ze vooraf uit te filteren met behulp of .small . Gebruik de dropdownmenu's om de gebruikte selector dynamisch te wijzigen.

Complexe nth-* selectiedemo

Meer informatie over complexe n-* selecties .

Domein

Browser Support

  • Chroom: 118.
  • Rand: 118.
  • Firefox: achter een vlag.
  • Safari: 17.4.

Source

Chrome 118 heeft ondersteuning toegevoegd voor @scope , een at-regel waarmee je een selector kunt selecteren die overeenkomt met een specifieke substructuur van het document. Met scoped styling kun je heel specifiek bepalen welke elementen je selecteert, zonder dat je al te specifieke selectors hoeft te schrijven of ze strak aan de DOM-structuur hoeft te koppelen.

Een scoped subtree wordt gedefinieerd door een scoping root (de bovengrens) en een optionele scoping limit (de ondergrens).

@scope (.card) {  } /* scoping root */
@scope (.card) to (.card__content) {  } /* scoping root + scoping limit*/

Stijlregels die binnen een scopeblok worden geplaatst, richten zich alleen op elementen binnen de uitgehouwen subboom. De volgende scoped stijlregel richt zich bijvoorbeeld alleen op <img> -elementen die zich tussen het .card element en een geneste component bevinden die overeenkomt met de selector [data-component] .

@scope (.card) to ([data-component]) {
  img {  }
}

In de volgende demo komen de <img> -elementen in het carrouselcomponent niet overeen vanwege de toegepaste scopinglimiet.

Scope Demo Screenshot

Reference screenshot for the @scope demo

Live demo van Scope

CSS @ @scope demo

Lees meer over @scope in het artikel "Hoe @scope te gebruiken om het bereik van uw selectoren te beperken" . In dit artikel leert u over de selector :scope , hoe specificiteit wordt verwerkt, scopes zonder prelude en hoe de cascade wordt beïnvloed door @scope .

Nestelen

Browser Support

  • Chroom: 120.
  • Rand: 120.
  • Firefox: 117.
  • Safari: 17.2.

Source

Vóór het nesten moest elke selector expliciet en afzonderlijk van elkaar worden gedeclareerd. Dit leidde tot herhaling, een overvloed aan stylesheets en een versnipperde schrijfervaring. Nu kunnen selectors worden gecontinueerd met bijbehorende stijlregels die erin zijn gegroepeerd.

dl {
  /* dt styles */
  
  dt {
    /* dl dt styles */
  }

  dd {
    /* dl dd styles */
  }
}

/* same as */
dt {
  /* dt styles */
}

dl dt {
  /* dl dt styles */
}

dl dd {
  /* dl dd styles */
}

Nesting Screencast

Live demo van nesten

Verander de ontspannen nestselector om de winnaar van de race te bepalen

Nesten kan de zwaarte van een stylesheet verminderen, de overhead van herhalende selectors verminderen en componentstijlen centraliseren. De syntaxis werd aanvankelijk uitgebracht met een beperking die het gebruik van & op verschillende plaatsen vereiste, maar is sindsdien opgeheven met een update van de versoepelde syntaxis voor nesten .

Meer informatie over nestelen .

Subraster

Browser Support

  • Chroom: 117.
  • Rand: 117.
  • Firefox: 71.
  • Safari: 16.

Source

Met CSS subgrid kun je complexere rasters maken met een betere uitlijning tussen onderliggende lay-outs. Het zorgt ervoor dat een raster dat zich in een ander raster bevindt, de rijen en kolommen van het buitenste raster als zijn eigen raster kan overnemen door subgrid te gebruiken als waarde voor rasterrijen of -kolommen.

Subgrid-screencast

Subgrid Live Demo

Koptekst, hoofdtekst en voettekst worden afgestemd op de dynamische afmetingen van hun verwante tekstblokken.

Subgrid is vooral handig om verwante content af te stemmen op elkaars dynamische content. Dit bevrijdt copywriters, UX-schrijvers en vertalers van de moeite om projectteksten te schrijven die 'passen' in de lay-out. Met Subgrid kan de lay-out worden aangepast aan de content.

Meer informatie over subgrid .

Typografie

Webtypografie heeft in 2023 een paar belangrijke updates ondergaan. Een bijzonder mooie, progressieve verbetering is de text-wrap . Deze eigenschap maakt het mogelijk om de typografische lay-out aan te passen, opgesteld in de browser zonder dat er extra scripts nodig zijn. Zeg vaarwel tegen onhandige regellengtes en hallo tegen meer voorspelbare typografie!

Beginletter

Browser Support

  • Chroom: 110.
  • Rand: 110.
  • Firefox: niet ondersteund.
  • Safari: 9.

Source

De initial-letter eigenschap, die begin dit jaar in Chrome 110 verscheen, is een kleine maar krachtige CSS-functie die de stijl voor de plaatsing van beginletters bepaalt. Je kunt letters zowel in een neergelaten als in een verhoogde positie plaatsen. De eigenschap accepteert twee argumenten: de eerste geeft aan hoe diep de letter in de bijbehorende alinea moet komen te staan, en de tweede hoe ver de letter erboven moet komen te staan. Je kunt zelfs een combinatie van beide gebruiken, zoals in de volgende demo.

Schermafbeelding van de beginletter

Schermafbeelding van de demo van de beginletter

Demo van de beginletter

Wijzig de waarden van de initial-letter element ::first-letter om te zien hoe deze verschuift.

Meer informatie over de beginletter .

tekstomloop: balans en mooi

Als ontwikkelaar weet je niet wat de uiteindelijke grootte, lettergrootte of zelfs de taal van een kop of alinea is. Alle variabelen die nodig zijn voor een effectieve en esthetische verwerking van tekstomloop, bevinden zich in de browser. Omdat de browser alle factoren wel kent, zoals lettergrootte, taal en toegewezen ruimte, is deze een uitstekende kandidaat voor geavanceerde en hoogwaardige tekstopmaak.

Hier komen twee nieuwe tekstomlooptechnieken van pas: balance en pretty . De balance waarde streeft naar een harmonieus tekstblok, terwijl pretty probeert om 'orphans' te voorkomen en gezonde afbreking te garanderen. Beide taken werden traditioneel handmatig uitgevoerd, en het is fantastisch om de taak aan de browser over te laten en het voor elke vertaalde taal te laten werken.

Tekstomloop Screencast

Tekstomloop Live Demo

In de volgende demo kun je door de schuifbalk te verslepen de effecten van balance en pretty op een kop en een alinea vergelijken. Probeer de demo eens in een andere taal!

Meer informatie over tekstafbreking: balance .

Kleur

2023 was het jaar van kleur voor het webplatform. Met nieuwe kleurruimtes en functies die dynamische kleurthema's mogelijk maken, staat niets je meer in de weg om de levendige, weelderige thema's te creëren die je gebruikers verdienen, en ze bovendien aanpasbaar te maken!

HD-kleurruimten (kleurniveau 4)

Browser Support

  • Chroom: 111.
  • Rand: 111.
  • Firefox: 113.
  • Safari: 15.

Source

Browser Support

  • Chroom: 111.
  • Rand: 111.
  • Firefox: 113.
  • Safari: 15.

Source

Van hardware tot software, van CSS tot knipperende lichtjes; het kan onze computers veel werk kosten om kleuren zo goed mogelijk weer te geven. In 2023 hebben we nieuwe kleuren, meer kleuren, nieuwe kleurruimten, kleurfuncties en nieuwe mogelijkheden.

CSS en kleur kunnen nu: - Controleren of de schermhardware van de gebruiker HDR-kleuren met een breed kleurengamma ondersteunt. - Controleren of de browser van de gebruiker kleurensyntaxis zoals Oklch of Display P3 begrijpt. - HDR-kleuren specificeren in Oklab, Oklch, HWB, Display P3, Rec.2020, XYZ en meer. - Verlopen met HDR-kleuren maken. - Verlopen interpoleren in alternatieve kleurruimten. - Kleuren mengen met color-mix() . - Kleurvarianten maken met relatieve kleurensyntaxis.

Kleur 4 Screencast

Kleur 4 Demo

In de volgende demo kunt u door de schuifbalk te verslepen de effecten van 'balans' en 'mooi' op een kop en een alinea vergelijken. Probeer de demo eens in een andere taal te vertalen!

Leer meer over Kleur 4 en kleurruimten .

kleurmengfunctie

Browser Support

  • Chroom: 111.
  • Rand: 111.
  • Firefox: 113.
  • Safari: 16.2.

Source

Het mengen van kleuren is een klassieke taak en in 2023 kan CSS dat ook. Je kunt niet alleen wit of zwart in een kleur mengen, maar ook transparantie, en dit alles in elke gewenste kleurruimte. Het is tegelijkertijd een basiskleurfunctie en een geavanceerde kleurfunctie.

kleur-mix() Screencast

kleur-mix() demo

Met Demo kunt u met een kleurenkiezer twee kleuren kiezen, de kleurruimte selecteren en bepalen hoeveel van elke kleur dominant moet zijn in de mix.

Je kunt color-mix() zien als een moment in de tijd van een gradiënt. Waar een gradiënt alle stappen laat zien die nodig zijn om van blauw naar wit te gaan, laat color-mix() slechts één stap zien. Het wordt geavanceerder zodra je rekening begint te houden met kleurruimten en leert hoe verschillend de mengkleurruimte kan zijn van de resultaten.

Meer informatie over color-mix() .

Relatieve kleursyntaxis

Relatieve kleursyntaxis (RCS) is een complementaire methode voor color-mix() voor het creëren van kleurvarianten. Het is iets krachtiger dan color-mix(), maar biedt ook een andere strategie voor het werken met kleur. color-mix() kan de kleur wit mengen om een ​​kleur lichter te maken, terwijl RCS nauwkeurige toegang biedt tot het helderheidskanaal en de mogelijkheid biedt om calc() op het kanaal te gebruiken om de helderheid programmatisch te verlagen of te verhogen.

RCS-schermopname

RCS Live-demo

Verander de kleur, verander de scènes. Elk gebruikt relatieve kleurensyntaxis om varianten van de basiskleur te creëren.

Met RCS kun je relatieve en absolute manipulaties op een kleur uitvoeren. Een relatieve wijziging is een wijziging waarbij je de huidige waarde van verzadiging of helderheid neemt en deze wijzigt met calc() . Een absolute wijziging is een wijziging waarbij je een kanaalwaarde vervangt door een geheel nieuwe, zoals het instellen van de dekking op 50%. Deze syntaxis biedt je handige tools voor thema's, just-in-time-varianten en meer.

Meer informatie over relatieve kleursyntaxis .

Responsief ontwerp

Responsief design is in 2023 geëvolueerd. Dit baanbrekende jaar maakte nieuwe functies mogelijk die de manier waarop we responsieve webervaringen bouwen volledig veranderen, en luidde een nieuw model van componentgebaseerd responsief design in. De combinatie van containerquery's en :has() ondersteunt componenten die hun responsieve en logische stijl bepalen op basis van de grootte van hun bovenliggende component, evenals de aanwezigheid of status van hun onderliggende componenten. Dat betekent dat je eindelijk de lay-out op paginaniveau kunt scheiden van de lay-out op componentniveau, en de logica één keer kunt schrijven om je component overal te gebruiken!

Grootte container query's

Browser Support

  • Chroom: 105.
  • Rand: 105.
  • Firefox: 110.
  • Safari: 16.

Source

In plaats van de globale grootte-informatie van de viewport te gebruiken om CSS-stijlen toe te passen, ondersteunen containerquery's het opvragen van een bovenliggend element binnen de pagina. Dit betekent dat componenten dynamisch kunnen worden gestyled in meerdere lay-outs en weergaven. Containerquery's voor grootte zijn sinds Valentijnsdag dit jaar (14 februari) stabiel in alle moderne browsers.

Om deze functie te gebruiken, stelt u eerst containment in voor het element dat u queryt en gebruikt u vervolgens, net als bij een mediaquery, @container met de grootteparameters om de stijlen toe te passen. Samen met containerquery's krijgt u containerquerygroottes. In de volgende demo wordt de containerquerygrootte cqi (die de grootte van de inline container vertegenwoordigt) gebruikt om de grootte van de kaartheader te bepalen.

@container Screencast

@container Demo

Meer informatie over het gebruik van containerquery's .

Stijlcontainerquery's

Browser Support

  • Chroom: 111.
  • Rand: 111.
  • Firefox: niet ondersteund.
  • Safari: 18.

Stijlquery's zijn gedeeltelijk geïmplementeerd in Chrome 111. Met stijlquery's kunt u momenteel de waarde van aangepaste eigenschappen van een bovenliggend element opvragen met behulp van @container style() . U kunt bijvoorbeeld opvragen of een aangepaste eigenschapswaarde bestaat of is ingesteld op een bepaalde waarde, zoals @container style(--rain: true) .

Schermafbeelding van stijlquery

Demo-screenshot voor stijlcontainerquery's voor weerkaarten

Stijlquery-demo

Verander de kleur, verander de scènes. Elk gebruikt relatieve kleurensyntaxis om varianten van de basiskleur te creëren.

Hoewel dit lijkt op het gebruik van klassenamen in CSS, hebben stijlquery's een aantal voordelen. Ten eerste kunt u met stijlquery's de waarde in CSS indien nodig bijwerken voor pseudostatussen. In toekomstige versies van de implementatie kunt u bovendien reeksen waarden opvragen om de toegepaste stijl te bepalen, zoals style(60 <= --weather <= 70) , en stijl op basis van eigenschap-waardeparen, zoals style(font-style: italic) .

Meer informatie over het gebruik van stijlquery's .

:has()-selector

Browser Support

  • Chroom: 105.
  • Rand: 105.
  • Firefox: 121.
  • Safari: 15.4.

Source

Bijna 20 jaar lang vroegen ontwikkelaars om een ​​"parent selector" in CSS. Met de :has() selector die standaard in Chrome 105 werd meegeleverd, is dit nu mogelijk. Met .card:has(img.hero) worden bijvoorbeeld de .card elementen geselecteerd die een hero-afbeelding als child hebben.

:has() Demo-screenshot

Reference screenshot for the :has() demo

:has() Live demo

CSS :has() demo: Kaart zonder/met afbeelding

Omdat :has() een relatieve selectorlijst als argument accepteert, kun je veel meer selecteren dan alleen het bovenliggende element. Met behulp van diverse CSS-combinators is het niet alleen mogelijk om hoger in de DOM-tree te gaan, maar ook zijwaartse selecties uit te voeren. Zo selecteert li:has(+ li:hover) het <li> -element dat voorafgaat aan het <li> -element waar momenteel de muis boven hangt.

:has() Screencast

:has() Demo

CSS :has() demo: Dock

Meer informatie over de CSS :has() selector .

Media query bijwerken

Browser Support

  • Chroom: 113.
  • Rand: 113.
  • Firefox: 102.
  • Safari: 17.

Source

Met de update media query kunt u de gebruikersinterface aanpassen aan de vernieuwingsfrequentie van een apparaat. De functie kan een waarde van fast , slow of none rapporteren, afhankelijk van de mogelijkheden van verschillende apparaten.

De meeste apparaten waarvoor u ontwerpt, hebben waarschijnlijk een hoge verversingssnelheid. Dit geldt voor desktops en de meeste mobiele apparaten. E-readers en apparaten zoals betaalsystemen met een laag vermogen kunnen een lage verversingssnelheid hebben. Wetende dat het apparaat geen animaties of frequente updates aankan, kunt u batterijverbruik of foutieve weergave-updates besparen.

Schermcast bijwerken

Demo bijwerken

Simuleer (door een keuzerondje te kiezen) een updatesnelheidswaarde en bekijk hoe dit de eend beïnvloedt.

Lees meer over @media (update) .

Scripting media query

Browser Support

  • Chroom: 120.
  • Rand: 120.
  • Firefox: 113.
  • Safari: 17.

Source

De scripting media query kan worden gebruikt om te controleren of JavaScript beschikbaar is. Dit is erg handig voor progressieve verbetering. Vóór deze media query was een strategie om te detecteren of JavaScript beschikbaar was, het plaatsen van een nojs -klasse in de HTML en deze te verwijderen met JavaScript. Deze scripts kunnen worden verwijderd, omdat CSS nu een manier heeft om JavaScript te detecteren en dienovereenkomstig aan te passen.

Leer hier hoe u JavaScript op een pagina kunt in- en uitschakelen voor testen via Chrome DevTools .

Scripting Screencast

Scripting-demo

Denk aan een thema-switch op een website. De scripting media query kan helpen om de switch te laten werken tegen de systeemvoorkeur in, aangezien er geen JavaScript beschikbaar is. Of denk aan een switchcomponent: als JavaScript beschikbaar is, kan de switch met een veegbeweging worden bediend in plaats van alleen maar aan en uit te zetten. Er zijn talloze geweldige mogelijkheden om de gebruikerservaring te verbeteren als scripting beschikbaar is, terwijl er tegelijkertijd een zinvolle basiservaring wordt geboden als scripting is uitgeschakeld.

Meer informatie over script .

Media query met verminderde transparantie

Browser Support

  • Chroom: 118.
  • Rand: 118.
  • Firefox: achter een vlag.
  • Safari: niet ondersteund.

Source

Niet-ondoorzichtige interfaces kunnen hoofdpijn veroorzaken of een visuele uitdaging vormen voor diverse visuele beperkingen. Daarom hebben Windows, macOS en iOS systeemvoorkeuren waarmee de transparantie van de gebruikersinterface kan worden verminderd of verwijderd. Deze media query voor prefers-reduced-transparency sluit goed aan bij de andere voorkeursmedia query's, waardoor je creatief kunt zijn en tegelijkertijd gebruikers kunt aanpassen.

Screencast met verminderde transparantie

Demo met verminderde transparantie

In sommige gevallen kun je een alternatieve lay-out bieden waarbij content niet over andere content heen wordt gelegd. In andere gevallen kan de dekking van een kleur worden aangepast zodat deze dekkend of bijna dekkend is. De volgende blogpost bevat meer inspirerende demo's die zich aanpassen aan de voorkeuren van de gebruiker. Neem een ​​kijkje als je benieuwd bent naar momenten waarop deze media query waardevol is.

Meer informatie over @media (prefers-reduced-transparency) .

Interactie

Interactie is een hoeksteen van digitale ervaringen. Het helpt gebruikers feedback te krijgen over waar ze op hebben geklikt en waar ze zich in een virtuele ruimte bevinden. Dit jaar zijn er veel interessante functies gelanceerd die het samenstellen en implementeren van interacties eenvoudiger hebben gemaakt, wat zorgt voor soepele gebruikerservaringen en een verfijndere webervaring.

Bekijk overgangen

Browser Support

  • Chroom: 111.
  • Rand: 111.
  • Firefox: 144.
  • Safari: 18.

Source

Weergaveovergangen hebben een enorme impact op de gebruikerservaring van een pagina. Met de View Transitions API kunt u visuele overgangen creëren tussen twee paginastatussen van uw Single Page Application. Deze overgangen kunnen volledige pagina's beslaan, of kleinere elementen op een pagina, zoals het toevoegen of verwijderen van een nieuw item aan een lijst.

De kern van de View Transitions API is de functie document.startViewTranstion . Geef een functie mee die de DOM bijwerkt naar de nieuwe status, en de API regelt alles voor je. Dit gebeurt door een snapshot van voor en na te maken en vervolgens tussen beide te schakelen. Met CSS kun je bepalen wat er wordt vastgelegd en optioneel aanpassen hoe deze snapshots worden geanimeerd.

VT-schermopname

VT-demo

Bekijk de Transitions-demo

De View Transitions API voor Single Page Applications is meegeleverd in Chrome 111. Meer informatie over View Transitions .

Lineaire-easing-functie

Browser Support

  • Chroom: 113.
  • Rand: 113.
  • Firefox: 112.
  • Safari: 17.2.

Source

Laat je niet misleiden door de naam van deze functie. De functie linear() (niet te verwarren met het trefwoord linear ) stelt je in staat om op een eenvoudige manier complexe easing-functies te maken, met als nadeel dat dit ten koste gaat van de precisie.

Vóór linear() , dat standaard in Chrome 113 werd geïntroduceerd, was het onmogelijk om bounce- of springeffecten in CSS te creëren. Dankzij linear() is het mogelijk om deze easings te benaderen door ze te vereenvoudigen tot een reeks punten en vervolgens lineair tussen deze punten te interpoleren.

Chart of a bounce easing curve with several dots added to it
De originele bouncecurve in blauw wordt vereenvoudigd door een set belangrijke punten, weergegeven in groen. De functie linear() gebruikt deze punten en interpoleert lineair tussen deze punten.

Lineaire-easing Screencast

Demo van lineaire versoepeling

CSS linear() demo.

Meer informatie over linear() . Gebruik de lineaire easinggenerator om linear() curven te maken.

Scroll einde

Browser Support

  • Chroom: 114.
  • Rand: 114.
  • Firefox: 109.
  • Safari: niet ondersteund.

Source

Veel interfaces bevatten scrollinteracties, en soms moet de interface informatie synchroniseren die relevant is voor de huidige scrollpositie, of gegevens ophalen op basis van de huidige status. Vóór de scrollend -gebeurtenis moest je een onnauwkeurige time-outmethode gebruiken die kon worden geactiveerd terwijl de vinger van de gebruiker nog op het scherm was. Met de scrollend -gebeurtenis heb je een perfect getimede scrollend-gebeurtenis die herkent of een gebruiker nog midden in een gebaar zit of niet.

Scrollend Screencast

Scrollend-demo

Dit was belangrijk voor de browser, omdat JavaScript de aanwezigheid van een vinger op het scherm tijdens het scrollen niet kan volgen; de informatie is simpelweg niet beschikbaar. Stukken onnauwkeurige code voor het einde van een scrollpoging kunnen nu worden verwijderd en vervangen door een zeer nauwkeurige gebeurtenis die door de browser wordt beheerd.

Meer informatie over scrollend .

Scroll-gestuurde animaties

Browser Support

  • Chroom: 115.
  • Rand: 115.
  • Firefox: achter een vlag.
  • Safari: 26.

Source

Scroll-gestuurde animaties zijn een interessante functie in Chrome 115. Hiermee kun je een bestaande CSS-animatie of een animatie die is gemaakt met de Web Animations API koppelen aan de scrolloffset van een scroller. Terwijl je omhoog en omlaag scrolt – of naar links en rechts in een horizontale scroller – scrolt de gekoppelde animatie direct vooruit en achteruit.

Met een ScrollTimeline kun je de algehele voortgang van een scroller volgen, zoals gedemonstreerd in de volgende demo. Naarmate je naar het einde van de pagina scrollt, wordt de tekst teken voor teken zichtbaar.

SDA-schermopname

SDA-demo

Demo van CSS-scroll-gestuurde animaties: scrolltijdlijn

Met een ViewTimeline kun je een element volgen terwijl het de scrollport passeert. Dit werkt op een vergelijkbare manier als hoe IntersectionObserver een element volgt. In de volgende demo onthult elke afbeelding zichzelf vanaf het moment dat deze de scrollport binnenkomt tot het moment dat deze in het midden staat.

SDA Demo Screencast

SDA Live-demo

Demo van CSS-scroll-gestuurde animaties: bekijk de tijdlijn

Omdat scroll-gestuurde animaties werken met CSS-animaties en de Web Animations API, profiteer je van alle voordelen die deze API's bieden. Zo kun je deze animaties ook vanuit de hoofdthread laten lopen. Je kunt nu zijdezachte animaties hebben, aangestuurd door scrollen, die vanuit de hoofdthread lopen met slechts een paar regels extra code – wat is er niet leuk aan?

Wilt u meer weten over scroll-animaties ? Bekijk dan dit artikel met alle details of bezoek scroll-driven-animations.style , waar u veel demo's kunt vinden.

Uitgestelde tijdlijnbijlage

Browser Support

  • Chroom: 116.
  • Rand: 116.
  • Firefox: niet ondersteund.
  • Safari: 26.

Source

Bij het toepassen van een scroll-aangedreven animatie via CSS doorloopt het zoekmechanisme om de besturende scroller te vinden altijd de DOM-tree, waardoor het beperkt blijft tot scroll-voorouders. Heel vaak is het te animeren element echter geen child van de scroller, maar een element in een compleet andere subtree.

Om het geanimeerde element een benoemde scroll-tijdlijn van een niet-voorouder te laten vinden, gebruikt u de eigenschap timeline-scope op een gedeelde bovenliggende entiteit. Hierdoor kan de gedefinieerde scroll-timeline of view-timeline met die naam eraan worden gekoppeld, waardoor deze een breder bereik krijgt. Hierdoor kan elk kind van die gedeelde bovenliggende entiteit de tijdlijn met die naam gebruiken.

Visualization of a DOM subtree with timeline-scope used on a shared parent
Als timeline-scope is gedeclareerd op de gedeelde ouder, kan de scroll-timeline die is gedeclareerd op de scroller worden gevonden door het element dat deze gebruikt als animation-timeline

Demo-screencast

Live demo

Demo van CSS-scroll-gestuurde animaties: uitgestelde tijdlijn-bijlage

Meer informatie over timeline-scope .

Discrete eigendomsanimaties

Een andere nieuwe mogelijkheid in 2023 is de mogelijkheid om discrete animaties te animeren, zoals animeren van en naar display: none . Vanaf Chrome 116 kunt u display en content-visibility gebruiken in keyframeregels. U kunt ook een discrete eigenschap laten overgaan op het 50%-punt in plaats van op het 0%-punt. Dit kunt u doen met de eigenschap transition-behavior met behulp van het trefwoord allow-discrete , of in de eigenschap transition als een verkorte notatie.

Discrete animatie screencast

Discrete Anim. Demo

Meer informatie over de overgang van discrete animaties .

@starting-style

Browser Support

  • Chroom: 117.
  • Rand: 117.
  • Firefox: 129.
  • Safari: 17.5.

Source

De CSS-regel @starting-style bouwt voort op nieuwe webmogelijkheden voor animaties van en naar display: none . Deze regel biedt een manier om een ​​element een "before-open"-stijl te geven die de browser kan opzoeken voordat het element op de pagina wordt geopend. Dit is erg handig voor entry-animaties en voor het animeren in elementen zoals een pop-over of dialoogvenster. Het kan ook handig zijn wanneer u een element aanmaakt en het de mogelijkheid wilt geven om erin te animeren. Neem het volgende voorbeeld, waarin een popover -attribuut (zie volgende sectie) soepel van buiten de viewport in beeld en in de bovenste laag wordt geanimeerd.

@starting-style Screencast

@starting-style Demo

Lees meer over @starting-style en andere entree-animaties.

Overlay

Browser Support

  • Chroom: 117.
  • Rand: 117.
  • Firefox: niet ondersteund.
  • Safari: niet ondersteund.

Source

De nieuwe CSS- overlay eigenschap kan aan je overgang worden toegevoegd om elementen met stijlen in de bovenste laag, zoals popover en dialog , soepel uit de bovenste laag te laten animeren. Als je geen overlay-overgang gebruikt, wordt je element direct weer bijgesneden, getransformeerd en bedekt, en zie je de overgang niet. Op dezelfde manier zorgt overlay ervoor dat ::backdrop soepel uit de bovenste laag wordt geanimeerd wanneer het aan een element in de bovenste laag wordt toegevoegd.

Overlay-schermopname

Overlay Live Demo

Meer informatie over overlay- en andere exit-animaties.

Componenten

2023 was een belangrijk jaar voor de kruising van stijl en HTML-componenten, met popover -landingen en veel werk rond ankerpositionering en de toekomst van de styling van dropdownmenu's. Deze componenten maken het eenvoudiger om veelgebruikte UI-patronen te bouwen zonder dat je afhankelijk bent van extra bibliotheken of elke keer je eigen statusbeheersystemen vanaf de grond af aan hoeft te bouwen.

Popover

Browser Support

  • Chroom: 114.
  • Rand: 114.
  • Firefox: 125.
  • Safari: 17.

Source

Met de Popover API kunt u elementen bouwen die bovenop de rest van de pagina worden geplaatst. Dit kunnen menu's, selecties en tooltips zijn. U kunt een eenvoudige popover maken door het popover -attribuut en een id toe te voegen aan het element dat verschijnt, en het id -attribuut te koppelen aan een oproepende knop met behulp van popovertarget="my-popover" . De Popover API ondersteunt:

  • Promotie naar de bovenste laag. Popovers verschijnen op een aparte laag boven de rest van de pagina, zodat u niet met de z-index hoeft te spelen.
  • Licht-verwijderfunctie. Door buiten het pop-overgebied te klikken, wordt de pop-over gesloten en keert de focus terug.
  • Standaard focusbeheer. Bij het openen van de pop-over wordt de volgende tabstop binnen de pop-over geplaatst.
  • Toegankelijke toetsenbordindelingen. Door op de esc -toets te drukken of dubbel te schakelen, sluit u de pop-over en keert u terug naar de focus.
  • Toegankelijke componentbindingen. Een popover-element semantisch verbinden met een popover-trigger.

Popover-schermopname

Popover Live Demo

Horizontale regels in selectie

Een andere kleine HTML-wijziging die dit jaar in Chrome en Safari is geïntroduceerd, is de mogelijkheid om horizontale regelelementen ( <hr> -tags) toe te voegen aan <select> -elementen om je content visueel op te splitsen. Voorheen werd een <hr> -tag in een select-element niet weergegeven. Maar dit jaar ondersteunen zowel Safari als Chrome deze functie, waardoor content binnen <select> -elementen beter gescheiden kan worden.

Schermafbeelding selecteren

screenshot van hr in select met een licht en donker thema in Chrome

Selecteer Live Demo

Leer meer over het gebruik van hr in geselecteerde

:gebruiker-geldige en ongeldige pseudo-klassen

Browser Support

  • Chroom: 119.
  • Rand: 119.
  • Firefox: 88.
  • Safari: 16.5.

Source

De :user-valid en :user-invalid zijn dit jaar stabiel in alle browsers en gedragen zich vergelijkbaar met de pseudoklassen :valid en :invalid . Ze matchen echter alleen een formulierbesturingselement nadat een gebruiker significante interactie met de invoer heeft gehad. Een formulierbesturingselement dat verplicht en leeg is, matcht :invalid zelfs als een gebruiker nog niet met de pagina is begonnen. Hetzelfde besturingselement matcht :user-invalid pas nadat de gebruiker de invoer heeft gewijzigd en deze in een ongeldige status heeft gelaten.

Met deze nieuwe selectors is het niet langer nodig om stateful code te schrijven om bij te houden welke invoer een gebruiker heeft gewijzigd.

:user-* Schermopname

:user-* Live demo

Meer informatie over het gebruik van pseudo-elementen voor gebruikers-* formuliervalidatie .

Exclusieve accordeon

Browser Support

  • Chroom: 120.
  • Rand: 120.
  • Firefox: 130.
  • Safari: 17.2.

Een veelgebruikt UI-patroon op het web is een accordioncomponent. Om dit patroon te implementeren, combineert u een aantal <details> -elementen, vaak visueel gegroepeerd om aan te geven dat ze bij elkaar horen.

Nieuw in Chrome 120 is de ondersteuning voor het name attribuut op <details> -elementen. Wanneer dit attribuut wordt gebruikt, vormen meerdere <details> -elementen met dezelfde name waarde een semantische groep. Maximaal één element in de groep kan tegelijk geopend zijn: wanneer u een van de <details> -elementen uit de groep opent, wordt het eerder geopende element automatisch gesloten. Dit type accordeon wordt een exclusieve accordeon genoemd.

Exclusieve accordeondemo

De <details> -elementen die deel uitmaken van een exclusieve accordeon hoeven niet per se verwante elementen te zijn. Ze kunnen verspreid over het document staan.

CSS heeft de afgelopen jaren een enorme opleving doorgemaakt, en vooral in 2023. Ben je nieuw met CSS of wil je gewoon de basisbeginselen opfrissen? Bekijk dan onze gratis cursus CSS leren en de andere gratis cursussen die web.dev aanbiedt.

Wij wensen u fijne feestdagen en hopen dat u binnenkort de kans krijgt om een ​​aantal van deze fantastische nieuwe CSS- en UI-functies in uw werk te integreren!

⇾ Het Chrome UI DevRel-team,

,
CSS-omhulde header

CSS verpakt: 2023!

Wauw! 2023 was een geweldig jaar voor CSS!

From #Interop2023 to many new landings in the CSS and UI space that enable capabilities developers once thought impossible on the web platform. Now, every modern browser supports container queries, subgrid, the :has() selector, and a whole plethora of new color spaces and functions . We have support in Chrome for CSS-only scroll-driven animations and smoothly animating between web views with view transitions . And to top it all off, there are so many new primitives that have landed for better developer experiences like CSS nesting and scoped styles.

What a year it has been! And so we'd like to end this milestone year celebrating and acknowledging all of the hard work by browser developers and the web community that made this all possible.

Architectural foundations

Let's begin with updates to the core CSS language and capabilities. These are features which are foundational to the way you author and organize styles, and bring great power to the hands of the developer.

Trigonometric functions

Browser Support

  • Chrome: 111.
  • Edge: 111.
  • Firefox: 108.
  • Safari: 15.4.

Source

Chrome 111 added support for the trigonometric functions sin() , cos() , tan() , asin() , acos() , atan() , and atan2() , making them available across all major engines. These functions come in very handy for animation and layout purposes. For example, it's now much easier to lay out elements on a circle around a chosen center.

Trigonometric functions demo

Learn more about the trigonometric functions in CSS .

Complex nth-* selection

Browser Support

  • Chrome: 111.
  • Edge: 111.
  • Firefox: 113.
  • Safari: 9.

With the :nth-child() pseudo-class selector it's possible to select elements in the DOM by their index. Using the An+B microsyntax you get fine control over which elements you want to select.

By default the :nth-*() pseudos take all child elements into account. As of Chrome 111 you can, optionally, pass a selector list into :nth-child() and :nth-last-child() . That way you can prefilter the list of children before An+B does its thing.

In the following demo, the 3n+1 logic is applied only to the small dolls by prefiltering them out using of .small . Use the dropdowns to dynamically change the used selector.

Complex nth-* selection demo

Learn more about complex nth-* selections .

Domein

Browser Support

  • Chrome: 118.
  • Edge: 118.
  • Firefox: behind a flag.
  • Safari: 17.4.

Source

Chrome 118 added support for @scope , an at-rule that lets you scope selector matching to a specific subtree of the document. With scoped styling, you can be very specific about which elements you select without having to write overly-specific selectors or tightly coupling them to the DOM structure.

A scoped subtree is defined by a scoping root (the upper boundary) and an optional scoping limit (the lower boundary).

@scope (.card) {  } /* scoping root */
@scope (.card) to (.card__content) {  } /* scoping root + scoping limit*/

Style rules placed inside a scope block will only target elements within the carved out subtree. For example, the following scoped style rule only targets <img> elements that sit between .card element and any nested component matched by the [data-component] selector.

@scope (.card) to ([data-component]) {
  img {  }
}

In the following demo, the <img> elements in the carousel component are not matched because of the applied scoping limit.

Scope Demo Screenshot

Reference screenshot for the @scope demo

Scope Live Demo

CSS @scope demo

Find out more about @scope in the article "How to use @scope to limit the reach of your selectors" . In this article you'll learn about the :scope selector, how specificity gets handled, prelude-less scopes, and how the cascade is affected by @scope .

Nesting

Browser Support

  • Chrome: 120.
  • Edge: 120.
  • Firefox: 117.
  • Safari: 17.2.

Source

Before nesting, every selector needed to be explicitly declared, separately from one another. This leads to repetition, stylesheet bulk and a scattered authoring experience. Now, selectors can be continued with related style rules grouped within.

dl {
  /* dt styles */
  
  dt {
    /* dl dt styles */
  }

  dd {
    /* dl dd styles */
  }
}

/* same as */
dt {
  /* dt styles */
}

dl dt {
  /* dl dt styles */
}

dl dd {
  /* dl dd styles */
}

Nesting Screencast

Nesting Live Demo

Change the relaxed nesting selector to decide the winner of the race

Nesting can reduce the weight of a stylesheet, reduce the overhead of repeating selectors, and centralize component styles. The syntax initially released with a limitation that required usage of & in various places, but since has been lifted with a nesting relaxed syntax update .

Learn more about nesting .

Subgrid

Browser Support

  • Chrome: 117.
  • Edge: 117.
  • Firefox: 71.
  • Safari: 16.

Source

CSS subgrid enables you to create more complex grids with better alignment between child layouts. It allows a grid that's inside another grid, to adopt the rows and columns of the outer grid as its own, by using subgrid as a value for grid rows or columns.

Subgrid Screencast

Subgrid Live Demo

Header, body and footers align to the dynamic sizes of their siblings.

Subgrid is especially useful for aligning siblings to each other's dynamic contents. This frees copywriters, UX writers, and translators from attempting to create project copy that "fits" into the layout. With subgrid, the layout can be adjusted to fit the content.

Learn more about subgrid .

Typografie

Web typography saw a few key updates in 2023. An especially nice progressive enhancement is the text-wrap property. This property enables typographic layout adjustment, composed in the browser with no additional scripting required. Say goodbye to awkward line lengths and hello to more predictable typography!

Initial-letter

Browser Support

  • Chrome: 110.
  • Edge: 110.
  • Firefox: not supported.
  • Safari: 9.

Source

Landing at the start of the year in Chrome 110, the initial-letter property is a small yet powerful CSS feature which sets styling for the placement of initial letters. You can position letters in either a dropped or raised state. The property accepts two arguments: the first for how deeply to drop the letter into the corresponding paragraph, and second for how much to raise the letter above it. You can even do a combination of both, such as in the following demo.

Initial-letter Screenshot

Screenshot of initial-letter demo

Initial-letter Demo

Change the values of the initial-letter for the ::first-letter pseudo element to watch it shift.

Learn more about initial-letter .

text-wrap: balance and pretty

As a developer, you don't know the final size, font size, or even language of a headline or paragraph. All the variables needed for an effective and aesthetic treatment of text wrapping, are in the browser. Since the browser does know all the factors, like font size, language, and allocated area, it makes it a great candidate for handling advanced and high quality text layout.

This is where two new text wrapping techniques come in, one called balance and the other pretty . The balance value seeks to create a harmonious block of text while pretty seeks to prevent orphans and ensure healthy hyphenation. Both of these tasks have traditionally been done by hand, and it's amazing to give the job to the browser and have it work for any translated language.

Text-wrap Screencast

Text-wrap Live Demo

In the following demo you can compare by dragging the slider, the effects of balance and pretty on a heading and a paragraph. Try translating the demo into another language!

Learn more about text-wrap: balance .

Kleur

2023 was the year of color for the web platform. With new color spaces and functions that enable dynamic color theming, there's nothing stopping you from creating the vivid, lush themes your users deserve, and make them customizable, too!

HD Color Spaces (Color Level 4)

Browser Support

  • Chrome: 111.
  • Edge: 111.
  • Firefox: 113.
  • Safari: 15.

Source

Browser Support

  • Chrome: 111.
  • Edge: 111.
  • Firefox: 113.
  • Safari: 15.

Source

From the hardware to the software, the CSS to the blinking lights; it can take a lot of work for our computers to try and represent colors as good as our human eyes can see. In 2023, we have new colors, more colors, new color spaces, color functions and new capabilities.

CSS and color can now: - Check if the users screen hardware is capable of wide gamut HDR colors. - Check if the user's browser understands color syntax like Oklch or Display P3. - Specify HDR colors in Oklab, Oklch, HWB, Display P3, Rec.2020, XYZ, and more. - Create gradients with HDR colors, - Interpolate gradients in alternative color spaces. - Mix colors with color-mix() . - Create color variants with relative color syntax.

Color 4 Screencast

Color 4 Demo

In the following demo you can compare by dragging the slider, the effects of `balance` and `pretty` on a heading and a paragraph. Try translating the demo into another language!

Learn more about Color 4 and color spaces .

color-mix function

Browser Support

  • Chrome: 111.
  • Edge: 111.
  • Firefox: 113.
  • Safari: 16.2.

Source

Mixing color is a classic task and in 2023 CSS can do it too. You can not only mix white or black to a color, but also transparency, and do all this in any color space of your choosing. It's simultaneously a basic color feature and an advanced color feature.

color-mix() Screencast

color-mix() Demo

Demo allows you to pick two colors with a color picker, the color space, and how much of each color should be dominant in the mix.

You can think of color-mix() as a moment in time from a gradient. Where a gradient shows all the steps it takes to go from blue to white, color-mix() shows just one step. Things get advanced once you begin to take color spaces into account and learn just how different the mixing color space can be to the results.

Learn more about color-mix() .

Relative color syntax

Relative color syntax (RCS) is a complementary method to color-mix() for creating color variants. It's slightly more powerful than color-mix() but also a different strategy for working with color. color-mix() may mix in the color white to lighten a color, where RCS gives precise access to the lightness channel and the ability to use calc() on the channel to reduce or increase lightness programmatically.

RCS Screencast

RCS Live Demo

Change the color, change the scenes. Each uses relative color syntax to create variants off the base color.

RCS allows you to perform relative and absolute manipulations to a color. A relative change is one where you take the current value of saturation or lightness and modify it with calc() . An absolute change is one where you replace a channel value with an entirely new one, like setting opacity to 50%. This syntax gives you meaningful tools for theming, just in time variants, and more.

Learn more about relative color syntax .

Responsive Design

Responsive design evolved in 2023. This groundbreaking year enabled new features that entirely change the way we build responsive web experiences, and ushered in a new model of component-based responsive design. The combination of container queries and :has() supports components that own their responsive and logical styling based on the size of their parent, as well as the presence or state of any of their children. That means you can finally separate page-level layout from component-level layout, and write the logic once to use your component everywhere!

Size container queries

Browser Support

  • Chrome: 105.
  • Edge: 105.
  • Firefox: 110.
  • Safari: 16.

Source

Rather than using the viewport's global size information to apply CSS styles, container queries support the querying of a parent element within the page. This means components can be styled in a dynamic way across multiple layouts and in multiple views. Container queries for size became stable in all modern browsers on Valentine's Day this year (February 14th).

To use this feature, first set up containment on the element you are querying, and then, similar to a media query, use @container with the size parameters to apply the styles. Along with container queries you get container query sizes. In the following demo, the container query size cqi (representing the size of the inline container), is used to size the card header.

@container Screencast

@container Demo

Learn more about using container queries .

Style container queries

Browser Support

  • Chrome: 111.
  • Edge: 111.
  • Firefox: not supported.
  • Safari: 18.

Style queries landed with partial implementation in Chrome 111. With style queries currently, you can query the value of custom properties on a parent element when using @container style() . For example, query if a custom property value exists, or is set to a certain value, such as @container style(--rain: true) .

Style query screenshot

Demo screenshot for style container queries weather cards

Style query demo

Change the color, change the scenes. Each uses relative color syntax to create variants off the base color.

While this sounds similar to using class names in CSS, style queries have some advantages. The first is that with style queries, you can update the value in CSS as needed for pseudo states. Also, in future versions of the implementation, you'll be able to query ranges of values to determine the style applied, such as style(60 <= --weather <= 70) , and style based on property-value pairs such as style(font-style: italic) .

Learn more about using style queries .

:has() selector

Browser Support

  • Chrome: 105.
  • Edge: 105.
  • Firefox: 121.
  • Safari: 15.4.

Source

For almost 20 years developers asked for a "parent selector" in CSS. With the :has() selector that shipped in Chrome 105 this is now possible. For example, using .card:has(img.hero) will select the .card elements that have a hero image as a child.

:has() Demo Screenshot

Reference screenshot for the :has() demo

:has() Live Demo

CSS :has() demo: Card without/with image

Because :has() accepts a relative selector list as its argument, you can select much more than the parent element. Using various CSS combinators, it's possible to not only go up the DOM tree, but also do sideway selections. For example, li:has(+ li:hover) will select the <li> element that precedes the currently hovered <li> element.

:has() Screencast

:has() Demo

CSS :has() demo: Dock

Learn more about the CSS :has() selector .

Update media query

Browser Support

  • Chrome: 113.
  • Edge: 113.
  • Firefox: 102.
  • Safari: 17.

Source

The update media query gives you a way to adapt UI to the refresh rate of a device. The feature can report a value of fast , slow , or none which relates to the capabilities of different devices.

Most of the devices you design for are likely to have a fast refresh rate. This includes desktops and most mobile devices. eReaders and devices such as low powered payment systems, may have a slow refresh rate. Knowing that the device can't handle animation or frequent updates, means that you can save battery usage or faulty view updates.

Update Screencast

Update Demo

Simulate (by choosing a radio option) an update speed value and see how it affects the duck.

Learn more about @media (update) .

Scripting media query

Browser Support

  • Chrome: 120.
  • Edge: 120.
  • Firefox: 113.
  • Safari: 17.

Source

The scripting media query can be used to check whether or not JavaScript is available. This is very nice for progressive enhancement. Before this media query, a strategy for detecting if JavaScript was available was to place a nojs class in the HTML, and remove it with JavaScript. These scripts can be removed as CSS now has a way to detect JavaScript and adjust accordingly.

Learn how to enable and disable JavaScript on a page for testing via Chrome DevTools here .

Scripting Screencast

Scripting Demo

Consider a theme switch on a website, the scripting media query can assist in making the switch work against the system preference since no JavaScript is available. Or consider a switch component—if JavaScript is available then the switch can be swiped with a gesture instead of just toggled on and off. Lots of great opportunities to upgrade UX if scripting is available while providing a meaningful foundation experience if scripting is disabled.

Learn more about script .

Reduced-transparency media query

Browser Support

  • Chrome: 118.
  • Edge: 118.
  • Firefox: behind a flag.
  • Safari: not supported.

Source

Non-opaque interfaces can cause headaches or be a visual struggle for various types of vision deficiencies. This is why Windows, macOS, and iOS have system preferences that can reduce or remove transparency from the UI. This media query for prefers-reduced-transparency fits in well with the other preference media queries, which allow you to be creative while also adjusting for users.

Reduced Transparency Screencast

Reduced Transparency Demo

In some cases, you can provide an alternative layout which doesn't have content overlaying other content. In other cases, the opacity of a color can be adjusted to be opaque or nearly opaque. The following blog post has more inspiring demos that adapt to the user preference, give them a look if you're curious about times when this media query is valuable.

Learn more about @media (prefers-reduced-transparency) .

Interaction

Interaction is a cornerstone of digital experiences. It helps users get feedback on what they clicked on and where they are in a virtual space. This year, there have been many exciting features landing which have made interactions easier to compose and implement, enabling smooth user journeys and a more finessed web experience.

View transitions

Browser Support

  • Chrome: 111.
  • Edge: 111.
  • Firefox: 144.
  • Safari: 18.

Source

View transitions have a huge impact on the user experience of a page. With the View Transitions API, ​​you can create visual transitions between two page states of your Single Page Application. These transitions can be full page transitions, or smaller things on a page such as adding or removing a new item to a list.

At the core of the View Transitions API is the document.startViewTranstion function. Pass in a function that updates the DOM to the new state, and the API takes care of everything for you. It does this by taking a before and after snapshot, then transitioning between the two. Using CSS you can control what gets captured and optionally customize how these snapshots should be animated.

VT Screencast

VT Demo

View Transitions demo

The View Transitions API for Single Page Applications shipped in Chrome 111. Learn more about View Transitions .

Linear-easing function

Browser Support

  • Chrome: 113.
  • Edge: 113.
  • Firefox: 112.
  • Safari: 17.2.

Source

Don't let the name of this function fool you. The linear() function (not to be confused with the linear keyword) allows you to create complex easing functions in a simple manner, with the compromise of losing some precision.

Before linear() , which shipped in Chrome 113, it was impossible to create bounce or spring effects in CSS. Thanks to linear() it is possible to approximate these easings by simplifying them to a series of points, then linearly interpolating between these points.

Chart of a bounce easing curve with several dots added to it
The original bounce curve in blue is simplified by a set of key points shown in green. The linear() function uses these points and interpolates linearly between them.

Linear-easing Screencast

Linear-easing Demo

CSS linear() demo.

Learn more about linear() . To create linear() curves, use the linear easing generator .

Scroll End

Browser Support

  • Chrome: 114.
  • Edge: 114.
  • Firefox: 109.
  • Safari: not supported.

Source

Many interfaces include scroll interactions, and sometimes the interface needs to synchronize information relevant to the current scroll position, or fetch data based on current state. Before the scrollend event, you had to use an inaccurate timeout method that could fire while the user's finger was still on the screen. With the scrollend event, you have a perfectly timed scrollend event that understands whether a user is still mid gesture or not.

Scrollend Screencast

Scrollend Demo

This was important for the browser to own because JavaScript cannot track a fingers presence on the screen during a scroll, the information is just simply not available. Chunks of inaccurate scroll end attempting code can now be deleted and replaced with a browser owned high precision event.

Learn more about scrollend .

Scroll-driven animations

Browser Support

  • Chrome: 115.
  • Edge: 115.
  • Firefox: behind a flag.
  • Safari: 26.

Source

Scroll-driven animations are an exciting feature available from Chrome 115. These allow you to take an existing CSS animation or an animation built with the Web Animations API , and couple it to the scroll offset of a scroller. As you scroll up and down–or left and right in a horizontal scroller–the linked animation will scrub forwards and backwards in direct response.

With a ScrollTimeline you can track the overall progress of a scroller, as demonstrated in the following demo. As you scroll to the end of the page, the text reveals itself character by character.

SDA Screencast

SDA Demo

CSS scroll-driven animations demo: scroll timeline

With a ViewTimeline you can track an element as it crosses the scrollport. This works similarly to how IntersectionObserver tracks an element. In the following demo, each image reveals itself from the moment it enters the scrollport until it is at the center.

SDA Demo Screencast

SDA Live Demo

CSS scroll-driven animations demo: view timeline

Because scroll-driven animations work with CSS animations and the Web Animations API, you can benefit from all the advantages these APIs bring. That includes the ability to have these animations run off the main thread. You can now have silky smooth animations, driven by scroll, running off the main thread with just a few lines of extra code–what's not to like?

To learn more about scroll-driven animations check out this article with all the details or visit scroll-driven-animations.style which includes many demos.

Deferred timeline attachment

Browser Support

  • Chrome: 116.
  • Edge: 116.
  • Firefox: not supported.
  • Safari: 26.

Source

When applying a scroll-driven animation through CSS, the lookup mechanism to find the controlling scroller always walks up the DOM tree making it limited to scroll ancestors only. Very often though, the element that needs to be animated is not a child of the scroller but an element located in an entirely different subtree.

To allow the animated element to find a named scroll-timeline of a non-ancestor use the timeline-scope property on a shared parent. This allows the defined scroll-timeline or view-timeline with that name to attach to it, giving it a broader scope. With this in place, any child of that shared parent can use the timeline with that name.

Visualization of a DOM subtree with timeline-scope used on a shared parent
With timeline-scope declared on the shared parent, the scroll-timeline declared on the scroller can be found by the element that uses it as its animation-timeline

Demo Screencast

Live Demo

CSS scroll-driven animations demo: deferred timeline attachment

Learn more about timeline-scope .

Discrete property animations

Another new capability in 2023 is the ability to animate discrete animations, such as animating to and from display: none . From Chrome 116, you can use display and content-visibility in keyframe rules. You can also transition any discrete property at the 50% point rather than at the 0% point. This is achieved with the transition-behavior property using the allow-discrete keyword, or in the transition property as a shorthand.

Discrete Anim. Screencast

Discrete Anim. Demo

Learn more about transitioning discrete animations .

@starting-style

Browser Support

  • Chrome: 117.
  • Edge: 117.
  • Firefox: 129.
  • Safari: 17.5.

Source

The @starting-style CSS rule builds on new web capabilities for animating to and from display: none . This rule provides a way to give an element a "before-open" style that the browser can look up before the element is open on the page. This is very useful for entry animations, and for animating in elements such as a popover or dialog. It can also be useful for any time you are creating an element and want to give it the ability to animate in. Take the following example which animates a popover attribute (see next section) into view and into the top layer smoothly from outside of the viewport.

@starting-style Screencast

@starting-style Demo

Learn more about @starting-style and other entry animations.

Overlay

Browser Support

  • Chrome: 117.
  • Edge: 117.
  • Firefox: not supported.
  • Safari: not supported.

Source

The new CSS overlay property can be added to your transition to enable elements with top-layer styles—such as popover and dialog —to animate out of the top-layer smoothly. If you don't transition overlay, your element will immediately go back to being clipped, transformed, and covered up, and you won't see the transition happen. Similarly, overlay enables ::backdrop to animate out smoothly when added to a top-layer element.

Overlay Screencast

Overlay Live Demo

Learn more about overlay and other exit animations.

Componenten

2023 was a big year for the intersection of style and HTML components, with popover landing and a lot of work being done around anchor positioning and the future of styling dropdowns. These components make it easier to build common UI patterns without the need to rely on additional libraries or building your own state management systems from the ground up each time.

Popover

Browser Support

  • Chrome: 114.
  • Edge: 114.
  • Firefox: 125.
  • Safari: 17.

Source

The Popover API helps you build elements which lay on top of the rest of the page. These could include menus, selection, and tooltips. You can create a simple popover by adding the popover attribute and an id to the element which pops up, and connecting its id attribute to an invoking button using popovertarget="my-popover" . The Popover API supports:

  • Promotion to the top layer. Popovers will appear on a separate layer above the rest of the page, so you don't have to play around with z-index.
  • Light-dismiss functionality. Clicking outside of the popover area will close the popover and return focus.
  • Default focus management. Opening the popover makes the next tab stop inside the popover.
  • Accessible keyboard bindings. Hitting the esc key or double toggling will close the popover and return focus.
  • Accessible component bindings. Connecting a popover element to a popover trigger semantically.

Popover Screencast

Popover Live Demo

Horizontal rules in select

Another small change to HTML which landed in Chrome and Safari this year, is the ability to add horizontal rule elements ( <hr> tags) into <select> elements to help visually break up your content. Previously, putting an <hr> tag into a select simply would not render. But this year, both Safari and Chrome support this feature, enabling better separation of content within <select> elements.

Select Screenshot

screenshot of hr in select with a light and dark theme in Chrome

Select Live Demo

Learn more about using using hr in select

:user-valid and invalid pseudo classes

Browser Support

  • Chrome: 119.
  • Edge: 119.
  • Firefox: 88.
  • Safari: 16.5.

Source

Stable in all browsers this year, the :user-valid and :user-invalid behave similarly to the :valid and :invalid pseudo-classes, but match a form control only after a user has significantly interacted with the input. A form control that is required and empty will match :invalid even if a user has not started interacting with the page. The same control will not match :user-invalid until the user has changed the input and left it in an invalid state.

With these new selectors, there's no longer a need to write stateful code to keep track of input a user has changed.

:user-* Screencast

:user-* Live Demo

Learn more about using user-* form validation pseudo elements .

Exclusive accordion

Browser Support

  • Chrome: 120.
  • Edge: 120.
  • Firefox: 130.
  • Safari: 17.2.

A common UI pattern on the web is an accordion component. To implement this pattern, you combine a few <details> elements, often visually grouping them to indicate that they belong together.

New in Chrome 120 is support for the name attribute on <details> elements. When this attribute is used, multiple <details> elements that have the same name value form a semantic group. At most one element in the group can be open at once: when you open one of the <details> elements from the group, the previously open one will automatically close. This type of accordion is called an exclusive accordion .

Exclusive accordion demo

The <details> elements that are part of an exclusive accordion don't necessarily need to be siblings. They can be scattered across the document.

CSS has had such a renaissance in the past few years, and especially during 2023. If you're new to CSS or just want a refresher on the basics, check out our free Learn CSS course along with the other free courses on offer at web.dev.

We wish you a happy holiday season and hope you get a chance to incorporate some of these brilliant new CSS and UI features into your work soon!

⇾ The Chrome UI DevRel Team,