Developer News

Creating Colorful, Smart Shadows

Css Tricks - Tue, 05/04/2021 - 4:19am

A bona fide CSS trick from Kirupa Chinnathambi here. To match a colored shadow with the colors in the background-image of an element, you inherit the background in a pseudo-element, kick it behind the original, then blur and filter it.

.colorfulShadow { position: relative; } .colorfulShadow::after { content: ""; width: 100%; height: 100%; position: absolute; background: inherit; background-position: center center; filter: drop-shadow(0px 0px 10px rgba(0, 0, 0, 0.50)) blur(20px); z-index: -1; }

Negative z-index is always a yellow flag for me as that only works if there are no intermediary backgrounds. But the trick holds. There would always be some other way to layer the backgrounds (like a <span> or whatever).

For some reason this made me think of a demo I saw (I can’t remember who to credit!). Emojis had text-shadow on them, which really made them pop. And those shadows could also be colorized to a similar effect.

CodePen Embed Fallback

Direct Link to ArticlePermalink

The post Creating Colorful, Smart Shadows appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Chapter 8: CSS

Css Tricks - Mon, 05/03/2021 - 11:52am

In June of 2006, web developers and designers from around the world came to London for the second annual @media conference. The first had been a huge success, and @media 2006 had even more promise. Its speaker lineup was pulled from some of the most exciting and energetic voices in the web design and browser community.

Chris Wilson was there to announce the first major release to Microsoft’s Internet Explorer in nearly half a decade. Rachel Andrew and Dave Shea were swapping practical tips about CSS and project management. Tantek Çelik was sharing some of his recent work on microformats. Molly Holzschlag, Web Standards Project lead at the time, prepared an illuminating talk on internationalization and planned to join a panel about the latest developments of CSS.

The conference kicked off on Thursday with a keynote talk by Eric Meyer, a pioneer and early adopter of CSS. The keynote’s title slide read “A Decade of Style.” In a captivating and personal talk, Meyer recounted the now decade-long history of Cascading Style Sheets, or CSS. His own professional history intertwined and inseparable from that of CSS, Meyer used his time on the stage to look at the language’s roots and understand better the decisions and compromises that had led to the present day.

At the center of his talk, Meyer unveiled the secret to the success of CSS: “Never underestimate the effect of a small, select group of passionate experts.” CSS, the open and accessible design language of the Web, thrived not because of the technology itself, but because of people—the people who built it (and built with it) and what they shared as they learned along the way. The history of CSS, Meyer concluded, is the history of the people who made it.

Fifteen years after that talk, and nearly three decades after its creation, that is still true.

On Thursday morning, October 20th, 1994, attendees of another conference, the Second International WWW Conference, shuffled into a room on the second floor of the Ramada Hotel in Chicago. It was called the Gold Room. The Grand Hall across the way was quite a bit larger—reserved for the keynote presentations on the day—but the Gold Room would work just fine for the relatively smaller group that had managed to make the early morning 8:30 a.m. panel.

Most in attendance that morning would have been exhausted and bleary-eyed, tired from late-night networking events that had spanned the previous three nights. Thursday was Developer Day, the final day of the conference.

The Chicago conference had been preceded six months earlier by the first WWW conference in Geneva. The contrast would have been immediately apparent. Rather than breakout sessions focused on standards and specs, the halls buzzed with industry insiders and commercial upstarts selling their wares. In a short amount of time, the Web had gone mainstream. The conference in Chicago reflected that shift in tone: it was an industry event, with representatives from Microsoft, HP, Silicon Graphics, and many more.

The theme of the conference was “Mosaic and the Web,” and the site of Mosaic’s creation, NCSA, had helped to organize the event. It was a fact made more dramatic by a press release from Netscape, a company mostly staffed by former NCSA employees, just days earlier. The first version of their browser—dramatically billed as “Mosaic killer”—was not only in beta, but would be free upon release (a decision that would later be reversed). Most members of the Netscape team were in attendance, in commercial opposition of their former employer and biggest rival.

The grand intrigue of commercial clashes somewhat overshadowed the first morning session on the last day of the conference, “HTML and SGML: A Technical Presentation.” This, in spite of the fact that the Web’s creator, Sir Tim Berners-Lee, was leading the panel. The final presenter was Håkon Wium Lie, who worked with Berners-Lee and Robert Calliau at CERN. It was about a new proposal for a design language that Lie was calling Cascading HTML Style Sheets. CHSS for short.

The proposal had come together in a hurry. A conversation with standards editor Dave Ragget helped convince Lie of the urgency. Running right up to the deadline, Lie had posted the first draft of his proposal ten days before the conference.

Lie had come to the Web early and enthusiastically. Early enough to have used Nicola Pellow’s line-mode browser to telnet into the very first website. And enthusiastic enough to join Berners-Lee and the web team at CERN shortly after graduating from the MIT media lab in 1992. “I heard the big bang and came running,” is how Lie puts it.

Hakon Wium Lie (Credit: Heinrich-Böll-Stiftung)

Not long after he began at CERN, the language of the web shifted. Realizing that the web’s audience could not stare at black text on a white background all day, the makers of Mosaic introduced a tag that let website creators add inline images to their website. Once the gate was open, more features rushed out. Mosaic added even more tags for colors and fonts and layout. Lie, and the team at CERN, could only sit on the sidelines and watch, a fact Lie would later comment on, saying, “It was like: ‘Darn, we need something quick, otherwise they’re going to destroy the HTML language.’”

The impending release of Netscape in 1994 offered no relief. Marc Andreessen and his team at Netscape promised a consumer-focused web browser. Berners-Lee had developed HTML—the singular language of the web—to describe documents, not to design them. To fill that gap, browsers stuffed the language of HTML with tags to allow designers to create dynamic and stylized websites.

The problem was, there was not yet a standard way of doing this. So each browser added what they felt was necessary and others were forced to either follow suit or go their own way. “As soon as images were allowed inline in HTML documents, the web became a new graphical design medium,” programmer and soon-to-be W3C member Chris Lilley posted to www-talk around that time, “If style sheets or similar information are not added to HTML, the inevitable price will be documents that only look good on a particular browser.”

Lie’s proposal—which he began working on almost as soon as he joined up at CERN—was for a second language. CHSS used style sheets: separate documents that described the visual design of HTML without affecting its structure. So you could change your HTML and your style sheet stayed the same. Change the style sheet and HTML stayed the same. Content lived in one place, and presentation in another.

There were other style sheet proposals. Rob Raisch from O’Reilly and Viola creator Pei-Yuan Wei each had their own spin. Working at CERN, where the web had been created, helped boost the profile of CHSS. Its relative simplicity also made it appealing to browser makers. The cascade in Cascading HTML Style Sheets, however, set it apart.

Each person experiences the web through a prism of their own experience. It is viewed through different devices, under different conditions. On screen readers and phones and on big screen TVs. One’s perception of how a page should look based on their situation runs in stark contrast to both the intent of the website’s author and the limitations and capabilities of browsers. The web, therefore, is chaotic. Multiple sources mingle and compete to decide the way each webpage is perceived.

The cascade brings order to the web. Through a simple set of rules, multiple parties—the browser, the user, and the website author—can define the presentation of HTML in separate style sheets. As rules flow from one style sheet to the next, the cascade balances one rule against another and determines the winner. It keeps design for the web simple, inheritable, and embraces its natural unstable state. It has changed over time, but the cascade has made the web adaptable to new computing environments.

After Lie gave his presentation on the second floor of the Ramada Hotel in Chicago, it was the cascade that monopolized discussions. The makers of the web used the CHSS proposal as a springboard for a much wider conversation about author intent and user preferences. In what situation, in other words, the author of a website’s design should override the preference of a user or the determination of a browser. Productive debate spilled outside of the room and onto the www-talk mailing list, where it was picked up by Bert Bos.

Bert Bos (Credit: dotConferences)

Bos was a Dutch engineer, studying mathematics at the University of Groningen in the Netherlands. Before he graduated, he created a browser called Argo, a well-known and useful tool for several of the University’s departments. Argo was notable for two reasons. The first was that it included an early iteration of what would later be known as applets. The second was that it included Bos’ own style sheet implementation, one that was not too unlike CHSS. He recognized an opportunity.

“Most of the content of CSS1 was discussed on the whiteboard in Sophia-Antipolis in July 1995… Whenever I encounter difficult technical problems, I think of Bert and that whiteboard.”

Hakon Wium Lie

Lie and Bos began working together, merging their proposals into something more refined. The following year, in the spring of 1995, the third WWW conference was held in Darmstadt, Germany. Netscape, having just been released six months earlier, was already coasting on a new wave of popularity led by their new CEO Jim Barksdale. A few months away from the most successful IPO in history, Netscape would soon launch itself into the stratosphere, with the web riding shotgun, still adding new, non-standard HTML features whenever they could.

Lie and Bos had only ever communicated remotely. In Germany, they met in person for the first time and gave a joint presentation on a new proposal for Cascading Style Sheets, CSS (the H dropped by then).

It stood in contrast to what was available at the time. With only HTML at their disposal, web designers were forced to create “page layout via tables and Netscapisms like FONT SIZE,” as one Suck columnist wrote at the time, later quoted in a dissertation written by Lie. Table-bloated webpages were slow to load, and difficult to understand by accessible devices like screen readers. CSS solved those issues. That same writer, though not believing in its longevity, praised CSS for its “simple elegance, but also… its superfluousness and redundancy.”

