Tag: Things

Reactive jQuery for Spaghetti-fied Legacy Codebases (or When You Can’t Have Nice Things)

I can hear you crying out now: “Why on Earth would you want to use jQuery when there are much better tools available? Madness! What sort of maniac are you?” These are reasonable questions, and I’ll answer them with a little bit of context.

In my current job, I am responsible for the care and feeding of a legacy website. It’s old. The front-end relies on jQuery, and like most old legacy systems, it’s not in the best shape. That alone isn’t the worst, but I’m working with additional constraints. For example, we’re working on a full rewrite of the system, so massive refactoring work isn’t being approved, and I’m also not permitted to add new dependencies to the existing system without a full security review, which historically can take up to a year. Effectively, jQuery is the only JavaScript library I can use, since it’s already there. 

My company has only recently come to realize that front-end developers might have important skills to contribute, so the entire front end of the app was written by developers unaware of best practices, and often contemptuous of their assignment. As a result, the code quality is wildly uneven and quite poor and unidiomatic overall.

Yeah, I work in that legacy codebase: quintessential jQuery spaghetti.

Someone has to do it, and since there will always be more legacy code in the world than greenfield projects, there will always be lots of us. I don’t want your sympathy, either. Dealing with this stuff, learning to cope with front-end spaghetti on such a massive scale has made me a better, if crankier, developer.

So how do you know if you’ve got spaghetti jQuery on your hands? One reliable code smell I’ve found is a lack of the venerable old .toggle(). If you’ve managed to successfully not think about jQuery for a while, it is a library that smooths cross-browser compatibility issues while also making DOM queries and mutations incredibly easy. There’s nothing inherently wrong with that, but direct DOM manipulation can be very hard to scale if you’re not careful. The more DOM-manipulation you write, the more defensive against DOM mutation you become. Eventually, you can find yourself with an entire codebase written that way and, combined with less-than-ideal scope management, you are essentially working in an app where all of the state is in the DOM and you can never trust what state the DOM will be in when you need to make changes; changes could swoop in from anywhere in your app whether you like it or not. Your code gets more procedural, bloating things up with more explicit instructions, trying to pull all the data you need from the DOM itself and force it into the state you need it to be in.

This is why .toggle() is often the first thing to go: if you can’t be sure whether an element is visible or not, you have to use .show() and .hide() instead. I’m not saying .show() and .hide() should be Considered Harmful™, but I’ve found they’re a good indication that there might be bigger problems afoot.

What can you do to combat this? One solution my coworkers and I have found takes a hint directly from the reactive frameworks we’d rather be using: observables and state management. We’ve all found that hand-rolling state objects and event-driven update functions while treating our DOM like a one-way dataflow template leads to more predictable results that are easier to change over time.

We each approach the problem a little differently. My take on reactive jQuery is distinctly flavored like Vue drop-in and takes advantage of some “advanced” CSS.

If you check out the script, you’ll see there are two different things happening. First, we have a State object that holds all of the values for our page, and we have a big mess of events.

var State = {   num: 0,   firstName: "",   lastName: "",   titleColor: "black",   updateState: function(key, value){     this[key] = value;              $  ("[data-text]").each(function(index, elem){       var tag = $  (elem).attr("data-tag");       $  (elem).text(State[tag]);     });          $  ("[data-color]").each(function(index, elem){       var tag = $  (elem).attr("data-tag");       $  (elem).attr("data-color", State[tag]);     });   } };

I’ll admit it, I love custom HTML attributes, and I’ve applied them liberally throughout my solution. I’ve never liked how HTML classes often do double-duty as CSS hooks and JavaScript hooks, and how if you use a class for both purposes at once, you’ve introduced brittleness into your script. This problem goes away completely with HTML attributes. Classes become classes again, and the attributes become whatever metadata or styling hook I need.

If you look at the HTML, you’ll find that every element in the DOM that needs to display data has a data-tag attribute with a value that corresponds to a property in the State object that contains the data to be displayed, and an attribute with no value that describes the sort of transformation that needs to happen to the element it’s applied to. This example has two different sorts of transformations, text and color.

<h1 data-tag="titleColor" data-color>jDux is super cool!</h1>

