Keyboard-Only Focus Styles

Like Eric Bailey says, if it’s interactive, it needs a focus style. Perhaps your best bet? Don’t remove the dang outlines that focusable elements have by default. If you’re going to rock a button { outline: 0; }, for example, then you’d better do a button:focus { /* something else very obvious visually */ }. I handled a ticket just today where a missing focus style was harming a user who relies on visual focus styles to navigate the web.

But those focus styles are most useful when tabbing or otherwise navigating with a keyboard, and less so when they are triggered by a mouse click. Now we’ve got :focus-visible! Nelo writes:

TLDR; :focus-visible is the keyboard-only version of :focus.

Also, the W3C proposal mentions that :focus-visible should be preferred over :focus except on elements that expect a keyboard input (e.g. text field, contenteditable).

(Also see his article for a good demo on why mouse clicking and focus styles can be at odds, beyond a general dislike of fuzzy blue outlines.)

Browser support for :focus-visible is pretty rough:

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 Opera Firefox IE Edge Safari
No No 4* No No No

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
No No No No No 62*

But it does have Firefox support, and as Lea Verou says:

… once Chrome ships its implementation it will explode in a matter of 1-2 months.

That’s generally how things go these days. Once two major browsers have support — and one of them is Chrome — that’s a huge enough slice of the web that can start using it. Especially when it can be done as safely as this property.

Safely, as in, there is an official polyfill, meaning you can nuke default focus styles and just use :focus-visible styles:

/* Remove outline for non-keyboard :focus */
*:focus:not(.focus-visible) { outline: none;
} /* Optional: Customize .focus-visible */
.focus-visible { outline: lightgreen solid 2px;
}

But, as Patrick H. Lauke documented, you can do it even without the polyfill, using careful selector usage and un-doing styles as needed:

button:focus { /* Some exciting button focus styles */ }
button:focus:not(:focus-visible) { /* Undo all the above focused button styles if the button has focus but the browser wouldn't normally show default focus styles */
}
button:focus-visible { /* Some even *more* exciting button focus styles */ }

Seems like a nice improvement for the web.

The post Keyboard-Only Focus Styles appeared first on CSS-Tricks.

Nested Links

The other day I posted an image, quite literally as a thought exercise, about how you might accomplish “nested” links. That is, a big container that is linked to one URL that contains a smaller container or text link inside of it that goes to another URL. That’s harder than it might seem at first glance. The main reason being that…

<!-- this is invalid and won't render as expected -->
<a href="#one"> Outside <a href="#two"> Inside </a>
</a>

Eric Meyer once called for more flexible linking, but even that doesn’t quite handle a situation where one link is nested inside another.

Here’s what happens with that HTML, by the way:

The nested link gets kicked out.

My first inclination would be to simply not nest the links in the markup, but make them appear nested visually. Some folks replied to the tweet, including Nathan Smith, who shared that same thought: have a relatively positioned parent element and absolutely position both links. The larger one could fill up the whole area and the smaller one could sit on top of it.

See the Pen “Nested” links by Nathan Smith (@nathansmith) on CodePen.

It’s finicky, as you’ll need magic numbers to some degree to handle the spacing and variable content.

My second inclination would be to deal with it in JavaScript.

<div onclick="window.location='https://codepen.io'" style="cursor: pointer;" tab-index="1"
> Outside <a href="https://css-tricks.com"> Inside </a>
</div>

I have literally no idea how kosher that is from an accessibility perspective. It looks gross to me so I’m just going to assume it’s bad news.

Speaking of accessibility, Heydon Pickering has a whole article about card components which is a popular design pattern where this situation often comes up. His solution is to have a relatively positioned parent element, then a normally-placed and functional main link. That first link has an absolutely positioned pseudo-element on it covering the entire card. Any sub-links are relatively positioned and come after the initial link, so they’d sit on top of the first link by way of z-index.

Demo with author link.

And speaking of stacking pseudos, that’s the approach Sean Curtis uses here:

See the Pen Pretend nested links by Sean Curtis (@seancurtis) on CodePen.

Other solutions in the “crafty” territory might be:

  • Using a <form> element where the action attribute acts as a link.
  • Using an <object> element to wrap the inner link.

Sara Soueidan responded with her own post!