Shortly after the conference, Bos joined Lie at the W3C. They began drafting a specification that summer. Lie recalls the frenzied and productive work they did fondly. “Most of the content of CSS1 was discussed on the whiteboard in Sophia-Antipolis in July 1995… Whenever I encounter difficult technical problems, I think of Bert and that whiteboard.”

Chris Wilson, in 1995, was already something of an expert in browsers. He had worked at NCSA on the Mosaic team, one of two programmers who created the Windows version. In the basement of the NCSA lab, Wilson was an eager participant in the conversations that helped define the early web.

Most of his colleagues at NCSA packed up and moved to Silicon Valley to work on Netscape’s Mosaic killer. Wilson chose something different. He settled farther north, in Seattle. His first job was with Spry, working on a Mosaic-licensed browser for their Internet In a Box package. However, as an engineer it was hard for Wilson to avoid the draw of Microsoft in Seattle. By 1995, he worked there as a software developer, and by 1996, he was moved to the Internet Explorer team just ahead of the browser’s version 2 release.

Internet Explorer was Microsoft’s late entry to the browser market. Bill Gates had notoriously sidestepped the Internet and the web for years, before completely reversing his company’s position. In that time, Netscape had captured a swiftly expanding market that didn’t exist when they started. They had released two wildly successful versions of their user-friendly, cross-platform browser. Their window to the web was adorned with built-in email, an easy install process, and a new language called JavaScript that let developers add lively animations to a web that had been previously inert.

Microsoft offered comparatively little. Internet Explorer began as a port of Mosaic, but by the time Wilson signed on, it rested on a rewritten codebase. Besides a few built-in native Microsoft features that appealed to the enterprise market, Internet Explorer had been unable to set themselves apart from the sharp focus and pace of Netscape.

Microsoft needed a differentiator. Wilson thought he had one. “There’s this thing called style sheets,” Wilson recalls telling his boss at the time, “it lets you control the fonts and you and you get to make really pretty looking pages, Netscape isn’t even looking at this stuff.” Wilson got approval to begin working on CSS on the spot.

At the time, the CSS specification wasn’t yet complete. To bridge the gap of how things were supposed to work, Wilson met regularly with Lie, Bos, and other members of the W3C. They would make edits to their draft specification, and Wilson would try it out in his browser. Rinse and repeat. Later, they even brought Vidur Apparao from Netscape into their discussions, which became more formal. Eventually, they became the CSS Working Group.

Internet Explorer 3 was released in August of 1996. It was the first browser to have any support for CSS, a language that hadn’t yet been formally recommended by the W3C. Later, that would become an issue. “There are still a lot of IE3s out there,” Lie would later say a few years after its initial release, “and since they don’t conform to the specification, it’s very hard to write a style sheet that will work well with IE3 while also working well with later browsers.”

Internet Explorer 3 (Credit: My Internet Explorer)

At the time, however, it was imminently necessary. A working version of CSS powered by a browser at the largest tech company in the world lent stability. Table-based layouts and Netscape-only tags were still more widely adopted, but CSS now stood a chance.

By 1997, the W3C split the HTML working group into three parts, with CSS getting its own dedicated group formed from the ad-hoc Internet Explorer 3 team. It would be chaired by Chris Lilley, who came to the web as a computer graphics specialist. Lilley had pointed out years earlier the need for a standardized web technology for design. At the W3C, he would lead the effort to do just that.

The first formal Recommendation of CSS was published in December of 1997. Six months later, CSS version 2 was released.

As chair of the working group, Lilley was active on the www-talk mailing list. He’d often solicit advice or answer questions from developers. On one such exchange, he received an email from one Eric Meyer. “Hey, I threw together these test pages, I don’t know if you’d be interested in them,” was how Meyer remembers the message, adding that he didn’t realize that “there was nothing else quite like it in existence.”

Eric Meyer was at the web conference in Chicago where Håkon Lie first demoed CSS, though not at the session. He didn’t get a chance to actually see CSS until a few years later, at the fifth annual Web Conference in Paris. He was there to present a paper on web technology he had developed while working as the Case Western webmaster. His real purpose there, however, was to discover the probable future of the web.

He attended one panel featuring Håkon Lie and Bert Bos, alongside Dave Raggett. They each spoke to the capabilities of CSS as part of the W3C specification. Chris Wilson was there too, nursing a bit of a cold but nevertheless emphatically demoing a working version of CSS in Internet Explorer 3. “I’d never even heard of CSS before, but by the time that panel was over, the top of my head felt like it had blown off,” Meyer would later say, “I was instantly sold. It just felt right.”