On to the events. Every change we want to make to our data is fired by an event. In the script, you’ll find every event we’re concerned about listed with its own .on() method. Every event triggers an update method and sends two pieces of information: which property in the State object that needs to be updated, and the new value it should be set to.

$  ("#inc").on("click", function(){   State.updateState("num", State.num + 1) });  $  ("#dec").on("click", function(){   State.updateState("num", State.num - 1) });  $  ("#firstNameInput").on("input", function(){   State.updateState("firstName", $  (this).val() ) });  $  ("#lastNameInput").on("input", function(){   State.updateState("lastName", $  (this).val() ) });  $  ('[class^=button]').on("click", function(e) {   State.updateState('titleColor', e.target.innerText); });

This brings us to State.updateState(), the update function that keeps your page in sync with your state object. Every time it runs, it updates all the tagged values on the page. It’s not the most efficient thing to redo everything on the page every time, but it’s a lot simpler, and as I hope I’ve already made clear, this is an imperfect solution for an imperfect codebase.

$  (document).ready(function(){   State.updateState(); });

The first thing the update function does is update the value according to the property it receives. Then it runs the two transformations I mentioned. For text elements, it makes a list of all data-text nodes, grabs their data-tag value, and sets the text to whatever is in the tagged property. Color works a little differently, setting the data-color attribute to the value of the tagged property, and then relies on the CSS, which styles the data-color properties to show the correct style.

I’ve also added a document.ready, so we can run the update function on load and display our default values. You can pull default values from the DOM, or an AJAX call, or just load the State object with them already entered as I’ve done here.

And that’s it! All we do is keep the state in the JavaScript, observe our events, and react to changes as they happen. Simple, right?

What’s the benefit here? Working with a pattern like this maintains a single source of truth in your state object that you control, you can trust and you can enforce. If you ever lose trust that your DOM is correct, all you need to do is re-run the update function with no arguments and your values become consistent with the state object again.

Is this kind of hokey and primitive? Absolutely. Would you want to build an entire system out of this? Certainly not. If you have better tools available to you, you should use them. But if you’re in a highly restrictive legacy codebase like I am, try writing your next feature with Reactive jQuery and see if it makes your code, and your life, simpler.


The post Reactive jQuery for Spaghetti-fied Legacy Codebases (or When You Can’t Have Nice Things) appeared first on CSS-Tricks.

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

CSS-Tricks

, , , , , , ,

Exciting Things on the Horizon For CSS Layout

Michelle Barker notes that it’s been a heck of a week for us CSS layout nerds.

  1. Firefox has long had the best DevTools for CSS Grid, but Chrome is about to catch up and go one bit better by visualizing grid line numbers and names.
  2. Firefox supports gap for display: flex, which is great, and now Chrome is getting that too.
  3. Firefox is trying out an idea for masonry layout.

Direct Link to ArticlePermalink

The post Exciting Things on the Horizon For CSS Layout appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

SVG, Favicons, and All the Fun Things We Can Do With Them

Favicons are the little icons you see in your browser tab. They help you understand which site is which when you’re scanning through your browser’s bookmarks and open tabs. They’re a neat part of internet history that are capable of performing some cool tricks.

One very new trick is the ability to use SVG as a favicon. It’s something that most modern browsers support, with more support on the way.

Here’s the code for how to add favicons to your site:

<link rel="icon" type="image/svg+xml" href="/favicon.svg"> <link rel="alternate icon" href="/favicon.ico"> <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#ff8a01">

If a browser doesn’t support a SVG favicon, it will ignore the first link element declaration and continue on to the second. This ensures that all browsers that support favicons can enjoy the experience. 

You may also notice the alternate attribute value for our rel declaration in the second line. This programmatically communicates to the browser that the favicon with a file format that uses .ico is specifically used as an alternate presentation.

Following the favicons is a line of code that loads another SVG image, one called safari-pinned-tab.svg. This is to support Safari’s pinned tab functionality, which existed before other browsers had SVG favicon support. There’s additional files you can add here to enhance your site for different apps and services, but more on that in a bit.

Here’s more detail on the current level of SVG favicon support:

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Firefox IE Edge Safari
80 41 No 80 TP