I had the same requirement a couple of years ago when I was building the front-end foundation for Smashing Magazine. So I thought I’d write my response to Chris’s thread out in the form of a blog post.

Sara has written about this with much more detail and care than I have here, so definitely check that out. It looks like both she and Heydon have landed on nearly the same solution, with the pseudo-element cover that contains sub-links poking above it as needed.

Have you ever done it another way? Plenty of UX and a11y to think abbout!

The post Nested Links appeared first on CSS-Tricks.

HTML elements, unite! The Voltron-like powers of combining elements.

Guides, resources and discussions about Semantic HTML are often focused around specific elements, like a heading, or a sectioning element, or a list. It’s not often that we talk specifically about how we can combine HTML elements to increase their effectiveness.

Normally, when we introduce HTML, we talk about how it is used to apply meaning to content in a document, and we do this by using examples like:

  • “Is it a paragraph?”
  • “Is it a heading?”
  • “Is it a numbered list”
  • “Is it a button”

We use these examples because they are easy to understand — it’s a single piece or chunk of the same content that needs to be represented in a particular way. This is useful, but it only scratches the surface of how we can use and combine elements to provide more context and meaning.

You remember Voltron, right? Each member of the Voltron force was powerful in their own right, but it was when they combined together to form a towering figure that their mighty powers became unstoppable.

The same is true of HTML elements. I have a few favorite combinations that I’ll take you through. They may seem obscure, but you’d be surprised at how often they come up when you take the time to think outside of divs and spans.

Abbreviations and Definitions

<abbr> and <dfn> are two of my favorite HTML elements. I particularly like them because they work really well together.

You can combine the abbreviation and definition elements to allow browsers, search bots, and other technologies to recognize that something is being defined and that the acronym is associated to that phrase.

<p> The <dfn><abbr title="International Good Dog Association">IGDA</abbr></dfn> is an international, not-for-profit organization responsible for determining that all dogs are good.
</p>

In the above example, I’m defining that the acronym “IGDA” as “International Good Dogs Association.” I do this by wrapping the acronym in an <abbr> element with a title attribute defining the full name. By adding the <dfn> element around the abbreviation, it indicates that the surrounding paragraph defines the term “International Good Dogs Association.”

The <abbr> element is useful because it can tell screen readers what they should read, while also providing a useful visual representation in the form of a tooltip explaining what the abbreviation is.

Visual representation of <abbr> and <dfn>.

Keyboard, Sample and Variable

If you haven’t heard of these elements, then get ready to have your socks blown off, because they are awesome.

First up, the <kbd> element is used to represent text for a textual user input (e.g. from a keyboard). You can also nest multiple <kbd> elements to represent multiple keystrokes. I love this because, as developers, we find ourselves (hopefully) writing documentation, blog posts, and guides on a regular basis and HTML provides us with native ways to represent this content straight out of the box!

If I wanted to tell someone how you copy and paste with the keyboard, I could mark it up like the code below.

<p>I like to <kbd><kbd>Ctrl</kbd>+<kbd>C</kbd></kbd> and <kbd><kbd>Ctrl</kbd>+<kbd>V</kbd></kbd> a lot.</p>

It looks a bit nuts but the above code, when rendered, looks like the following without any styling applied to it. If you are wondering why kbd is nested inside another kbd element, what this does is specify that the key or input is part of a larger input. Even more combined superpowers!

See the Pen rZpNPy by CSS-Tricks (@css-tricks) on CodePen.

You can further target the <kbd> elements with CSS to make it look more like little keyboard controls. (Note: Browsers tend to render this by default with a monospace font.)

See the Pen gdoOqE by CSS-Tricks (@css-tricks) on CodePen.

If you’re wondering what the difference is between using <kbd> versus a span, I believe it comes down to information. I will repeat this sentiment a lot: we do not know how someone is going to consume our HTML, so give your content it’s best chance by representing it in the most meaningful and contextual way possible. If you are still not on board, then please go read my post about HTML as told by TypeScript.

The <samp> element is really cool because you can nest it inside the <kbd> element and vice versa. WHAT? I know, so versatile! Let’s have a look at some examples from MDN.

The following code is an example of nesting a <samp> element inside a <kbd> element. This is used to mark up content that represents input based on the text displayed by the system (e.g. button names).