Eric A. Meyer (Credit

Meyer got home and began experimenting with CSS. But he quickly hit a wall. He had a little more than a spec to go off of—there wasn’t such a thing as formal documentation or CSS tutorials—but something felt off. He’d code a bit of CSS and expect it to work one way, and it’d work another.

That’s when he began to pull together test pages. Meyer would isolate his code to a single feature of CSS. Then he’d test that across browsers, and document their inconsistencies, alongside how he thought they should work. “I think it was mostly the sheer joy of crawling through a new system, pulling it apart, figuring out how it worked, and documenting what worked and what didn’t. I don’t know exactly why those kinds of things excite me, but they do.” Over the years, Meyer has built a career on top of this type of experimentation.

Those test pages—posted to Meyer’s website and later to other blogs—carefully arranged and unknowingly documented the proper implementation of CSS according to its specification. Once Chris Lilley got a hold of them, the CSS Working Group helped Meyer transform them into the official W3C CSS Test Suite, an important tool to assist browsers working to introduce CSS.

Test pages and tutorials on Meyer’s personal site soon became regular columns on popular blogs. Then O’Reilly approached him about writing a book, which eventually became CSS: The Definitive Guide. Research for the book connected Meyer to the people that were building CSS inside of the W3C and browsers. He, in turn, shared what he learned with the web development community. Before long, Meyer had cemented a legacy as a central figure in the history of CSS.

His work continued. When the Web Standards Project reached out to programmer John Allsopp to form a committee dedicated to CSS, he immediately thought of Meyer. Meyer was joined by Allsopp and several others: Sue Sims, Ian Hickson, David Baron, Roland Eriksson, Ken Gunderson, Brade McDaniel, Liam Quinn and Todd Fahrner. Collectively, their official title was the CSS Action Committee, but they often went by CSS Samurai.

CSS was a properly standardized design language. If done right, it could shake loose the Netscape-only features and table-based layouts of the past. But browsers were not catching up to CSS quick enough for some developers. And when they did, it was frequently an afterthought. “You really can’t imagine, unless you lived through it, just how buggy and inconsistent and frustrating browser support for CSS was,” Meyer would later recall. The goal of the CSS Samurai was to fix that.

The committee took a familiar Web Standards Project approach, publishing public reports about lack of browser support on the one hand, and privately meeting with browser makers to discuss changes on the other. A third objective of the committee was to speak to developers directly. Grassroots education became a central goal to the work of the CSS Samurai, an effective instrument of change from the ground up.

Netscape provided the greatest hurdle. Wholly dependent on JavaScript, Netscape used a non-standard version of CSS known as JSSS, a language which by now has been largely forgotten. The browser processed style sheets dynamically using JavaScript to render the page, which made its support uneven and often slow to load. It would not be until the release of the Gecko rendering engine in the early 2000’s, that JSSS would be removed. As Netscape transformed into Mozilla in the wake of that change, it would finally come around to a functional CSS implementation.

But with other browsers, particularly with versions of Internet Explorer that were capturing larger segments of the market, WaSP proved successful. The hearts and minds of developers were with them, as they entered a new era of styling on the web.

There was at least one conversation over coffee that saved CSS. There may have been more, but the conversation in question happened in 1999, between Todd Fahrner and Tantek Çelik. Fahrner was a member of the Web Standards Project and a CSS Samurai, often on the front-lines of change. Among untold work with and for the web, he helped Meyer with the CSS Test Suite and developed a practical litmus test for CSS support known as the Acid Test.

Çelik worked at Microsoft. He was largely responsible for bringing web standards support into Internet Explorer for Mac, years before other major browsers would do the same. Çelik would have a long and lasting impact on the development of CSS. He would soon join the Web Standards Project Steering Committee. Later, as a member of the CSS Working Group, he would contribute and help edit several specifications.

On that particular day, over coffee, the topic of conversation was the web’s existential crisis. For years, browsers had added ad-hoc, uneven and incompatible versions of CSS. With a formalized Recommendation from the W3C, there was finally an objectively correct way of doing things. But if browsers took the new, correct rules from the W3C and applied them to all of the sites that had relied on the old, incorrect rules from before, they would suddenly look broken.

What they needed was a toggle. Some sort of switch that developers could turn on to signal that they wanted the new, correct rules. That day, Fahrner proposed using the doctype declaration. It’s a bit of text at the top of the HTML page that specifies a document type definition (the one Dan Connolly had spent years at the W3C standardizing). The practice became known as doctype switching. It meant that new sites could code CSS the right way, and old sites would continue to work just fine.

When Internet Explorer for Mac version 5 was released, it included doctype switching. Before long, all the browsers did. That swung the door open for standards-compliant CSS in browsers.

“We have not learned to design the Web.” So read the first line of the introduction of Molly Holzschlag’s 2003 book Cascading Style Sheets: The Designer’s Edge. It was a bold statement, not the first or the last from Holzschlag—who has had a profound and lasting impact on the evolution of the web. Throughout her career Holzschlag has been a restless advocate for people that use the web, even when that has clashed with makers of web technology. Her decades long history with the web has spanned well beyond CSS, to almost every aspect of its development and evolution.

Holzschlag goes on. “To get to this point in the web’s history, we’ve had to borrow guidelines from other media, hack and workaround our way through browser inconsistencies, and bend markup so far out of its normal shape that we’ve broken it.”

Molly Holzschlag

At the end of 2000, Netscape released the sixth version of their browser. Internet Explorer 6 came out not long after. The style sheets for these browsers were far more capable than any that had come before. But Microsoft wouldn’t release another browser for five years. Netscape, all but defeated by Microsoft, would take years to regroup and reform as the more capable and standards-compliant Firefox.

The work of the Web Standards Project and the W3C had brought a working version of CSS to the web. But it was incomplete, and often difficult to understand. And developers had to take older browsers into account, which many people still used.

In the early 2000’s, creators of the web were caught between a past riddled with inconsistency and a future that captured their imagination. “Designers and developers were pushing the bounds of what browsers were capable of,” web developer Eevee recalls about using CSS at the time, “Browsers were handling it all somewhat poorly. All the fixes and workarounds and libraries were arcane, brittle, error-prone, and/or heavy.”

Most web designers continued to rely on a combination of HTML table hacks and Netscape-specific tags to create advanced designs. Level two of CSS offered even more possibilities, but designers were hesitant to go all in and risk a bad experience for Netscape users. “Netscape Navigator 4 was holding everyone back,” developer Dave Shea would later say, “It just barely supported CSS, and certainly not in any capacity that we could start building completely table-less sites. And the business case for continued support was too strong to ignore.”

Beneath the surface, however, a vibrant and influential community spread new ideas through blogs and mailing lists and books. That community introduced clever solutions with equally clever names. The “Holly Hack” and “clearfix” from the Position is Everything, maintained by Holly Bergevin and John Gallant. Douglas Bowman’s “Sliding Doors of CSS,” Dan Webb and Patrick Griffith’s “Suckerfish Dropdowns” and Dan Ciederholm’s “Faux Columns” all came from Jeffrey Zeldman’s A List Apart blog. Even Meyer and Allsopp created the CSS Discuss mailing list as a workshop for innovative ideas and practice.

“It’s going to be the people using CSS in the next few years who will come up with the innovative design ideas we need to help drive the potential of the Web in general.”

Molly Holzschlag

And yet, so much of the energy of that community was spent on hacks and workarounds and creative solutions. The most interesting design ideas came always attached with a caveat, a bit of code to make it work in this browser or that. The first edition of CSS Anthology **by Rachel Andrew, which became a handbook for many CSS developers, featured an entire chapter on what to do about Netscape 4.

The innovators of CSS—beset by disparities difficult to explain—were forced to pick apart the language and find a way through to their designs. In the wake of that newness came a creative surge. Some of the most expressive and shrewd designs in the web’s history came out of this era.

That very same community, however, often fell to a collective preoccupation with what they could make CSS do. A culture that, at times, overvalued hacks and workarounds. Largely out of necessity, shared education focused on the how rather than the why. Too-clever techniques that sometimes outpaced their usefulness.

That would begin to change. Holzschlag ended the introduction to her book on CSS with a nod to the future. “It’s going to be the people using CSS in the next few years who will come up with the innovative design ideas we need to help drive the potential of the Web in general.”

Dave Shea was an ideological disciple of the Web Standards Project, an active member of a growing CSS community. He agreed with Holzschlag. “We entered a period where individuals could help shape the future of the web,” he would later describe the moment. Like others, he was frustrated with the limitations of browsers without CSS support.

The antidote to this type of frustration was often to have a bit of fun. Though getting larger by the day, the web design community was small and familiar. For some, it became a hobby to disseminate inspiration. Domino Shriver compiled a list of CSS designs in his site, WebNoveau, later maintained by Meryl Evans. Each day, new web pages designed with CSS would be posted to its homepage. Chris Casciano’s Daily CSS Fun amended that approach. Each day he’d post a new style sheet for the same HTML file, capturing the wide range of designs CSS made possible. In May of 2003, Shea produced his own take on the format when he launched the CSS Zen Garden. The project rested on a simple premise. Each page used exactly the same HTML file with exactly the same content. The only thing that was different was the page’s style sheet, the CSS that was applied to that HTML. Rather than create them himself, Shea solicited style sheets from developers all over the world to create a digital gallery of CSS inspiration. Designs ranged from constructed minimalism to astonishingly baroque. It was a playground to explore what was possible.

At once a source of influence, a practical demonstration of CSS advantages, and a showcase of great web design, the Zen Garden spread to the far ends of the web. What began with five designs soon turned into a website filled with dozens of different designs. And then more. “Hundreds of designers have made their mark—and sometimes their reputations—by creating Zen Garden layouts,” author Jeffrey Zeldman would later say in his book Designing with Web Standards, “and tens of thousands all over the world have learned to love CSS because of it.”

Though Zen Garden would become the most well-known, it was only one contribution to a growing oeuvre of inspiration projects on the web. Web creators wanted to look to the future.

In 2005, Shea published a book based on the project with Molly Holzschlag called The Zen of CSS Design. By then, CSS had web designers’ full attention.

In 1998, in an attempt to keep pace with Microsoft, Netscape made the decision to release their browser for free, and to open source its source code under a newly formed umbrella project known as Mozilla that would ultimately lead to the release of the Firefox browser in 2003.

David Baron and Ian Hickson both began their careers at Mozilla in the late 1990’s as volunteers, and later interns, on the Mozilla Quality Assurance team, identifying standards-compliance bugs. It was through the course of their work that they became deeply familiar not just with how CSS was supposed to work, but how, in practice, it was being used inside of a standards-driven browser. During that time, Hickson and Baron became an integral part of a growing CSS community, and joined the CSS Samurai. They helped write and run the tests for the CSS Test Suite. They became active participants in the www-style mailing list, and later, the CSS Working Group itself.

While Meyer was writing his first book, CSS: The Definitive Guide, he recalls asking Baron and Hickson for help in understanding how some parts of CSS worked. “I doubt that I will ever stop owing them for their dedication to getting me through the wilderness of my own misunderstandings,” he would later say. It was their attention to detail that would soon make them an incredible asset.

Browsers understand style sheets, the language of CSS, based on the words of the specifications at the W3C. If the language is not specific enough, or if not every edge case or feature combination has been considered, this can lead to incompatibilities among browsers. While working at the W3C, Hickson and Baron helped bring the vague language of its technical specifications into clearer focus. They made the definition of CSS more precise, consistent, and easier to implement correctly.

Their work, alongside Bert Bos, Tantek Çelik, Håkon Lie and others, led to a substantial revision of the second version of CSS, what CSS Working Group member Elika Etemad would later describe as “a long process of plugging the holes, fixing errors, and building test suites for the core CSS standard.” It was tireless work, as much about conversation with browser programmers as actual technical work and writing.

It was also a job nobody thought would take very long. There had been two versions of CSS released in a few years. A minor revision was expected to take a fraction of the time. One night at a conference a few months in, several CSS editors commented that if they stayed up late one night, they might be able to get it done before the next day. Instead, the work would take nearly a decade.

For years, Elika Etemad, then known only as ‘fantasai’, had been an active member of the www-style mailing list and Mozilla bug tracker. It had put her in conversations with browser makers, and members of the W3C. Though she had spoken with many different members of the CSS Working Group over the years, some of her most engaged and frequent discussions were with David Baron and Ian Hickson. Like Hickson and Baron, ‘fantasai’ was uncovering bugs and spec errors that no one else had noticed—and happily reporting what she found.

Elika Etemad (Credit: Web Conferences Amsterdam)

That work earned her an invite to the W3C Technical Plenary in 2004. Each year, members of the W3C working groups travel to shifting locations (2020 was the first year it was held virtually) for the event. W3C discussions are mostly done through emails and conference calls and editorial comments. For some members, the plenary is the only time they see each other face to face all year. In 2004, it was held in the south of France, in a town called Mandelieu-la-Napoule, overlooking the Bay of Cannes. It was there that Etemad met Baron and Hickson in person for the first time.

The CSS Working Group, several years into their work on CSS 2.1, invited Etemad to join them. Microsoft had all but pulled back from the standards process after the release of Internet Explorer 6 in 2001. The working group had to work with actively developed browsers like Mozilla and Opera while constrained by the stagnant IE6. They spent years ironing out the details, always feeling on the verge of completion. “We’re almost out of issues, and the new issues we are getting are usually minor stuff like typo fixes and so forth,” Hickson posted in 2006, still years away from a final specification.

During this time, the CSS Working Group was also working on something new. Hickson and Baron had learned from CSS 2.1, an exhaustive but monolithic specification. “We succeeded,” Hickson would later comment, “but boy are they insanely complicated. What we should have done instead is just break the constraints and come up with something simpler, ideally something that more closely matched what browsers implemented at the time.” Over time, the CSS Working Group began to shift their approach. Specifications would no longer be a single, immutable document. It would change over time to accommodate real-world browser implementations.

Beginning with CSS3, also transitioned to a new format to cover a wider set of features and maintain pace with browser development. CSS3 consists of a number of modules, each that addresses a single area of functionality—including color, font, text, and more advanced concepts like media queries. “Some of the CSS3 modules out there are ‘concept albums,’” ‘fantasai’ describes, “specs that are sketching out the future of CSS.” These “concepts” are developed independently and at a variable pace. Each CSS3 module has its own editors. Collectively, they have contributed to a bolder vision of CSS. Individually, they are developed alongside real-world browser implementations and, on their own, can more deftly adapt to change.

The modular approach to CSS3 would prove effective. The second decade of CSS would introduce sweeping changes and refreshing new features. The second decade of CSS would be different than the first. New features would lead to new designs, and eventually, a new web.

The post Chapter 8: CSS appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Swipey Image Grids

Css Tricks - Mon, 05/03/2021 - 4:35am

I hope people think of SVG as a vector format that is good for drawing things. There is plenty more to know, but here’s one more: SVG is good for composition. You draw things at very specific coordinates in SVG and, while they can scale, they tend to stay put. And while SVG is a vector format, you can place raster images onto it. That’s my favorite part of Cassie’s “Swipey image grids” post. The swipey part is cool, but the composition is even cooler.

<svg viewBox="0 0 100 100"> <rect x="30" y="0" width="70" height="50" fill="blue"/> <rect x="60" y="60" width="40" height="40" fill="green"/> <rect x="0" y="30" width="50" height="70" fill="pink"/> <image x="30" y="0" width="70" height="50" href=""/> <image x="60" y="60" width="40" height="40" href=""/> <image x="0" y="30" width="50" height="70" href=""/> </svg>

You’ll need to check this out in Chrome, Edge or Firefox:

CodePen Embed Fallback

Don’t miss Cassie’s interactive examples explaining preserveAspectRatio. That’s a thing I normally think of on the <svg> itself, but is used to great effect on the <image> elements themselves here. It’s like a more powerful object-fit and object-position.

Direct Link to ArticlePermalink

The post Swipey Image Grids appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Safari 14.1 Adds Support for Flexbox Gaps

Css Tricks - Fri, 04/30/2021 - 11:51am

Yay, it’s here! Safari 14.1 reportedly adds support for the gap property in flexbox layouts. We’ve had grid-gap support for some time, but true to its name, it’s limited to grid layouts. Now we can use gap in either type of layout:

.container { display: flex; flex-flow: row wrap; gap: 1.5rem; }

Apple’s been rather quiet about the update. I didn’t even hear about it until Eric Meyer brought it up in an email, and he only heard about it when Jen Simmons tweeted it out.

Did you see, Safari 14.1 shipped yesterday… including support for Gaps in Flexbox.

(*Can I Use & MDN still need to be updated, so they don't show support yet… but it's there! Try it out.)

— Jen Simmons (@jensimmons) April 27, 2021

I checked the WebKit CSS Feature Status and, sure enough, it’s supported. It just wasn’t called out in the release notes. Nothing is posted to Safari’s release notes archive just yet, so maybe we’ll hear about it officially there at some point. For now, it seems that Maximiliano Firtman‘s overview of iOS 14.5 is the deepest look at what’s new.

And how timely is it that Eric recently covered how to use the gap property, not only in grid and flexbox layouts, but multi-column as well.

The post Safari 14.1 Adds Support for Flexbox Gaps appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Web Languages as Compile Targets

Css Tricks - Fri, 04/30/2021 - 8:05am

Jim Nielsen quoting Eric Bailey:

He references an example on Twitter where someone noted you can use the <details> element to “create a native HTML accordion,” to which someone responded: “this works without Bootstrap? &#x1f92f;”

What’s the problem here? From Eric:

the problem that arises from this situation is that it teaches people to think and work framework-first. When that happens, the hard-won, baked-in interoperability and, importantly, accessibility of the [web] platform is thrown away. It’s a compounding problem, as well: The more people don’t use the elements made available to us, the more the notion exists that they’re irrelevant.

I’ve seen people on GitHub routinely amazed by <details>, and assume it’s a special GitHub feature.

Readers, it’s just HTML (lol)

Seriously though, I’m not exactly sure when the perfect time to learn HTML is. Early on, for sure, but I wouldn’t blame anyone for not learning it first. I’m sure I learned it in the context of WordPress PHP templates. I’m sure a lot of people are learning it in the form of JSX or .vue files these days. That’s fine. It’s like learning to play “(Sittin’ On) The Dock of Bay” on guitar before you learn about keys and scales and voicings. But if you never circle back to the fundamentals, it’s limiting, and in the case of the web, damaging.

Direct Link to ArticlePermalink

The post Web Languages as Compile Targets appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Jenny B Kowalski’s A-Z (and a-z) as Variable Letterforms

Css Tricks - Fri, 04/30/2021 - 6:02am

Jenny B Kowalski has been posting a-letter-a-day on Instagram exploring multi-axis variable/responsive letterforms. They are very clever in that one of the axes controls an uppercase-to-lowercase conversion, literally morphing the shape of the letters from an uppercase version to a lowercase version. The other axis is a stroke weight, which also dramatically changes the feel of the letters.

Here’s Q, one of my favorites:

View this post on Instagram

A post shared by Jenny B Kowalski (@jennybkowalski)

She’s using p5.js, but I don’t see any reason these couldn’t be made into a variable font with custom axes.

OK here’s one more. I find the I/i very clever:

View this post on Instagram

A post shared by Jenny B Kowalski (@jennybkowalski)

The post Jenny B Kowalski’s A-Z (and a-z) as Variable Letterforms appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Sending Large Files

Css Tricks - Thu, 04/29/2021 - 7:52am

I’ve got a podcast that will be 10 years old this coming January! Most of those episodes have one or more guests (plus me and Dave). Despite fancy modern options for recording podcasts with guests, like or Zencastr where guests don’t have to worry about recording their own audio, we haven’t made the leap to one of those yet.

We have the guests record their own audio locally (typically Quicktime Player or Windows Voice Recorder) because that way our editor can make the most of the editing process. At the end of the show, our guest has a file that is ~100MB that they need to send over to us.

How that handoff happens isn’t always completely obvious. Typically we don’t share a Slack with our guests, but when we do, that works for sharing large files like that. Even a Nitro-boosted Discord won’t take a file that big, though. I’d say 70% of the time, our guests chuck the file into their Dropbox and create a sharing link for us to download it. From there, it’s probably Google Drive 20% of the time, and the last 10% is some random thing.

That last 10% is stuff like uploading the file to a web server or file storage service the guest controls and they link us up to the file from there. If we were smarter, we’d probably use “File Request” links on Dropbox or Box.

I usually say something like, Send us that file however you like to send large files, because I don’t want to be too prescriptive about what service someone uses. You never know if someone has a particular aversion to some specific tech or company. I would always mention Firefox Send because it was meant for one-off file sending and I find people generally like and trust Mozilla. Alas, Firefox Send shut down.

Unfortunately, some abusive users were beginning to use Firefox Send to ship malware and conduct phishing attacks. When this problem was reported, we stopped the service. Please see the Mozilla Blog for more details on why this service was discontinued.

I guess it’s responsible to try to shut down bad behavior, but of course it was used for bad behavior. Dickwads use any and every service on the entire internet for bad behavior. The real answer, probably, is that it was just a little random side project that didn’t make any money and they didn’t feel like investing the time and money into fixing it. Fair enough, but of course that always costs you trust points. What else is on the chopping block?

I ran across Wormhole the other day which looks like a direct, if not better, replacement. It uses end-to-end encrypted and has some nice UX touches, like getting a share link before the upload is complete. It doesn’t say anything about how they intend to pay for it and support it long-term, but I’d guess the cost is somewhat minimal as they only host the files for 24 hours. They also don’t say if they intend to prevent bad behavior or if it’s just a free-for-all. Even with all the encryption and whatnot, I would imagine if a site like Google or Twitter found that tons of URLs had malware on them, they’d be blacklisted. That wouldn’t stop people from using it but it certainly stops people from finding it too. I did hear from Feross on this, and they have ideas to fight bad behavior if it comes to that.

The thing I’m the most surprised by is that we don’t get more emails where the email service itself just hosts the file. That might sound silly, as email is notorious for not accepting very large file attachments, but that has changed over the years with some of the big players. When you select a file that’s larger than 25MB in Gmail, it’ll offer to upload it to Google Drive and automatically share it with the person you’re sending the email to. iCloud does largely the same thing with Mail Drop.

Me, I use Dropbox quite a bit, but rarely for sharing one-off files. If I want to make sure I have a copy in perpetuity, sometimes I’ll even use a personal Amazon S3 bucket. But mostly I’ll just upload it to Droplr, which I’ve used for ages just for this kind of thing.

The post Sending Large Files appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

How to Monitor Core Web Vitals and Take Action with Raygun

Css Tricks - Thu, 04/29/2021 - 7:50am

Raygun is an error and performance monitoring software for websites and mobile apps. In the case of websites, you install their JavaScript snippet onto your site, which takes 2 seconds, and now you’ve got monitoring in place. Why? Well now you can watch the performance of your site, not just in a single report of one test, but historical dashboards, tracking that performance over time.

This is Real User Monitoring (RUM)

RUM is regarded as better data than the alternative, which is running synthetic tests. Imagine running a performance test against a headless browser. Useful, but fake. Better is to measure how real people are experiencing your site, which is exactly how Raygun does it.

When you log into Raygun, you’ll see high-level trends as to how your site is performing, with the ability to dig deeper into specific pages and individual user sessions.

Now with Core Web Vitals

Google’s latest user experience metrics, Largest Contentful Paint, First Input Delay, and Cumulative Layout Shift are now directly in Raygun:

What I found particularly cool about this is that you don’t have to necessarily pick which pages you want to track CWV on, they’ll be tracked on all pages you have Raygun installed on. I imagine for most sites, that’s all pages, so now you’ll have CWV (and all other performance information) on every page of your site. So rather than picking-and-choosing a handful of pages to test, and risking there being outlier pages that behave slowly, you’ve got full coverage.

Filter to What You Need

You’re going to have a lot of data with Raygun, and that’s a very good thing. But that doesn’t mean it has to be overwhelming or you can’t find exactly what you need. Say you’ve heard from a user that the site is behaving slowly for them in Firefox, you can filter for Firefox and look into that.

Take Action

What makes Raygun really useful is having all of the information you need to take action, with access to waterfall timelines, session information, and instance level diagnostics. This means you don’t just monitor what your CWV scores are, you can actively improve them.

Crash Reporting

We’ve mostly talked about performance reporting here, but note that Raygun is an error reporting tool as well. That is significant, as it means you don’t need to reach for a separate service for that vital need. You get your performance and crash reporting information in the same place.

Find issues. Fix issues. Watch your site improve. After your free trial, pricing starts at just $8/month for plans that have Real User Monitoring with CWV.

Get a 14-day Free Trial of Raygun

The post How to Monitor Core Web Vitals and Take Action with Raygun appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

List Markers and String Styles

Css Tricks - Thu, 04/29/2021 - 4:32am

Lists—we’ve all worked with them in one form or another. I’m talking about HTML’s <ol> and <ul>. Much of the time, because we desire styling control, we turn off the list’s markers completely with list-style-type: none, and start styling from there. Other times, we choose from a very limited set of unordered list markers, such as disc, circle, or square; or a (much) wider range of ordered list markers. We might even, from time to time, supply the URL of an image to be used.

But what if we want to style the markers differently than the contents of the list items? That’s always been difficult at best. Now, thanks to the ::marker pseudo-element, it’s a whole lot easier. You don’t get the full range of CSS to apply to the markers, but there’s still a great deal that can be done.

::marker is available in Firefox and, thanks to work by Igalia, Chrome as well.

Consider this list:

CodePen Embed Fallback

By default, that will yield an ordered list numbered from 1 to 5, using Arabic numerals (1, 2, 3, etc.), each followed by a dot (period), all of which will match the text contents in font face, size, style, color, and so on.

If you had a design direction that required making the numbers smaller or a different color, you’d have to manually create that effect by suppressing the markers and using the ::before pseudo-element and CSS counters and negative text indenting and… well, it would take a scientist to explain it all.

Enter ::marker. Add these styles to the above list, and you’ll get the result shown after.

CodePen Embed Fallback

That’s all you need!

Before you go tearing off to rewrite all your CSS, though, beware: the properties you can apply via ::marker are fairly limited at the moment. As of February 2021, the properties that markers should recognize are:

  • All font properties (font-face, font-size, etc.)
  • The white-space property
  • The color property
  • The internationalization properties text-combine-upright, unicode-bidi, and direction
  • The content property
  • All animation and transition properties

There are some additions in some browsers, but almost all of the additions relate to text styling, not the box model. So if you were thinking you could put all your list numbers into circles with shaded backgrounds, ::marker won’t get you there—you’ll have to return to the hackfest of ::before generated content. For now, anyway: the specification explicitly says more properties may be permitted for ::marker in the future.

There’s also a limitation around white-space, which has rendering bugs in varying browsers. Chrome, for example, treats all whitespace in markers as white-space: pre as the specification says, but won’t let you change it. This should be fixed when Chrome’s LayoutNG (Next Generation) ships, but not until then. Firefox, on the other hand, ignores any white-space values, and treats whitespace like normal-flow text by default.

With those limits in mind, you can still jazz up your markers with the content property. Instead of numbers followed by a period, you can put each number in brackets with a combination of counters and strings.

CodePen Embed Fallback

Note the space after the closing bracket in the content value. That’s included to provide a little bit of space between the marker and the list content. Ordinarily you might think to use a marking or padding, but as we saw earlier, those properties can’t be applied with ::marker. Which is frustrating! Also note the CSS counter list-item. That wasn’t defined anywhere else in the CSS—it’s a built-in counter that all browsers (that understand CSS counters) use to count list items, like those in ordered lists. You can use it in your CSS as well!

If all you want to do is change the text content of a list marker and don’t care about changing any of its styles, you can do that with ::marker, or you can do it with the new cross-browser support for string values on the list-style-type property.

li.warning { list-style-type:"⚠"; } CodePen Embed Fallback

So that’s what’s new in the world of list markers. It might not be something you need to do often, but if you ever do, it’s good to know that the capabilities in this area have increased, and stand to be even better in the future. Let us know if you come up with some clever markers!

The post List Markers and String Styles appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Your Team is Not “Them”

Css Tricks - Wed, 04/28/2021 - 9:35am

This post was written for engineering managers, but anyone is welcome to read it.

Let’s talk for a moment about how we talk about our teams. This might not seem like something that needs a whole article dedicated to it, but it’s actually quite crucial. The way that we refer to our teams sends signals: to stakeholders, to your peers, to the team itself, and even to ourselves. In addressing how we speak about our teams, we’ll also talk about accountability.

I have noticed shared similarities in those folks I consider good managers whose teams deliver well, and those who don’t. It starts with how they communicate about their teams.

Your team is “we”

There can be a perception that as a manager of an organization you are in control at all times. Part of that control can invariably be perceived as how you appear to be in charge, are competent, or how you personally perform. Due to that, some bad behaviors can arise- not due to malice, but due to fear. For this reason, it can be tempting to take credit for success and avoid credit when there is failure.

The irony is that the more that you try to hold on to these external perceptions, the more it will slip away. Why? Because the problems you are solving as a manager really aren’t about you.

Your team is “we”. You are a driving force of that team, no matter how high up the hierarchy chain. What happens on that team is your responsibility. When you speak about your org, you should include yourself in the statement.

When your team succeeds in something though, then you can praise them and leave yourself out of it. Here’s an example:

They really pulled this project over the line, despite the incredibly tight project timeline. Everyone showed up and was driven throughout the engagement. They did a fantastic job.

However, if the team failed at something, the pronoun is then I:

I didn’t recognize how tight this turnaround was and failed to prioritize the team’s time well. I need to reconvene with everyone so we can come up with a better plan.

And never, ever them:

They didn’t adhere to this tight timeline. They just weren’t able to get this project over the line.

Do you see how the last example shirks responsibility for what occurred? Too often I will hear managers relieve themselves of their duties when shit hits the fan, and that is exactly when a manager needs to step up, and dive in to the problems that are their responsibility.

Photo by Marvin Meyer on Unsplash The wider organization

There is another piece of this too, and it impacts how your team operates. It’s that your job is not to be the ambassador of who you manage and think of every other group as separate. You’re part of a larger system. A company is composed of groups, but those groups can only be successful if they’re working together, not if they are protecting their own org at all costs.

I admit I didn’t fully understand the depth of this until I read Patrick Lencioni’s great book The Advantage, thanks to Dalia Havens, a peer at Netlify. In the book, Lencioni talks about how organizational health, not “being smart”, as the biggest key to success. Plenty of smart people with good ideas build companies and see them fail. Success lies in being able to work together.

Fundamentally, other groups at the company are not separate from your group, rather that you’re all part of one whole. The Leadership Team is also a team, and should be treated as your team. How you speak about this team is equally important.

As such, when we talk about successes and failures of any groups, these should also be shared. There should be a sense that you’re all working towards a common goal together, and every group contributes to it. Within a leadership team there should be trust and vulnerability to own their part so that the whole organization can operate at its best.

And, yes, the leadership team as well

You may see where I’m going with this: when you talk about the leadership team, this is “we” too. You can’t speak to your team about decisions that were made at a table with your peers and boss and say “they decided something you don’t agree with” even if you don’t agree. You were there, ideally you took part in that decision, when you talk about that team, presenting them as “we” is important as well.

Why? Because as a manager, our job is to try as much as we can to drive balance and clarity. It’s confusing and disorienting to hear a manager talk about a leadership team they are on as though they aren’t a part of it and not take accountability for what’s happening there. Your reports themselves can’t effect change at that level, so if you don’t own your involvement in the leadership group, you can demoralize your staff and make them feel distrustful of other parts of the company. This can have an effect where folks demonize other teams and their initiatives, which as we discussed is ultimately unhealthy.

Saying “we” holds you accountable to your team for leadership decisions that you are a part of, which is how it should be. If people on your team have issues with the direction, it’s also your responsibility to own that conversation and next steps, as a liaison to the leadership team.

There are of course, some small instances when this might not be appropriate. Something that really goes against your core values that you fought strongly against can make this untenable. I would say those instances should ideally be very infrequent, or unfortunately you may need to pursue another place to work.

Speaking about the Leadership Team in Practice

Here’s how this works in practice, using an example of conveying a decision at the leadership level to the people who report to you:

The leadership team decided that we need to ship at least 3 features this quarter so I guess that’s what we have to figure out to do.


One of the key OKRs this quarter is that we as a company need to double the signups to our platform. We’ve done some calculations that show we can almost certainly get there by shipping 3 features, so let’s all talk about what we can do within our group to make that possible. If you’re curious, we can chat through what initiatives other groups are doing to support this as well.

The first is not just passive, but demotivating. I have made the mistake of using this approach when I want to be liked by my employees and for them to think of me as a peer. But we’re not peers, I have a responsibility to them.

You’ll note in the second approach, we also explained the reasoning behind the decision. I’ve noticed personally that when I have to hold myself accountable to the decision, I care a bit more that people understand the reasoning behind it. This is a very good thing for the morale on your team! Which is arguably one of your most important jobs.

The last line in the second approach also opens up discussion- since you’re taking ownership of the decision, you’re also owning that you know about other pieces of the puzzle, and show a willingness to dive in with your team.

What if you make a mistake?

We all do! Management can be difficult and it’s impossible to be perfect all the time. Try not to beat yourself up, but perhaps show a bit more thoughtfulness next time. I’ve made lots of mistakes as well. It’s not a stick to beat up yourself or others, but a lesson learned to be as mindful as possible and promote a better working environment.

We communicate to our teams, peers, and stakeholders whether or not we’re taking responsibility as a true leader in these moments. We communicate whether we’ll approach a problem with humility, and a desire to collaborate and improve. This may seem to be a detail, but it’s a powerful piece of leading an organization.

The post Your Team is Not “Them” appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Eliminating five top compatibility pain points on the web

Css Tricks - Fri, 04/23/2021 - 10:55am

Robert Nyman and Philip Jägenstedt:

Google is working with other browser vendors and industry partners to fix the top five browser compatibility pain points for web developers. The areas of focus are CSS Flexbox, CSS Grid, position: sticky, aspect-ratio, and CSS transforms.

[…] The goal in 2021 is to eliminate browser compatibility problems in five key focus areas so developers can confidently build on them as reliable foundations.

I’d say slow clap, but I don’t want to sound sarcastic. Full on, regular clapping.

Ten, fifteen years ago, the job of a web designer and developer was heavily thinking about, planning for, and dealing with cross-browser compatibility. These days, it’s still a thing, but it’s not about dealing with bugs, quirks, and frustrating implementation differences like it was then. It’s more edge-case stuff with more obvious work-arounds. And when we’re thinking about the browser and device landscape, we’re doing it through the lens of meeting our users where they are and embracing that landscape. Doing our best, anyway.

If the powers that be can keep chipping away at compatibility problems, that further cements the web as the correct place to build.

I vote for some kind of proper stab at reliable viewport units in 2022, that somehow sensibly handle scrollbars and other browser chrome.

Direct Link to ArticlePermalink

The post Eliminating five top compatibility pain points on the web appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

The Almost-Complete Guide to Cumulative Layout Shift

Css Tricks - Thu, 04/22/2021 - 9:04am

Here’s Jess B. Peck writing all about Google’s Core Web Vitals:

Let’s step back one. CLS is when you’re about to click on a link, and the whole page shifts and you click on a different link instead. It’s when you’re halfway through a blogpost and an ad loads and you lose your place. It is when… the layout shifts. At least, that’s what it’s trying to measure– both those shifts, how often they happen, and the irritation that causes the user.

I didn’t quite understand just how complex Cumulative Layout Shift is before reading Jess’s piece. As Jess explains:

CLS is a measure for a robot to approximate the user perception of instability. This means we’re getting a unit of change over time. It’s a three dimensional equation, and there are tons of things that can affect it. […] The idea is more to alert devs to a problem area, rather than be a perfect measurement of how annoying a page is.

I had this problem on, of all places, Google dot com. I kept tapping an element just as it appeared on screen and this sent me to the wrong page.

Jess notes that these metrics are sometimes more of an art than a science, and so we shouldn’t be obsessed with making sure that just these Core Web Vital metrics are okay. Chris mentioned a while ago that he worries folks might begin to game these metrics for improving their SEO:

This feels like the start of a weird new era of web performance where the metrics of web performance have shifted to user-centric measurements, but people are implementing tricky strategies to game those numbers with methods that, if anything, slightly harm user experience.

Harry Roberts mentioned something similar:

A new and unusual phenomenon: clients reluctant (even refusing) to fix performance issues unless they directly improve Vitals.

— Harry Roberts (@csswizardry) March 5, 2021

I feel like this is our responsibility as web developers, to explain that what we want to do here is reduce user misery on our websites. That’s not to say it’s easy, though, and there’s certainly not much we can do to avoid the shady folks who’ll game these metrics only to improve SEO.

As Jeremy wrote just the other day:

The map is not the territory. The numbers are a proxy for user experience, but it’s notoriously difficult to measure intangible ideas like pain and frustration.

Direct Link to ArticlePermalink

The post The Almost-Complete Guide to Cumulative Layout Shift appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Tools to Improve UX and Win Over Your Customers

Css Tricks - Thu, 04/22/2021 - 9:03am

Try Hotjar for free today!

An enjoyable user experience and high conversion rates go hand-in-hand. It makes sense then, that if you want to improve conversion rates, your first task is to improve user experience.

To improve UX, deeply understanding your users is non-negotiable. But speaking with customers one by one to figure out their pain points isn’t a feasible or fast strategy.

Which is why today, we’re showing you different tools you can use to learn more about your customers so you can make quick and impactful changes that improve UX and increase conversions!

Why your visitors aren’t converting

Before we talk about the different tools to help you understand your users, let’s look at five main reasons why you don’t see as many conversions as you’d like:

Your website is confusing to navigate: If navigating your way through a cornfield maze is easier than trying to get to the checkout page on your website, you have a problem. Users like it when they can get from point A to point B with no roadblocks or confusion.

You’re guessing what your visitors want (but don’t actually know): As someone who knows your product inside and out, it can be hard to take a step back to try and get into the mind of your visitors. Unless you’re gathering voice of customer data, any changes you make will be based on guesswork.

Your visitors are distracted: If your visitors are distracted by unimportant elements on your page, they’ll miss your CTA and won’t convert. Even worse, they’ll get frustrated by a lack of flow and leave your website (and maybe even head over to your competitor).

There are roadblocks you aren’t aware of: Using your website might be easy for you and your team—you helped build it, after all—but that bias makes it challenging to see roadblocks and other issues that could prevent your users from having an enjoyable experience.

Your users don’t trust your website: Things like poor design, spelling issues in your copy, and low-quality imagery can turn potential customers away.

Simply put, if your website is clunky, you’ll irritate your users, and they won’t convert. But when you understand what your visitors want—and why they want it—you’ll be able to build an experience they love.

4 tools to improve UX and conversions

At Hotjar, we want to help you make your users happy and avoid the above problems! Here are four tools you can use to improve your user experience, make your customers smile from ear to ear, and as a result, skyrocket your conversions!


Heatmaps are visual representations of your analytical data, organized so you can easily spot popular (and unpopular) areas of your website. With heatmaps, you can figure out which areas of your website contribute to a poor user experience.

You can use three types of heatmaps: scroll maps, click maps, and move maps.

Scroll maps A scroll map

Scroll maps show you how far users scroll down your page. Red areas mean more visitors went to that part of your page, whereas the blue areas signal low activity. They can help you understand if users see key information.

Click maps A click map

Click maps show an aggregate of where users click their mouse or tap the screen on desktop and mobile devices. Click maps help you understand if your CTAs are in the right place, if people are clicking on clickable items, and whether or not users are ‘rage clicking’ on your site.

Move maps A move map

Move maps show where users move their mouse as they go through your page. Research suggests that mouse movement correlates with eye movement, helping you understand what people look at on your website.

You can use Hotjar’s Heatmaps to:

  • See whether important information is within the “hottest” areas of your heatmap (or if it’s being missed because it’s in areas where visitors aren’t scrolling to)
  • Decide where to move essential information based on where your users focus their attention
  • Spot where your visitors’ attention drops
  • A/B test to see how user behavior changes
  • Make sure clicks and taps happen on “clickable” elements
  • See how behavior changes on different devices (i.e., desktop, tablet, and mobile)

It’s easy to improve UX when you know how your users are really using your website. Recordings let you watch live playbacks of each user on your site so you can see exactly how your visitors navigate through your website, identify roadblocks, and make sense of your web analytics.

Recordings let you see mouse movement, scrolling, clicks, and keyboard strokes across multiple pages on your site.

You can use Hotjar Recordings to:

  • Make sense of your bounce rate by analyzing why your visitors are leaving your page(s)
  • Empathize with your visitors by understanding their roadblocks and frustrations on your website
  • Uncover what’s preventing your visitors from converting
  • Find bugs and see if something’s not working as planned (like pages that load differently on mobile versus desktop)
  • See how long it really takes for users to convert (and identify what’s preventing them from converting sooner)
Incoming Feedback

With Hotjar’s Incoming Feedback tool, you can eliminate the guesswork and get into your user’s mind by placing feedback widgets right on your website. Your visitors can tell you exactly what they like and dislike, and you can use that information to fix issues and provide more of what your users love.

Incoming Feedback widget

Users can also highlight certain elements of your site, so you don’t need to guess what they’re referring to—you’ll know precisely what they’re talking about!

You can use Hotjar’s Incoming Feedback to:

  • Get feedback on specific elements on your website and understand why your users like and dislike certain aspects of your site
  • Gather the emotions of your website visitors
  • Pinpoint exactly which areas are causing trouble for your users
  • Track changes over time to see if user experience is improving

Gathering voice of customer (VOC) data is easy with Hotjar Surveys. Hotjar has two types of surveys: on-site and off-site.

On-site surveys let you ask your users questions while on specific pages of your website. By asking open- or closed-ended questions (or a mix of both), you can get into the mind of your visitor and get valuable feedback to improve your website and increase conversions.

You can also use Hotjar’s on-site surveys to follow up on specific questions. For example, if you asked, “did you find what you were looking for today?” and someone clicked “no,” you can have a follow-up question asking them to explain why.

You can use Hotjar’s Surveys to:

  • Validate new product ideas
  • Understand why your visitors like or dislike aspects of your site
  • Find areas of your site that need fixing (for example, place an on-site survey on pages with high bounce rates to figure out why users are leaving)
  • Gather valuable insight from your users
  • Improve conversions through post-purchase surveys
  • how your customers you care about their input
Try Hotjar for free today!

All of Hotjar’s tools collect powerful data in ways everyone on your team will be able to understand. Using data to drive your decision-making process will steer you in the right direction, keep users happy, and improve your conversion rates!

Click to sign up and see how easy it is to understand your users with Hotjar!

Try Hotjar for free today!

P.S. To get you up to speed, we’ve put together checklists to help you improve user experience and increase conversions during your free Hotjar trial &#x1f4af;

The post Tools to Improve UX and Win Over Your Customers appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Still Hoping for Better Native Page Transitions

Css Tricks - Wed, 04/21/2021 - 12:57pm

It would be nice to be able to animate the transition between pages if we want to on the web without resorting to hacks or full-blown architecture choices to achieve it. I could imagine an API that would run stuff, perhaps integrating with WAAPI, before the page is unloaded, and other stuff after the next page loads in. This, with otherwise regular ol’ anchor links and page loads.

We do have an onbeforeunload API, but I’m not sure what kind of baggage that has. We can technically build page transitions now, even without single-page-app architecture, but what I want are purpose-built APIs that help us do it cleanly (understandable functions) and with both performance (working as quickly as clicking links normally does) and accessibility (like focus handling) in mind.

If you’re building a single-page app anyway, you get the freedom to animate between views because the page never reloads. The danger here is that you might pick a single-page app just for this ability, which is what I mean by having to buy into a site architecture just to achieve this. That feels like an unfortunate trade-off, as single-page apps bring a ton of overhead, like tooling and accessibility concerns, that you wouldn’t have otherwise needed.

Without a single-page app, you could use something like Turbo and animate.css like this. Or, Adam’s new, a clip-path() based homage to Daniel Edan’s masterpiece. Maybe if that approach was paired with it would be as fast as any other internal link click.

There are other players trying to figure this out, like smoothState.js and Swup. The trick being: intercept the action to move to the next page, run the animation first, then load the next page, and animate the new page in. Technically, it slows things down a bit, but you can do it pretty efficiently and the movement adds enough distraction that the perceived performance might even be better.

Ideally, we wouldn’t have to animate the entire page but we could have total control to make more interesting transitions. Heck, I was doing that a decade ago with a page for a musician where clicking around the site just moved things around so that the audio would keep playing (and it was fun).

This would be a great place for the web platform to step in. I remember Jake pushed for this years ago, but I’m not sure if that went anywhere. Then we got portals which are… ok? Those are like if you load an iframe on the page and then animate it to take over the whole page (and update the URL). Not much animation nuance possible there, but you could certainly swipe some pages around or fade them in and out (hey here’s another one: Highway), like jQuery Mobile did back in ancient times.

The post Still Hoping for Better Native Page Transitions appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Sticky Headers: 5 Ways to Make Them Better

Css Tricks - Wed, 04/21/2021 - 10:53am

Page Laubheimer says that if you’re going to do a sticky header…

  1. Keep it small.
  2. Visually contrast it with the rest of the page.
  3. If it’s going to move, keep it minimal. (I’d say, respect prefers-reduced-motion.)
  4. Consider “partially persistent headers.” (Jemima Abu calls it a Smart Navbar.)
  5. Actually, maybe don’t even do it.

I generally like the term “sticky” header, because it implies you should use position: sticky for them, which I think you should. It used to be done with position: fixed, but that was trickier to pull off since the header would move in-and-out of flow of the document. Using sticky positioning helps reserve that space automatically without JavaScript or magic numbers.

Direct Link to ArticlePermalink

The post Sticky Headers: 5 Ways to Make Them Better appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

How to Improve CSS Performance

Css Tricks - Mon, 04/19/2021 - 11:33am

There is no doubt that CSS plays a huge role in web performance. Milica Mihajlija puts a point on exactly why:

When there is CSS available for a page, whether it’s inline or an external stylesheet, the browser delays rendering until the CSS is parsed. This is because pages without CSS are often unusable.

The browser has to wait until the CSS is both downloaded and parsed to show us that first rendering of the page, otherwise browsing the web would be a terribly visually jerky to browse. We’d probably write JavaScript to delay page rendering on purpose if that’s how the native web worked.

So how do you improve it? The classics like caching, minification, and compression help. But also, shipping less of it, and only loading the bit you need and the rest after the first render.

It’s entirely about how and how much CSS you load, and has very little to do with the contents of the the CSS.

Direct Link to ArticlePermalink

The post How to Improve CSS Performance appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Float an Element to the Bottom Corner

Css Tricks - Mon, 04/19/2021 - 4:17am

Need to lay out an element to the right or the left, such that text wraps around it? That’s an easy task for the float property. But what about if you also want to push that element (let’s call it an image) to one of the bottom corners while we’re at it? Sounds a bit tricky, right? We probably need JavaScript?

Nope, few lines of (tricky) CSS can do it! Here’s the CSS-only solution that will make your image to stick to the bottom corner, regardless of the size and content.

Resize the wrapper element and see the magic at work:

CodePen Embed Fallback

Let’s dissect the code.

Markup and layout

We’ll need a wrapper element to contain everything, and we’ll be using flexbox on it. Flexbox allows us to rely on the default stretch alignment to be able to later use height: 100%.

<div class="wrapper"> <div class="box"> <div class="float"><img></div> Lorem ipsum dolor ... </div> </div> .wrapper { display: flex; } .float { float: right; height: 100%; display: flex; align-items: flex-end; shape-outside: inset(calc(100% - 100px) 0 0); }

The .box within the .wrapper is our flex item. We don’t need any particular CSS applied to the box. It defines the height of the wrapper and, at the same time, is stretched to the same height. This behavior will give us a “reference height” that can be used by the child elements.

From the specification:

If the flex item has align-self: stretch, redo layout for its contents, treating this used size as its definite cross size so that percentage-sized children can be resolved.

The keyword is the definite which allows us to safely use a percentage (%) height inside the box element.

Now for the floated element

Our .float element will take the entire height next to the text content, thanks to the height calculation we detailed above. Inside this element we push the image to the bottom using flexbox alignment.

The image is floated to the right but the free space above it prevents the content from wrapping around it.

Now for the real trickery, using the shape-outside property. Here’s how MDN defines it:

The shape-outside CSS property defines a shape—which may be non-rectangular—around which adjacent inline content should wrap. By default, inline content wraps around its margin box; shape-outside provides a way to customize this wrapping, making it possible to wrap text around complex objects rather than simple boxes.

In other words, shape-outside sets the way content flows around an element’s bounding box.

It takes a number of values. One of those is the inset() function which, again, according to MDN:

Defines an inset rectangle. When all of the first four arguments are supplied they represent the top, right, bottom and left offsets from the reference box inward that define the positions of the edges of the inset rectangle.

So, with shape-outside: inset(calc(100% - X) 0 0) we can create an inset rectangle that starts exactly at the top of the image. And the top is equal to 100% - X, where X is the image height and 100% is the height of the .float element. This allows the text to wrap within the free space on the top of the image. This is responsive, plus we can easily switch between left and right (by adjusting the float property)

That’s it! The only major caveat is that you need to know the image height.

Want more?

We can extend this concept a little further to account for fancier situations. For example, we can float the image to the right, but pin it to the middle of the box with justify-content: center: and also adjust our inset rectangle to the middle by changing the shape-outside from inset(calc(100% - X) 0 0) to inset(calc(50% - X/2) 0 0)

CodePen Embed Fallback

We can also float two images at both bottom corners:

CodePen Embed Fallback

Nothing complex here. I am simply using the same floating element twice, once on the right, and again on the left. And why stop at two corners when we can place images at all four corners:

CodePen Embed Fallback

The same basic idea is at play here, but we’re are also relying on the common float feature for the top images. However, you’ll notice that this is where the concept starts to break down a bit, and we get some unwanted overflow depending on the size of the containing box. We can make the height of the .float element greater than 100% and apply somewhat “magic numbers” that smooth things out by adjusting the padding and margin of the images.

Did you know that shape-outside accepts radial-gradient() as a value? We can use that to place rounded images like below:

CodePen Embed Fallback

The transparent part of the gradient is the free space where the text can go. You may have noticed that we applied a border-radius to the image as well. The shape-outside property will simply affect the .float element and we need to manually adjust the shape of the image to follow the shape defined by shape-outside.

While we’re at it, let’s combine this with our earlier example that pins the image to the vertical center of the box using justify-content: center:

CodePen Embed Fallback

Another radial-gradient() and also another border-radius configuration.

We could have used a linear-gradient() instead to make a triangular shape for the wrapping area:

CodePen Embed Fallback

This is the same idea that we used for the radial-gradient(). The big difference is that we’re using clip-path instead of border-radius to cut our image.

And, since we did it for the others, let’s use the justify-content: center idea to pin the image to the vertical center of the box’s right edge:

CodePen Embed Fallback

We used a conic-gradient() in the above demo with shape-outside to define the triangular shape and clip-path to get a similar shape on the image

All of these examples can still be optimized using less of code in the case that the image is decorative (when it’s not needed inside the HTML for SEO purposes). Let’s replace the .float element with a pseudo-element and apply the image as background instead:

CodePen Embed Fallback

We’re using mask to show just the portion of the image that we need and, guess what, it uses the same value as shape-outside! So, all we had to do is define one value for the shape.

That’s it!

There are a lot of possibilities here to place not just rectangles in corners, but any kind of shape at any position, using largely the same code structure. We only need to:

  • Adjust the shape-outside property to define the shape
  • Apply some styling to the image to follow the previously defined shape or apply the same value to mask in case we are using the pseudo element version

Then everything holds it place, even in responsive designs.

The post Float an Element to the Bottom Corner appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Platform News: Using :focus-visible, BBC’s New Typeface, Declarative Shadow DOMs, A11Y and Placeholders

Css Tricks - Fri, 04/16/2021 - 4:33am

There’s a whole lot of accessibility in this week’s news, from the nuances of using :focus-visible and input placeholders, to accessible typefaces and a Safari bug with :display: contents. Plus, a snippet for a bare-bones web component that supports style encapsulation.

Now may be a good time to start using :focus-visible

The CSS :focus-visible pseudo-class replaces :focus as the new way to create custom focus indicators for keyboard users. Chrome recently switched from :focus to :focus-visible in the user agent stylesheet and, as a result of that change, the default focus ring is no longer shown when the user clicks or taps a button.

When switching from :focus to :focus-visible, consider backwards compatibility. Your keyboard focus indicators should be clearly visible in all browsers, not just the ones that support :focus-visible. If you only style :focus-visible, non-supporting browsers will show the default focus ring which, depending on your design, “may not be sufficiently clear or visible at all.”

button { background: white; } button:focus-visible { outline: none; background: #ffdd00; /* gold */ }

A good way to start using :focus-visible today is to define the focus styles in a :focus rule and then immediately undo these same styles in a :focus:not(:focus-visible) rule. This is admittedly not the most elegant and intuitive pattern, but it works well in all browsers:

  • Browsers that don’t support :focus-visible use the focus styles defined in the :focus rule and ignore the second style rule completely (because :focus-visible is unknown to them).
  • In browsers that do support :focus-visible, the second style rule reverts the focus styles defined in the :focus rule if the :focus-visible state isn’t active as well. In other words, the focus styles defined in the :focus rule are only in effect when :focus-visible is also active.
button:focus { outline: none; background: #ffdd00; /* gold */ } button:focus:not(:focus-visible) { background: white; /* undo gold */ } The BBC created a more accessible typeface

The BBC created their own custom typeface called Reith (named after the BBC’s founder Sir John Reith). Their goal was to create a font that supports multiple languages and is easier to read, especially on small devices. The font was tested with mixed-ability user groups (dyslexia and vision impairment) and across different screen sizes.

We [the BBC] were using Helvetica or Arial. We also had Gill Sans as the corporate typeface. These typefaces were designed a hundred years ago for the printed page [and] don’t perform well on today’s modern digital screens.

Reith Sans can bee seen in use on BBC Sport

Note: If you’d like to inspect Reith Sans and Reith Serif in Wakamai Fondue, you can quickly access the URLs of the WOFF2 files in the “All fonts on page” section of the Fonts pane in Firefox’s DOM inspector on BBC’s website.

display: contents is still not accessible in Safari

The CSS display: contents value has been supported in browsers since 2018. An element with this value “does not generate any boxes” and is effectively replaced by its children. This is especially useful in flex and grid layouts, where the contents value can be used to “promote” more deeply nested elements to flex/grid items while retaining a semantic document structure.

Source: Manuel Rego Casasnovas

Unfortunately, this feature originally shipped with an implementation bug that removed the element from the browser’s accessibility tree. For example, applying display: contents to a <ul> element resulted in that element no longer mentioned by screen readers. Since then, this bug has been fixed in Firefox and Chrome (in the latest version).

View on CodePen

In Chrome and Firefox, the screen reader informs the user that the “Main, navigation” contains a “list, 2 items.” In Safari, the latter part is missing because the <ul> and <li> elements are not present in the accessibility tree. Until Apple fixes this bug in Safari, be careful when using the contents value on semantic elements and test in screen readers to confirm that your pages are accessible in Safari as well.

Set opacity when overriding the color of placeholder text

Accessibility experts recommend avoiding placeholders if possible because they can be confused for pre-populated text and disappear when the user starts entering a value. However, many websites (including Wikipedia and GOV.UK) use placeholders in simple web forms that contain only a single input field, such as a search field.

The subscription form for the CSS-Tricks newsletter uses a placeholder in the email field

Placeholders can be styled via the widely supported ::placeholder pseudo-element. If your design calls for a custom color for placeholder text, make sure to specify both color and opacity. The latter is needed for Firefox, which applies opacity: 0.54 to ::placeholder by default. If you don’t override this value, your placeholder text may have insufficient contrast in Firefox.

.search-field::placeholder { color: #727272; opacity: 1; /* needed for Firefox */ } The placeholder text on eBay’s website is lighter in Firefox and doesn’t meet the minimum contrast requirement of 4.5:1 Declarative shadow DOM could help popularize style encapsulation

One of the key features of shadow DOM is style encapsulation, wherein the outer page’s style rules don’t match elements inside the shadow tree, and vice versa. In order to use this feature, you need to attach a shadow DOM tree to an element (usually a custom element, like <my-element>) and copy the element’s template (usually from a <template> element in the DOM) to the element’s newly created shadow DOM.

These steps can only be performed in JavaScript. If you’re only interested in style encapsulation and don’t need any dynamic functionality for your element, here is the minimum amount of JavaScript required to create a custom element with a shadow DOM:

customElements.define( "my-element", class extends HTMLElement { constructor() { super(); // find <template id="my-template"> in the DOM let template = document.getElementById("my-template"); // make a copy of the template contents… let content = template.content.cloneNode(true); // …and inject it into <my-element>’s shadow DOM this.attachShadow({ mode: "open" }).appendChild(content); } } );

For an example of style encapsulation, see Miriam Suzanne’s <media-object> element on CodePen. The scoped styles are located in the <template> element in the HTML pane. Notice how this CSS code can use simple selectors, such as article, that only match elements inside <media-object>’s shadow DOM.

JavaScript may soon no longer be required to create this type of style encapsulation in modern browsers. Earlier this week, Chrome became the first browser to ship Google’s Declarative Shadow DOM proposal. If it becomes a standard, this feature will also make it possible to use Shadow DOM in combination with server-side rendering.

The post Platform News: Using :focus-visible, BBC’s New Typeface, Declarative Shadow DOMs, A11Y and Placeholders appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Not Your Typical Horizontal Rules

Css Tricks - Fri, 04/16/2021 - 4:31am

The default browser style for <hr> is so weird. It’s basically:

border-style: inset; border-width: 1px;

The default border-color is black, but the border doesn’t actually look black, because the inset border “adds a split tone to the line that makes the element appear slightly depressed.”

If I kick up the border-width to 40px you can see it more clearly:

I often reset an <hr> to be “just a line” and it always gets me because I’ll try something, like height: 1px with a background at first, but that’s not right. The easier way to clear it is to turn off all the borders then only use border-top or border-bottom. Or, turn off all the borders, set a height, and use a background.

Annnyway… Sara has some of the nicest horizontal rules in town on the current design of her site, and she’s written it all up. Guess what? They aren’t even <hr> elements! It turns out the only styling hook you have is CSS, which wasn’t as adaptive as Sara needed, so she ended up with a <div role="separator"> (TIL!) and inline SVG.

The best way to get the full flexibility of an SVG is by inlining it. But the <hr> element is content-less — it has no opening and closing tags within which you can place other elements.

The only way to work around the limitations of <hr> while preserving semantics for screen reader users is to use a div and provide the semantics of an hr using ARIA.

Direct Link to ArticlePermalink

The post Not Your Typical Horizontal Rules appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Flash of inAccurate coloR Theme (FART)

Css Tricks - Thu, 04/15/2021 - 12:13pm

There is a lot to think about when implementing a dark mode theme on a website. We have a huge guide on it. There are some very clever quick wins out there, but there are also some quite tricky things to pull off. One of those tricky things is how it’s not a dark mode “toggle” between dark and light, but really three modes you need to support: dark, light, and use system preference. That’s similar to how audio preferences work in many apps, which allow you to very specifically choose which audio input or output you want, or default to the system preference.

CSS and JavaScript can handle the system preference angle, via the prefers-color-scheme API, but if the user preference has changed, and that preference is now different than the user preference, you’re in the territory of “Flash of inAccurate coloR Theme” or FART. Ok ok, it’s a tounge-in-cheek acronym, but it’s potentially quite a visually obnoxious problem so I’m keeping it. It’s in the same vein that FOUT (Flash of Unstyled Text) is for font loading.

Storing a user preference means something like a cookie, localStorage, or some kind of database. If access to that data means running JavaScript, e.g. localStorage.getItem('color-mode-preference');, then you’re in FART territory, because your JavaScript is very likely running after a page’s first render, lest you’re otherwise unnecessarily delaying page render.

User preference is “dark” mode, but the system preference is “light” mode (or unset), so when the page refreshes, you get FART.

You can access a cookie with a server-side language before page-render, meaning you could use it to output something like <html class="user-setting-dark-mode"> and style accordingly, which deftly avoids FART, but that means a site that even has access to a server-side language (Jamstack sites do not, for example).

Allllll that to say that I appreciated Rob Morieson’s article about dark mode because it didn’t punt on this important issue. It’s very specifically about doing this in Next.js, and uses localStorage, but because Next.js is JavaScript-rendered, you can force it to check the user-saved preference as the very first thing it does. That means it will render correctly the the first time (no flash). You do have to turn off server-side rendering for this to work, which is a gnarly trade-off though.

I’m not convinced there is a good way to avoid FART without a server-side language or force-delayed page renders.

The post Flash of inAccurate coloR Theme (FART) appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Syndicate content
©2003 - Present Akamai Design & Development.