Mobile / Tablet

Android Chrome Android Firefox Android iOS Safari
80 No No 13.4

Why SVG?

You may be questioning why this is needed. The .ico file format has been around forever and can support images up to 256×256 pixels in size. Here are three answers for you.

Ease of authoring

It’s a pain to make .ico files. The file is a proprietary format used by Microsoft, meaning you’ll need specialized tools to make them. SVG is an open standard, meaning you can use them without any further tooling or platform lock-in.

Future-proofing

Retina? 5k? 6k? When we use a resolution-agnostic SVG file for a favicon, we guarantee that our favicons look crisp on future devices, regardless of how large their displays get

Performance

SVGs are usually very small files, especially when compared to their raster image counterparts — even more-so if you optimize them beforehand. By only using a 16×16 pixel favicon as a fallback for browsers that don’t support SVG, we provide a combination that enjoys a high degree of support with a smaller file size to boot. 

This might seem a bit extreme, but when it comes to web performance, every byte counts!

Tricks

Another cool thing about SVG is we can embed CSS directly in it. This means we can do fun things like dynamically adjust them with JavaScript, provided the SVG is declared inline and not embedded using an img element.

<svg  version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">   <style>     path { fill: #272019; }   </style>   <!-- etc. --> </svg>

Since SVG favicons are embedded using the link element, they can’t really be modified using JavaScript. We can, however, use things like emoji and media queries.

Emoji

Lea Verou had a genius idea about using emoji inside of SVG’s text element to make a quick favicon with a transparent background that holds up at small sizes.

In response, Chris Coyier whipped up a neat little demo that lets you play around with the concept.

Dark Mode support

Both Thomas Steiner and Mathias Bynens independently stumbled across the idea that you can use the prefers-color-scheme media query to provide support for dark mode. This work is built off of Jake Archibald’s exploration of SVG and media queries.