<p>To save the image file, select <kbd><kbd><samp>File</samp></kbd> - <kbd><samp>Save as...</samp></kbd></kbd>.
</p>

See the Pen YOYzbJ by CSS-Tricks (@css-tricks) on CodePen.

In the above code, we define our keyboard shortcuts the same as our previous example, but we also determine that the menu and menu item names (contained within both <kbd> and <samp>) are an input selected from something displayed by the system, e.g. a dialog or widget.

In other words, this piece of text is a message from the system which has some user inputs that you need to follow (like File and Save as…).

Whereas, when we nest <kbd> inside <samp>, we determine that the input has been echoed back to the user by the system.

<p><samp>yarn start:theproject does not exist, did you mean:</p>
<blockquote><samp><kbd>yarn start:the-project</kbd></samp></blockquote>

Finally, the <var> element! This is used to mark up the name of a variable in math or programming, for example:

<var>E</var> = <var>m</var><var>c</var><sup>2</sup>.
<samp>Error: <var>console<var> is undefined.</samp>

Here you can start to see how combining <var> with other elements like <pre>, <code>, <kbd> or <samp> starts to make your content’s markup more explicit by adding more context. Anything that interprets your HTML markup can start to derive more meaning from the elements you are using rather than just assuming that it’s all standard text.

If you put this content in a paragraph with some spans, there is no way for technology to distinguish this from any other old text on your page. You don’t have to resort to <span> or a <div> to represent this content because HTML already provides us with more semantically accurate elements we can use. HTML is not just about presentation; it’s about meaning. Various technologies outside of visual rendering engines rely on this meaning to make decisions about how to communicate our content in the most meaningful way (e.g. screen readers, text to voice, reading apps, bots, or the next big thing in the future).

Figures

Figures (<figure>) are a great example of a power combination element. Unfortunately, I think it is widely misused and under appreciated (much like <aside>, which I could talk about for hours). The obvious combination you are probably familiar with is using <figure> and <figcaption> together. We often use this duo to represent graphical content like images, illustrations and diagrams — but it can also be used for things like code, poems and quotes!

Because a figure is so flexible in what kind of content it represents, there are a bunch of different HTML elements you can use within a figure to provide more context around the type of content you are putting in your page.

Figcaption

The <figure> element is often seen with an optional <figcaption> which represents a caption or legend for a figure. It should be the first child or last child of the <figure> element. You can also use any flow content (e.g. paragraphs, headings, etc.) in the <figcaption> to provide more context and you can have multiple images inside a <figure> represented by a single <figcaption>.

<figure> <img src="jello.jpg" alt="Golden Retriever Puppy" /> <figcaption>Jello the Golden Retriever enjoying being carried home.</figcaption>
</figure>

Preformatted Text

The <pre> element is used to display preformatted text or code and is usually rendered using a monospace font. While <pre> can be used on its own, it can also be combined with <figure> and <figcaption>. By doing this, the content inside the <pre> element becomes more accessible to assistive technologies, like screen readers, since it allows us to use <figcaption> as a label for the text or code.

We can go even further by combining the <pre> and <code> elements to identify the pre- formatted content as code.

See the Pen QVaWVW by CSS-Tricks (@css-tricks) on CodePen.

Because <code> is considered flow content, it can also be used inside a <figcaption> to mark up inline references to code (i.e. a single phrase or line).

Cite and Blockquote

Quotations are something I use a lot and it honestly didn’t occur to me it could be used as part of a figure. But it still makes sense to use cite or quotation if the content they contain is relevant to the overall content, even if it is not part of the main document flow.

I like the example of using a figure for poems, mainly so I could share the amazing poem I wrote about my dog. Here I use the <cite> element inside the <figcaption>:

<figure> <p> Jello - A little fluffy dog. Hello! Squishy Jello - you little fluffy fellow. BOUNCY yellow Jello. A very mellow fellow. EATING MY MARSHMALLOW. </p> <figcaption><cite>Eating my Marshmallow by Mandy Michael</figcaption>
</figure>

It’s easy to fall into the trap of thinking that the figure element is just for images or image-like content, but you can use it for content like audio, video, charts, poems, quotations or even tables of statistics. Because the element is so versatile you can combine it with so many other elements to provide more and more context about the figure for assistive technology, browsers, and other technologies consuming your website.

