As mentioned several times before, I enjoy using Twitter and generally find a lot of interesting information, analysis and news on the platform. Some tweets get embedded into my blog posts as well. One of the big advantages compared to embeds from other social networks is how straightforward the fallback is: the tweet text is inserted inside a <blockquote> tag, and any styles and media in the tweet are added by the embedding script. This means that, even if the tweet gets deleted or the script does not load (or when Twitter shuts down, at some point in the future), the relevant information is preserved in the text on my blog post.
You can add several options to each individual embedded tweet to control its display, for example to align it to center, to display or hide the conversation, or to fine-tune its appearance. As I was looking at these options, I discovered Twitter provides some global controls as well. These can be enabled through <meta> tags on each site. This includes the ability to switch the default theme of embedded tweets from light to dark, with this element:
<meta name="twitter:widgets:theme" content="dark">
But would it be possible to automatically switch from dark to light theme depending on the user’s local preference? CSS has introduced media queries that developers can use to adapt their designs for dark or light modes, and it turns out an equivalent of CSS media queries exists for <meta> tags as well, in this format:
<meta name="…" content="…" media="(prefers-color-scheme: dark)">
In the case of Twitter widgets, the two lines of code below, added inside the <head> section of a website, would be enough to automatically switch the theme of embedded tweets according to the local preference. If the overall site theme is changing based on local dark mode settings, embedded tweets would also match the site design with little effort from the designer.
<meta name='twitter:widgets:theme' content='dark' media='(prefers-color-scheme: dark)'>
<meta name='twitter:widgets:theme' content='light' media='(prefers-color-scheme: light)'>
Naturally I added these new tags to my blog, even though it does not currently have a dark mode. Dark embedded tweets look awesome on a white background nevertheless.
Unfortunately, browser support for media queries inside meta tags is very limited for the time being. Safari should be the first browser to support this for both desktop and mobile in version 15, whereas desktop Chrome (and presumably Edge), starting with version 93, will support this only for installed progressive web apps. On my Android smartphone, this currently works only in Samsung Internet, and it looks a bit weird because the browser forces a dark theme onto the site. Hopefully after being adopted in Safari, this feature will make its way to other browsers as well.
Post a Comment