<svg width="128" height="128" xmlns="http://www.w3.org/2000/svg">   <style>     path { fill: #000000; }     @media (prefers-color-scheme: dark) {       path { fill: #ffffff; }     }   </style>   <path d="M111.904 52.937a1.95 1.95 0 00-1.555-1.314l-30.835-4.502-13.786-28.136c-.653-1.313-2.803-1.313-3.456 0L48.486 47.121l-30.835 4.502a1.95 1.95 0 00-1.555 1.314 1.952 1.952 0 00.48 1.99l22.33 21.894-5.28 30.918c-.115.715.173 1.45.768 1.894a1.904 1.904 0 002.016.135L64 95.178l27.59 14.59c.269.155.576.232.883.232a1.98 1.98 0 001.133-.367 1.974 1.974 0 00.768-1.894l-5.28-30.918 22.33-21.893c.518-.522.71-1.276.48-1.99z" fill-rule="nonzero"/> </svg>

For supporting browsers, this code means our star-shaped SVG favicon will change its fill color from black to white when dark mode is activated. Pretty neat!

Other media queries

Dark mode support got me thinking: if SVGs can support prefers-color-scheme, what other things can we do with them? While the support for Level 5 Media Queries may not be there yet, here’s some ideas to consider:

Mockup of four SVG favicon treatments. The first treatment is a pink star with a tab title of, “SVG Favicon.” The second treatment is a hot pink star with a tab title of, “Light Level SVG Favicon.” The third treatment is a light pink star with a tab title of, “Inverted Colors SVG Favicon.” The fourth treatment is a black pink star with a tab title of, “High Contrast Mode SVG Favicon.” The tabs are screen captures from Microsoft Edge, with the browser chrome updating to match each specialized mode.
A mockup of how these media query-based adjustments could work.

Keep it crisp

Another important aspect of good favicon design is making sure they look good in the small browser tab area. The secret to this is making the paths of the vector image line up to the pixel grid, the guide a computer uses to turn SVG math into the bitmap we see on a screen. 

Here’s a simplified example using a square shape:

A crisp orange square on a white background. There is also a faint grid of gray horizontal and vertical lines that represent the pixel grid. Screenshot from Figma.

When the vector points of the square align to the pixel grid of the artboard, the antialiasing effect a computer uses to smooth out the shapes isn’t needed. When the vector points aren’t aligned, we get a “smearing” effect:

A blurred orange square on a white background. There is also a faint grid of gray horizontal and vertical lines that represent the pixel grid. Screenshot from Figma.

A vector point’s position can be adjusted on the pixel grid by using a vector editing program such as Figma, Sketch, Inkscape, or Illustrator. These programs export SVGs as well. To adjust a vector point’s location, select each node with a precision selection tool and drag it into position.

Some more complicated icons may need to be simplified, in order to look good at such a small size. If you’re looking for a good primer on this, Jeremy Frank wrote a really good two-part article over at Vidget.

Go the extra mile

In addition to favicons, there are a bunch of different (and unfortunately proprietary) ways to use icons to enhance its experience. These include things like the aforementioned pinned tab icon for Safari¹, chat app unfurls, a pinned Windows start menu tile, social media previews, and homescreen launchers.

If you’re looking for a great place to get started with these kinds of enhancements, I really like realfavicongenerator.net.

Icon output from realfavicongenerator.net arranged in a grid using CSS-Trick’s logo. There are two rows of five icons: android-chrome-192x192.png, android-chrome-384x384.png, apple-touch-icon.png, favicon-16x16.png, favicon-32x32.png, mstile-150x150.png, safari-pinned-tab.svg, favicon.ico, browserconfig.xml, and site.webmanifest.
It’s a lot, but it guarantees robust support.

A funny thing about the history of the favicon: Internet Explorer was the first browser to support them and they were snuck in at the 11th hour by a developer named Bharat Shyam:

As the story goes, late one night, Shyam was working on his new favicon feature. He called over junior project manager Ray Sun to take a look.

Shyam commented, “This is good, right? Check it in?”, requesting permission to check the code into the Internet Explorer codebase so it could be released in the next version. Sun didn’t think too much of it, the feature was cool and would clearly give IE an edge. So he told Shyam to go ahead and add it. And just like that, the favicon made its way into Internet Explorer 5, which would go on to become one of the largest browser releases the web has ever seen.

The next day, Sun was reprimanded by his manager for letting the feature get by so quickly. As it turns out, Shyam had specifically waited until later in the day, knowing that a less experienced Program Manager would give him a pass. But by then, the code had been merged in. Incidentally, you’d be surprised just how many relatively major browser features have snuck their way into releases like this.

From How We Got the Favicon by Jay Hoffmann

I’m happy to see the platform throw a little love at favicons. They’ve long been one of my favorite little design details, and I’m excited that they’re becoming more reactive to user’s needs. If you have a moment, why not sneak a SVG favicon into your project the same way Bharat Shyam did way back in 1999. 


¹ I haven’t been able to determine if Safari is going to implement SVG favicon support, but I hope they do. Has anyone heard anything?

The post SVG, Favicons, and All the Fun Things We Can Do With Them appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

15 Things to Improve Your Website Accessibility

This is a really great list from Bruce. There is a lot of directly actionable stuff here. Send it around to your team and make it something that you all go through together.

Here’s a little one that prodded me to finally fix…

Most screen readers allow the user to quickly see a list of links on a page [..] However, if every link has text saying “Click here” or “Read more”, with nothing else to distinguish them, this is useless. The easiest way to solve this is simply to write unique link text, but if that isn’t possible, you can over-ride the link text for assistive technology by using a unique aria-label attribute on each link.

I had links like that right here on CSS-Tricks. Some of them are automatically created by WordPress itself, not something I hand-coded into a template. When you show the_excerpt of a post, you get a “read more” link automatically, and aside from getting your hands dirty with some filters, you don’t have that much control over it.

DevTools showing the DOM of a "read more" link with no context.

Fortunately, I already use a cool plugin called Advanced Excerpt. I poked into the settings to see if I could do something about injecting the post title in there somehow. Lookie lookie:

A setting for Advanced Excerpt that does screen reader links.

That screen-reader-text class is exactly what I already used for that kind of stuff, so it was a one-click fix!

Much nicer DOM now for those links:

Direct Link to ArticlePermalink

The post 15 Things to Improve Your Website Accessibility appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

Making Things Better: Redefining the Technical Possibilities of CSS

(This is a sponsored post.)

Robin recently lamented the common complaint that CSS is frustrating. There are misconceptions about what it is and what it does. There are debates about what kind of language it is. There are even different views on where it should be written.

Rachel Andrew has a new talk from An Event Apart DC 2019 available that walks us back; back to the roots of the issues we used to have with CSS and the “hacks” we used to overcome them. CSS has changed a lot over the past few years and, while those changes have felt complex and confusing at times, they are designed to solve what we have always wanted CSS to do.

The full hour it takes to watch the talk is well worth the time. Here are a few nuggets that stood out. First off, some de-bunking of common CSS complaints:

  • You never know how tall anything is on the web. Floats never solved this because they only bring things next to each other instead of knowing about the items around them. New layout methods, including CSS Grid and Flexbox, actually look at our elements and help them behave consistently.
  • Flexbox is weird and unintuitive. It’s not the layout method you might think it is. If we view it as a way to line things up next to each other, it’s going to feel weird and behavior weirdly as well. But if we see it for what it is – a method that looks at differently sized elements and returns the most logical layout – it starts to make sense. It assigns space, rather than squishing things into a box.

Rachel continues by giving us a peek into the future of what CSS wants to do for us:

  • CSS wants to avoid data loss. New alignment keywords like safe and unsafe will give us extra control to define whether we want CSS to aggressively avoid content that’s unintentionally hidden or allow it to happen.
.container {   display: flex;   flex-direction: column;   /* Please center as long as it doesn't result in overflow */   align-items: safe center; }
  • CSS wants to help us get real with overflow. Themin-content and max-content keywords make it possible to create boxes that are wide enough for the content but not wider, and boxes that are as big as the content can be.
.container {   width: min-content; /* Allow wrapping */ }
  • CSS wants to lay things out logically. The web is not left-to-right. Grid and Flexbox quietly introduced a way of thinking start-to-end that is direction agnostic. That has brought about a new specification for Logical Properties and Values.
  • CSS wants to make content more portable. CSS Regions let us flow content from one element into another. While it’s probably a flawed comparison, it’s sorta like the pipes in old school Mario Bros. games where jumping in one pipe at one location will plop your character out of another pipe in another location… but we get to define those sources ourselves and without angry plants trying to eat us along the way.

Anyway, these are merely scratching the surface of what Rachel covers in her talk. It’s a good reminder that An Event Apart has an entire library of valuable talks from amazing speakers and that attending an AEA event is an invaluable experience worth checking out. Rachel’s talk was from last year’s Washington D.C. event and, as it turns out, the very next event is taking place there this April 13-15. If you can’t make that one, there are several others throughout the year across the United States.

Oh, and of course we have a discount code for you! Use AEACP for $ 100 off any show.

Direct Link to ArticlePermalink

The post Making Things Better: Redefining the Technical Possibilities of CSS appeared first on CSS-Tricks.

CSS-Tricks

, , , , ,
[Top]

Things you can do with a browser in 2020

I edit a good amount of technical articles about the web, and there is a tendency for authors to be super broad in their opening sentence, like “What we’re able to do on the web has expanded greatly over the years.”

I tend to remove stuff like that because it usually doesn’t serve the article well, even though I understand the sentiment.

Just look at Luigi De Rosa’s list here. I’d bet a lot of you didn’t know the browser could do all that stuff — push notifications! Native sharing menus! Picture-in-picture!

It’s mostly JavaScript stuff, a little CSS, and notably absent: anything in HTML.

Direct Link to ArticlePermalink

The post Things you can do with a browser in 2020 appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

“All these things are quite easy to do, they just need somebody to sit down and just go through the website”

I saw a video posted on Twitter from Channel 5 News in the UK (I have no idea what the credibility of them is, it’s an ocean away from me) with anchor Claudia Liza asking Glen Turner and Kristina Barrick questions about website accessibility.

Apparently, they often post videos with captions, but this particular video doesn’t (ironically). So, I’ve transcribed it here as I found them pretty well-spoken.

[Claudia Liza]: … you do have a visual impairment. How does that make it difficult for you to shop online?

[Glen Turner]: Well, I use various special features on my devices to shop online to make it easier. So, I enlarge the text, I’ll invert the colors to make the background dark so that I don’t have glare. I will zoom in on pictures, I will use speech to read things to me because it’s too difficult sometimes. But sometimes websites and apps aren’t designed in a way that is compatible with that. So sometimes the text will be poorly contrasted so you’ll have things like brown on black, or red on black, or yellow on white, something like that. Or the menu system won’t be very easy to navigate, or images won’t have descriptions for the visually impaired because images can have descriptions embedded that a speech reader will read back to them. So all these various factors make it difficult or impossible to shop on certain websites.

[Claudia Liza]: What do you need retailers to do? How do they need to change their technology on their websites and apps to make it easier?

It’s quite easy to do a lot of these things, really. Check the colors on your website. Make sure you’ve got light against dark and there is a very clear distinctive contrast. Make sure there are descriptions for the visually impaired. Make sure there are captions on videos for the hearing impaired. Make sure your menus are easy to navigate and make it easy to get around. All these things are quite easy to do, they just need somebody to sit down and just go through the website and check that it’s all right and consult disabled people as well. Ideally, you’ve got disabled people in your organization you employ, but consult the wider disabled community as well. There is loads of us online there is loads of us spread all over the country. There is 14 million of us you can talk to, so come and talk to us and say, “You know, is our website accessible for you? What can we do to improve it?” Then act on it when we give you our advice.

[Claudia Liza]: It makes sense doesn’t it, Glen? It sounds so simple. But Christina, it is a bit tricky for retailers. Why is that? What do other people with disabilities tell you?

So, we hear about content on websites being confusing in the way it’s written. There’s lots of information online about how to make an accessible website. There’s a global minimum legal standard called WCAG and there’s lot of resources online. Scope has their own which has loads of information on how to make your website accessible.

I think the problem really is generally lack of awareness. It doesn’t get spoken about a lot. I think that disabled consumers – there’s not a lot of places to complain. Sometimes they’ll go on a website and there isn’t even a way to contact that business to tell them that their website isn’t accessible. So what Scope is trying to do is raise the voices of disabled people. We have crowdsourced a lot of people’s feedback on where they experience inaccessible websites. We’re raising that profile and trying to get businesses to change.

[Claudia Liza]: So is it legal when retails aren’t making their websites accessible?

Yeah, so, under the Equality Act 2010, it’s not legal to create an inaccessible website, but what we’ve found is that government isn’t generally enforcing that as a law.

[Claudia Liza]: Glenn, do you feel confident that one day you’ll be able to buy whatever you want online?

I would certainly like to think that would be the case. As I say, you raise enough awareness and get the message out there and alert business to the fact that there is a huge consumer market among the disabled community, and we’ve got a 274 billion pound expenditure a year that we can give to them. Then if they are aware of that, then yeah, hopefully they will open their doors to us and let us spend our money with them.

The post “All these things are quite easy to do, they just need somebody to sit down and just go through the website” appeared first on CSS-Tricks.

CSS-Tricks

, , , , , , , , , , ,
[Top]

Some Things You Oughta Know When Working with Viewport Units

David Chanin has a quickie article summarizing a problem with setting an element’s height to 100vh in mobile browsers and then also positioning something on the bottom of that.

Summarized in this graphic:

The trouble is that Chrome isn’t taking the address bar (browser chrome) into account when it’s revealed which cuts off the element short, forcing the bottom of the element past the bottom of the actual viewport.

<div class="full-page-element">   <button>Button</button> </div>
.full-page-element {   height: 100vh;   position: relative; }  .full-page-element button {   position: absolute;   bottom: 10px;   left: 10px; }

You’d expect that button in the graphic to be visible (assuming this element is at the top of the page and you haven’t scrolled) since it’s along the bottom edge of a 100vh element. But it’s actually hidden behind the browser chrome in mobile browsers, including iOS Safari or Android Chrome.

I use this a lot:

body {   height: 100vh; /* Nice to not have to think about the HTML element parent   margin: 0; }

It’s just a quick way to make sure the body is full height without involving any other elements. I’m usually doing that on pretty low-stakes demo type stuff, but I’m told even that is a little problematic because you might experience jumpiness as browser chrome appears and disappears, or things may not be quite as centered as you’d expect.

You’d think you could do body { height: 100% }, but there’s a gotcha there as well. The body is a child of <html> which is only as tall as the content it contains, just like any other element.

If you need the body to be full height, you have to deal with the HTML element as well:

html, body {    height: 100%; }

…which isn’t that big of a deal and has reliable cross-browser consistency.

It’s the positioning things along the bottom edge that is tricky. It is problematic because of position: absolute; within the “full height” (often taller-than-visible) container.

If you are trying to place something like a fixed navigation bar at the bottom of the screen, you’d probably do that with position: fixed; bottom: 0; and that seems to work fine. The browser chrome pushes it up and down as you’d expect (video).

Horizontal viewport units are just as weird and problematic due to another bit of browser UI: scrollbars. If a browser window has a visible scrollbar, that scrollbar will usually eat into the visual space although a value of 100vw is calculated as if the scrollbar wasn’t there. In other words, 100vw will cause horizontal scrolling in a way you probably wouldn’t expect.

See the Pen
CSS Vars for viewport width minus scrollbar
by Shaw (@shshaw)
on CodePen.

Our last CSS wishlist roundup mentioned better viewport unit handling a number of times, so developers are clearly pretty interested in having better solutions for these things. I’m not sure what that would mean for web compatibility though, because changing the way they work might break all the workarounds we’ve used that are surely still out in the wild.

The post Some Things You Oughta Know When Working with Viewport Units appeared first on CSS-Tricks.

CSS-Tricks

, , , , , ,
[Top]

Naming things to improve accessibility

I like the this wrap-up statement from Hidde de Vries:

In modern browsers, our markup becomes an accessibility tree that ultimately informs what our interface looks like to assistive technologies. It doesn’t matter as much whether you’ve written this markup:

  • in a .html file
  • in Twig, Handlebars or Nunjucks
  • as the <template> in a Vue Single File Component
  • exported in the JSX of your React component
  • outputted by a weird legacy CMS

It is which markup that determines if your site is pleasurable to experience for AT users. In short: it’s the markup that matters

As a front-end developer, you’ll find yourself writing markup in lots of different places with lots of different technologies. I think it behooves you think of how best to write it regardless of where and how.

Direct Link to ArticlePermalink

The post Naming things to improve accessibility appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

Little Things That Tickled My Brain from An Event Apart Seattle

I had so much fun at An Event Apart Seattle! There is something nice about sitting back and basking in the messages from a variety of such super smart people.

I didn’t take comprehensive notes of each talk, but I did jot down little moments that flickered my brain. I’ll post them here! Blogging is fun! Again, note that these moments weren’t necessarily the main point of the speaker’s presentation or reflective of the whole journey of the topic — they are little micro-memorable moments that stuck out to me.


Jeffrey Zeldman brought up the reading apps Instapaper (still around!) and Readability (not around… but the technology is what seeped into native browser tech). He called them a vanguard (cool word!) meaning they were warning us that our practices were pushing users away. This turned out to be rather true, as they still exist and are now joined by new technologies, like AMP and native reader mode, which are fighting the same problems.


Margot Bloomstein made a point about inconsistency eroding our ability to evaluate and build trust. Certainly applicable to websites, but also to a certain President of the United States.

President Flip Flops

Sarah Parmenter shared a powerful moment where she, through the power of email, reached out to Bloom and Wild, a flower mail delivery service, to tell them a certain type of email they were sending she found to be, however unintentionally, very insensitive. Sarah was going to use this as an example anyway, but the day before, Bloom and Wild actually took her advice and implemented a specialized opt-out system.

This not only made Sarah happy that a company could actually change their systems to be more sensitive to their customers, but it made a whole ton of people happy, as evidenced by an outpouring of positive tweets after it happened. Turns out your customers like it when you, ya know, think of them.


Eric Meyer covered one of the more inexplicable things about pseudo-elements: if you content: url(/icons/icon.png); you literally can’t control the width/height. There are ways around it, notably by using a background image instead, but it is a bit baffling that there is a way to add an image to a page with no possible way to resize it.

Literally, the entire talk was about pseudo-elements, which I found kinda awesome as I did that same thing eight years ago. If you’re looking for some nostalgia (and are OK with some cringe-y moments), here’s the PDF.

Eric also showed a demo that included a really neat effect that looks like a border going from thick to thin to thick again, which isn’t really something easily done on the web. He used a pseudo, but here it is as an <hr> element:

See the Pen
CSS Thick-Thin-Thick Line
by Chris Coyier (@chriscoyier)
on CodePen.


Rachel Andrew had an interesting way of talking about flexbox. To paraphrase:

Flexbox isn’t the layout method you think it is. Flexbox looks at some disparate things and returns some kind of reasonable layout. Now that grid is here it’s a lot more common to use that to be more much explict about what we are doing with layout. Not that flexbox isn’t extremely useful.

Rachel regularly pointed out that we don’t know how tall things are in web design, which is just so, so true. It’s always been true. The earlier we embrace that, the better off we’ll be. So much of our job is dealing with overflow.

Rachel brought up a concept that was new to me, in the sense that it has an official name. The concept is “data loss” through CSS. For example, aligning something a certain way might cause some content to become visually hidden and totally unreachable. Imagine some boxes like this, set in flexbox, with center alignment:

No “data loss” there because we can read everything. But let’s say we have more content in some of them. We can never know heights!

If that element was along the top of a page, for example, no scrollbar will be triggered because it’s opposite the scroll direction. We’d have “data loss” of that text:

We now alignment keywords that help with this. Like, we can still attempt to center, but we can save ourselves by using safe center (unsafe center being the default):

Rachel also mentioned overlapping as a thing that grid does better. Here’s a kinda bad recreation of what she showed:

See the Pen
Overlapping Figure with CSS Grid
by Chris Coyier (@chriscoyier)
on CodePen.

I was kinda hoping to be able to do that without being as explicit as I am being there, but that’s as close as I came.


Jen Simmons showed us a ton of different scenarios involving both grid and flexbox. She made a very clear point that a grid item can be a flexbox container (and vice versa).

Perhaps the most memorable part is how honest Jen was about how we arrive at the layouts were shooting for. It’s a ton of playing with the possible values and employing a little trial and error. Happy accidents abound! But there is a lot to know about the different sizing values and placement possibilties of grid, so the more you know the more you can play. While playing, the layout stuff in Firefox DevTools is your best bet.

Flexbox with gap is gonna be sweet.

There was a funny moment in Una Kravets’ talk about brainstorming the worst possible ideas.

The idea is that even though brainstorm sessions are supposed to be judgment-free, they never are. Bad ideas are meant to be bad, so the worst you can do is have a good idea. Even better, starting with good ideas is problematic in that it’s easy to get attached to an idea too early, whereas bad ideas allow more freedom to jump through ideation space and land on better ideas.


Scott Jehl mentioned a fascinating idea where you can get the benefits of inlining code and caching files at the same time. That’s useful for stuff we’ve gotten used to seeing inlined, like critical CSS. But you know what else is awesome to inline? SVG icon systems. Scott covered the idea in his talk, but I wanted to see if it I could give it a crack myself.

The idea is that a fresh page visit inlines the icons, but also tosses them in cache. Then other pages can <svg><use> them out of the cache.

Here’s my demo page. It’s not really production-ready. For example, you’d probably want to do another pass where you Ajax for the icons and inject them by replacing the <use> so that everywhere is actually using inline <svg> the same way. Plus, a server-side system would be ideal to display them either way depending on whether the cache is present or not.


Jeremy Keith mentioned the incredible prime number shitting bear, which is, as you might suspect, computationally expensive. He mentioned it in the context of web workers, which is essentially JavaScript that runs in a separate thread, so it won’t/can’t slow down the operation of the current page. I see that same idea has crossed other people’s minds.


I’m sad that I didn’t get to see every single talk because I know they were all amazing. There are plenty of upcoming shows with some of the same folks!

The post Little Things That Tickled My Brain from An Event Apart Seattle appeared first on CSS-Tricks.

CSS-Tricks

, , , , , , ,
[Top]