Wrapping Up

These are just some of the ways HTML elements can be combined for better context. HTML elements are indeed useful and valuable on their own when used as isolated pieces — and using them this way is a good first step. But, like Voltron, when you combine HTML elements together, the individual pieces form a greater whole and gain much more meaning and power. It’s important that we don’t think of HTML as individual pieces of code, but parts of a whole because HTML is really a mass of totally amazing combinations.

You can combine and use HTML elements in any number of ways to best represent your content. Don’t simply stick to the same old things you know; take the time to explore HTML and learn about all it has to offer. Like any language, we should make the most of it and use it to its full potential.

The more accurate you are in marking up your content, the better that content will be represented across technologies, and the more prepared it will be for any anything else that is used to interpret your HTML in the future.

So, go forth and HTML elements, unite!


Resources

In my opinion, the best resource for learning and understanding how to use HTML (outside of the spec itself) is the MDN Web Docs. It lists all the HTML elements you could ever need.

The following are among the elements covered in this post:

  • <abbr>
  • <cite>
  • <code>
  • <dfn>
  • <figure>
  • <figcaption>
  • <kbd>
  • <samp>
  • <var>

If you are a TypeScript fan and don’t understand why Semantic HTML is important, I wrote this post just for you: Understanding why Semantic HTML is important as told by TypeScript.

The post HTML elements, unite! The Voltron-like powers of combining elements. appeared first on CSS-Tricks.

Empower Through Web Development

As a person with a disability, I appreciate the web and modern-day computing for their many affordances. The web is a great place to work and share and connect. You can make a living, build your dream, and speak your mind.

It’s not easy, though. Beginners struggling with the box model often take to Google in search of guidance (and end up at this very website). More seasoned developers find themselves hopping from framework to framework trying to keep up. We experience plenty of late nights, console logs, and rage quits.

It’s in times like these that I like to remember why I’m doing this thing. And that’s because of the magic of creating. Making websites is empowering because it allows you to shape the world—in ways big and small, public and personal. It’s especially powerful for people with disabilities, who gain influence on the tech that they rely on. And, hey, you can do web stuff for fun and profit.

The magic of craft

I knew I wanted to be a person who makes websites the first time I ever wrote HTML, hit reload, and saw my changes. I felt the power coursing through my veins as I FTP-ed my site to my shiny new web server under my very own domain name. My mind jumped into the future, imagining my vast web empire.

I never got around to making an empire, but I had something most of my friends didn’t—a personal homepage. I don’t care how ugly or weird they might be, I think everyone should have a homepage they made for themselves. I love going to personal web homes—you know, just to check out what they’ve done with the place.

I love that the web can be this artisanal craft. My disability (spinal muscular atrophy) precludes me from practicing many crafts one might pick up. And yet as a child, I watched as my grandfather would take to his workshop and emerge with all sorts of wooden inventions—mostly toys for me, of course. I came to appreciate the focus and dedication he put into it. Regardless of what terrible things were going on in life, he could escape into this wonderful world of creation, systems, and problem-solving. I wanted that too. Years later, I found my craft. What with its quirky boxes, holy wars, and documentation.

But I loved it. I couldn’t get enough. And finally I realized… this can be my life’s work. I can get paid to make things on the internet.

But first, some not great facts about employment

Employment levels of people with disabilities are low, and those who are employed tend to be in low-paying occupations.

— U.S. Department of Labor

The U.S. Department of Labor (DOL) keeps statistics on employment levels for people with disabilities and, let me tell you, they kind of suck. The DOL goes on to say that only a third of working-age people with disabilities were employed, on average, in the 2010-2012 period. In contrast, over two-thirds of people without disabilities were employed in the same period.

This problem affected me personally as I struggled to get a job after college. Fortunately, the web is a great tool for breaking down barriers. With its vast learning resources, free and open source software, and plethora of ways to connect and share, the web makes possible all sorts of employment opportunities. I’m now a designer/developer at Mad Genius and loving it.

I urge anyone—disabled or not—who finds themselves with limited access to more conventional jobs to consider working on the web. Whether you draw, write, design, or code, there’s something here for you. This big web we’re building for everyone should be built by everyone.

We need that thing that you’re going to build

Last fall, I launched A Fine Start, a web service and browser extension for turning your new tab page into a minimal list of links. Some people saw it when Chris mentioned it in an article and it picked up quite a few new users. But what those users don’t know is that A Fine Start began life as an assistive technology.

Because of my extremely weak muscles, I type using a highly customized on-screen keyboard. It’s doable, but tedious, so I use the mouse method of getting things done wherever possible. I could open a new tab and start typing, but I would rather click. As a result, I made Start, a one-file tool that allowed me to save lists of links and get at them quickly when set as my new tab page—no keyboard necessary.

It was fantastic and I realized I needed Start on every computer I used, but I had no way of getting my bookmarks on another device without sticking them in a text file in Dropbox. So, last year, I wrote a backend service, polished the design, made a Chrome extension, and threw my baby out of the nest to see if it would fly. We’ll see.

The point is, there’s something the world needs, waiting to be built. And you are the only one who can build it. The recipe is mediocre ideas, showing up, and persistence. The web needs your perspective. Load up on your caffeinated beverage of choice, roll up your sleeves, and practice your craft. You’ve got the power. Now use it.

The post Empower Through Web Development appeared first on CSS-Tricks.

How to Disable Links

The topic of disabling links popped up at my work the other day. Somehow, a “disabled” anchor style was added to our typography styles last year when I wasn’t looking. There is a problem though: there is no real way to disable an <a> link (with a valid href attribute) in HTML. Not to mention, why would you even want to? Links are the basis of the web.

At a certain point, it looked like my co-workers were not going to accept this fact, so I started thinking of how this could be accomplished. Knowing that it would take a lot, I wanted to prove that it was not worth the effort and code to support such an unconventional interaction, but I feared that by showing it could be done they would ignore all my warnings and just use my example as proof that it was OK. This hasn’t quite shaken out for me yet, but I figured we could go through my research.

First, things first:

Just don’t do it.

A disabled link is not a link, it’s just text. You need to rethink your design if it calls for disabling a link.

Bootstrap has examples of applying the .disabled class to anchor tags, and I hate them for it. At least they mention that the class only provides a disabled style, but this is misleading. You need to do more than just make a link look disabled if you really want to disable it.

Surefire way: remove the href

If you have decided that you are going to ignore my warning and proceed with disabling a link, then removing the href attribute is the best way I know how.

Straight from the official Hyperlink spec:

The href attribute on a and area elements is not required; when those elements do not have href attributes they do not create hyperlinks.

An easier to understand definition from MDN:

This attribute may be omitted (as of HTML5) to create a placeholder link. A placeholder link resembles a traditional hyperlink, but does not lead anywhere.

Here is basic JavaScript code to set and remove the href attribute:

/* * Use your preferred method of targeting a link * * document.getElementById('MyLink'); * document.querySelector('.link-class'); * document.querySelector('[href="https://unfetteredthoughts.net"]'); */
// "Disable" link by removing the href property
link.href = '';
// Enable link by setting the href property
link.href = 'https://unfetteredthoughts.net';

Styling this via CSS is also pretty straightforward:

a { /* Disabled link styles */
}
a:link, a:visited { /* or a[href] */ /* Enabled link styles */
}

That’s all you need to do!

That’s not enough, I want something more complex so that I can look smarter!

If you just absolutely have to over-engineer some extreme solution, here are some things to consider. Hopefully, you will take heed and recognize that what I am about to show you is not worth the effort.

First, we need to style our link so that it looks disabled.

.isDisabled { color: currentColor; cursor: not-allowed; opacity: 0.5; text-decoration: none;
}
<a class="isDisabled" href="https://unfetteredthoughts.net">Disabled Link</a>

Setting color to currentColor should reset the font color back to your normal, non-link text color. I am also setting the mouse cursor to not-allowed to display a nice indicator on hover that the normal action is not allowed. Already, we have left out non-mouse users that can’t hover, mainly touch and keyboard, so they won’t get this indication. Next the opacity is cut to half. According to WCAG, disabled elements do not need to meet color contrast guidelines. I think this is very risky since it’s basically plain text at this point, and dropping the opacity in half would make it very hard to read for users with low-vision, another reason I hate this. Lastly, the text decoration underline is removed as this is usually the best indicator something is a link. Now this looks like a disabled link!

But it’s not really disabled! A user can still click/tap on this link. I hear you screaming about pointer-events.

.isDisabled { ... pointer-events: none;
}

Ok, we are done! Disabled link accomplished! Except, it’s only really disabled for mouse users clicking and touch users tapping. What about browsers that don’t support pointer-events? According to caniuse, this is not supported for Opera Mini and IE<11. IE11 and Edge actually don't support pointer-events unless display is set to block or inline-block. Also, setting pointer-events to none overwrites our nice not-allowed cursor, so now mouse users will not get that additional visual indication that the link is disabled. This is already starting to fall apart. Now we have to change our markup and CSS…

.isDisabled { cursor: not-allowed; opacity: 0.5;
}
.isDisabled > a { color: currentColor; display: inline-block; /* For IE11/ MS Edge bug */ pointer-events: none; text-decoration: none;
}
<span class="isDisabled"><a href="https://unfetteredthoughts.net">Disabled Link</a></span>

Wrapping the link in a <span> and adding the isDisabled class gives us half of our disabled visual style. A nice side-affect here is that the disabled class is now generic and can be used on other elements, like buttons and form elements. The actual anchor tag now has the pointer-events and text-decoration set to none.

What about keyboard users? Keyboard users will use the ENTER key to activate links. pointer-events are only for pointers, there is no keyboard-events. We also need to prevent activation for older browsers that don’t support pointer-events. Now we have to introduce some JavaScript.

Bring in the JavaScript

// After using preferred method to target link
link.addEventListener('click', function (event) { if (this.parentElement.classList.contains('isDisabled')) { event.preventDefault(); }
});

Now our link looks disabled and does not respond to activation via clicks, taps, and the ENTER key. But we are still not done! Screen reader users have no way of knowing that this link is disabled. We need to describe this link as being disabled. The disabled attribute is not valid on links, but we can use aria-disabled="true".

<span class="isDisabled"><a href="https://unfetteredthoughts.net" aria-disabled="true">Disabled Link</a></span>

Now I am going to take this opportunity to style the link based on the aria-disabled attribute. I like using ARIA attributes as hooks for CSS because having improperly styled elements is an indicator that important accessibility is missing.

.isDisabled { cursor: not-allowed; opacity: 0.5;
}
a[aria-disabled="true"] { color: currentColor; display: inline-block; /* For IE11/ MS Edge bug */ pointer-events: none; text-decoration: none;
}

Now our links look disabled, act disabled, and are described as disabled.

Unfortunately, even though the link is described as disabled, some screen readers (JAWS) will still announce this as clickable. It does that for any element that has a click listener. This is because of developer tendency to make non-interactive elements like div and span as pseudo-interactive elements with a simple listener. Nothing we can do about that here. Everything we have done to remove any indication that this is a link is foiled by the assistive technology we were trying to fool, ironically because we have tried to fool it before.

But what if we moved the listener to the body?

document.body.addEventListener('click', function (event) { // filter out clicks on any other elements if (event.target.nodeName == 'A' && event.target.getAttribute('aria-disabled') == 'true') { event.preventDefault(); }
});

Are we done? Well, not really. At some point we will need to enable these links so we need to add additional code that will toggle this state/behavior.

function disableLink(link) {
// 1. Add isDisabled class to parent span link.parentElement.classList.add('isDisabled');
// 2. Store href so we can add it later link.setAttribute('data-href', link.href);
// 3. Remove href link.href = '';
// 4. Set aria-disabled to 'true' link.setAttribute('aria-disabled', 'true');
}
function enableLink(link) {
// 1. Remove 'isDisabled' class from parent span link.parentElement.classList.remove('isDisabled');
// 2. Set href link.href = link.getAttribute('data-href');
// 3. Remove 'aria-disabled', better than setting to false link.removeAttribute('aria-disabled');
}

That’s it. We now have a disabled link that is visually, functionally, and semantically disabled for all users. It only took 10 lines of CSS, 15 lines of JavaScript (including 1 listener on the body), and 2 HTML elements.

Seriously folks, just don’t do it.


How to Disable Links is a post from CSS-Tricks