Tag: HTML

You don’t need external assets in an HTML file

A fun exercise from Terence Eden. You can send an HTML file over the wire including anything a website might need without requesting any other files. CSS and JavaScript are easy, because there are <script> and <style> tags. Images and fonts (and pretty much whatever other kind of asset) aren’t too hard because Data URLs exist. See Terence’s post for an extra-tricky final version including .zip files.

Reminds me of a couple of other tricks…

Direct Link to ArticlePermalink


The post You don’t need external assets in an HTML file appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , , ,

Tabs in HTML?

You know what tabs are, Brian.

I mean… You use them every day, on every OS. Everybody knows they exist in every toolbox. All that’s left is to “just pave the cowpaths!” But when you get right down to it, it’s a lot more complicated than that.

Brian Kardell shares a bit about the progress of bringing “Tabs” to HTML. We kinda think we know what they are, but you have to be really specific when dealing with specs and defining them. It’s tricky. Then, even if you settle on a solid definition, an HTML expression of that isn’t exactly clear. There are all kinds of expressions of tabs that all make sense in their own way. Imagine marking up tabs where you put all the tabs as a row of links or buttons up top, and then a bunch of panels below that. They call that a “Table of Contents” style of markup, and it makes some kind of logical sense (“the markup looks like tabs already”). But it also has some problems, and it looks like sections-with-headers is more practical (“If you have the heading, you can build the TOC, but not vice-versa”). Spicy sections are a totally different pattern. And that’s just one problem they are facing.

I don’t envy the work, but I look forward to the progress in no small part because authoring tabs is tricky business. Not hard to do, but very hard to do right. I’ve talked in the past about how I’ve built tabs many times in jQuery where just a click handler on a row of links hides or shows some matching divs below. That “works” if you ignore accessibility entirely (e.g. how you navigate between tabs, focus management, ARIA expectations, etc).

Here’s the ShopTalk discussion and here’s a different perspective in a chat I had with Stephen on CodePen Radio where we get into our <Tabs /> React component on CodePen.

Direct Link to ArticlePermalink


The post Tabs in HTML? appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

,
[Top]

HTML is Not a Programming Language?

HTML is not a programming language.

I’ve heard that sentence so many times and it’s tiring. Normally, it is followed by something like, It doesn’t have logic, or, It is not Turing complete,.so… obviously it is not a programming language. Like it’s case-closed and should be the end of the conversation.

Should it be, though?

I want to look at typical arguments I hear used to belittle HTML and offer my own rebuttals to show how those claims are not completely correct.

My goal is not to prove that HTML is or is not a programming language, but to show that the three main arguments used for claiming it is not are flawed or incorrect, thus invalidating the conclusion from a logical point of view.

“HTML is a markup language, not a programming language”

This statement, by itself, sounds great… but it is wrong: markup languages can be programming languages. Not all of them are (most are not) but they can be. If we drew a Venn diagram of programming languages and markup languages, it would not be two separate circles, but two circles that slightly intersect:

A markup language that operates with variables, has control structures, loops, etc., would also be a programming language. They are not mutually exclusive concepts.

TeX and LaTeX are examples of markup languages that are also considered programming languages. It may not be practical to develop with them, but it is possible. And we can find examples online, like a BASIC interpreter or a Mars Rover controller (which won the Judges’ prize in the ICFP 2008 programming contest).

While some markup languages might be considered programming languages, I’m not saying that HTML is one of them. The point is that the original statement is wrong: markup languages can be programming languages. Therefore, saying that HTML is not a programming language because it is a markup language is based on a false statement, and whatever conclusion you arrive at from that premise will be categorically wrong.

“HTML doesn’t have logic”

This claim demands that we clarify what “logic” means because the definition might just surprise you.

As with Turing-completeness (which we’ll definitely get to), those who bring this argument to the table seem to misunderstand what it is exactly. I’ve asked people to tell me what they mean by “logic” and have gotten interesting answers back like:

Logic is a sensible reason or way of thinking.

That’s nice if what we’re looking for is a dictionary definition of logic. But we are talking about programming logic, not just logic as a general term. I’ve also received answers like:

Programming languages have variables, conditions, loops, etc. HTML is not a programming language because you can’t use variables or conditions. It has no logic.

This is fine (and definitely better than getting into true/false/AND/OR/etc.), but also incorrect. HTML does have variables — in the form of attributes — and there are control structures that can be used along with those variables/attributes to determine what is displayed.

But how do you control those variables? You need JavaScript!

Wrong again. There are some HTML elements that have internal control logic and don’t require JavaScript or CSS to work. And I’m not talking about things like <link> or <noscript> – which are rudimentary control structures and have been part of the standard for decades. I’m referring to elements that will respond to the user input and perform conditional actions depending on the current state of the element and the value of a variable. Take the <details>/<summary> tuple or the <dialog> element as examples: when a user clicks on them, they will close if the open attribute is present, and they will open if it is not. No JavaScript required.

So just saying alone that HTML isn’t a programming language because it lacks logic is misleading. We know that HTML is indeed capable of making decisions based on user input. HTML has logic, but it is inherently different from the logic of other languages that are designed to manipulate data. We’re going to need a stronger argument than that to prove that HTML isn’t a form of programming.

“HTML is not ‘Turing complete’”

OK, this is the one we see most often in this debate. It’s technically correct (the best kind of correct) to say HTML is not Turing complete, but it should spark a bigger debate than just using it as a case-closing statement.

I’m not going to get into the weeds on what it means to be Turing complete because there are plenty of resources on the topic. In fact, Lara Schenck summarizes it nicely in a post where she argues that CSS is Turning complete:

In the simplest terms, for a language or machine to be Turing complete, it means that it is capable of doing what a Turing machine could do: perform any calculation, a.k.a. universal computation. After all, programming was invented to do math although we do a lot more with it now, of course!

Because most modern programming languages are Turing complete, people use that as the definition of a programming language. But Turing-completeness is not that. It is a criterion to identify if a system (or its ruleset) can simulate a Turing machine. It can be used to classify programming languages; it doesn’t define them. It doesn’t even apply exclusively to programming languages. Take, for example, the game Minecraft (which meets that criterion) or the card game Magic: The Gathering (which also meets the criterion). Both are Turing complete but I doubt anyone would classify them as programming languages.

Turing-completeness is fashionable right now the same way that some in the past considered the difference between compiled vs. interpreted languages to be good criteria. Yes. We don’t have to make a big memory effort to remember when developers (mainly back-end) downplayed front-end programming (including JavaScript and PHP) as not “real programming.” You still hear it sometimes, although now faded, mumbled, and muttered.

The definition of what programming is (or is not) changes with time. I bet someone sorting through punched cards complained about how typing code in assembly was not real programming. There’s nothing universal or written in stone. There’s no actual definition.

Turing-completeness is a fair standard, I must say, but one that is biased and subjective — not in its form but in the way it is picked. Why is it that a language capable of generating a Turing Complete Machine gets riveted as a “programming language” while another capable of generating a Finite State Machine is not? It is subjective. It is an excuse like any other to differentiate between “real developers” (the ones making the claim) and those inferior to them.

To add insult to injury, it is obvious that many of the people parroting the “HTML is not Turing complete” mantra don’t even know or understand what Turing-completeness means. It is not an award or a seal of quality. It is not a badge of honor. It is just a way to categorize programming languages — to group them, not define them. A programming language could be Turing complete or not in the same way that it could be interpreted or compiled, imperative or declarative, procedural or object-oriented.


So, is HTML a programming language?

If we can debase the main arguments claiming that HTML is not a programming language, does that actually mean that HTML is a programming language? No, it doesn’t. And so, the debate will live on until the HTML standard evolves or the “current definition” of programming language changes.

But as developers, we must be wary of this question as, in many cases, it is not used to spark a serious debate but to stir controversy while hiding ulterior motives: from getting easy Internet reactions, to dangerously diminishing the contribution of a group of people to the development ecosystem.

Or, as Ashley Kolodziej beautifully sums it up in her ode to HTML:

They say you’re not a real programming language like the others, that you’re just markup, and technically speaking, I suppose that’s right. Technically speaking, JavaScript and PHP are scripting languages. I remember when it wasn’t cool to know JavaScript, when it wasn’t a “real” language too. Sometimes, I feel like these distinctions are meaningless, like we built a vocabulary to hold you (and by extension, ourselves as developers) back. You, as a markup language, have your own unique value and strengths. Knowing how to work with you best is a true expertise, one that is too often overlooked.

Independent of the stance that we take on the “HTML is/isn’t a programming language” discussion, let’s celebrate it and not deny its importance: HTML is the backbone of the Internet. It’s a beautiful language with vast documentation and extensive syntax, yet so simple that it can be learned in an afternoon, and so complex that it takes years to master. Programming language or not, what really matters is that we have HTML in the first place.


The post HTML is Not a Programming Language? appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, ,
[Top]

Detect Unused Classes in… HTML

Usually, when “unused” comes up in conversation regarding CSS, it’s about removing chunks of CSS that are not used in your site or, at least, the styles not currently in use on a specific page. The minimal amount of CSS is best! I’ve written about how this is a hard problem in the past. In JavaScript-land, the equivalent is tree shaking (removing unusued JavaScript).

But what about the other way around, detecting classes in HTML that aren’t used in your CSS? If you knew this for sure, you could clean up your markup, removing classes that don’t do anything.

I saw Robert Kieffer post a Gist the other day with an interesting solution. The idea is to load up document.styleSheets and find all the rules (the ones that are classes). Then, use a MutationObserver to watch the DOM for all HTML, and check the classList of each node to see if it matches any from any stylesheet. If the HTML has a class not found in a stylesheet, report it.

I gave it a quick whirl and got it working and correctly reporting unused classes:

Your mileage may vary. For one thing, this script is set up as an ES Module. That means if you just import it and run it on a regular ol’ HTML document, it won’t find anything because your <script type="module"> is deferred and the MutationObserver won’t pick anything up. I just un-moduled it and put it in the <head> to make my demo work.

I Netlify Dropped the site online in case you wanna dig into it and check it out. I would have used CodePen, but CodePen doesn’t link up your styles as <link>ed stylesheets (by default, but you could use external resources to do that). I just thought it would be more clear as a deployed site.

Careful now.

Just like unused CSS is a hard problem because of how hard it is to know for sure know if a ruleset is unused, this approach may be an even harder problem. For one thing, classes might be used as a JavaScript hook for things. Styles might get injected onto the page in <style> blocks, which this script wouldn’t check. Heck, you might have integration tests that run in CI that use classes to do testing-related things.

I’d say this kind of thing is a useful tool for havin’ a looksie at classes that you have a hunch might be unused. But I wouldn’t say there’s a permission slip to run this thing and then yank out every reported class without further investigation.


The post Detect Unused Classes in… HTML appeared first on CSS-Tricks.

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

CSS-Tricks

, , , ,
[Top]

VS Code Extensions for HTML

Let’s look at some extensions for VS Code that make writing and editing HTML (and languages that are basically HTML with extra powers) better. You may not like all of them. Maybe some of them don’t appeal to you, solve a problem you don’t have, or feel like more clutter than you need. That’s OK. These are just a handful that I’ve tried and liked to some degree.

I’d start with Emmet here, even thought it’s not technically an extension1 for VS Code. It’s built right in. You should know about it though because it’s very useful. It does “HTML Expansions” like this, which I use pretty much every day of my life:

HTML End Tag Labels

I heard about this one from Stefan Judis who blogged about it the other day and inspired this post idea.

The whole idea is that rather than you leaving comments in your HTML to indicate what HTML element it is closing (a somewhat common practice, especially for partials that close elements that might not be opened in the same document).

<div class="main">   </div> <!-- / div.main -->  <?php /* / div.main */ ?> <?php /* Sometimes I'd do it in a server side language so it didn't go over the wire. */ ?>

This extension shows you UI about what HTML is being closed:

Auto Close Tag

As soon as you type the > in an HTML element, like the last bracket in <div>, the closing tag is automatically created for you.

It can be configured to only auto close after you’ve typed the </ to indicate you’re about to close a tag, which is a default in Sublime Text 3. Speaking of which, if you install the Sublime Text Keymap, you’d get that automatically, plus a handful of other fancy key commands.

There is also Close HTML/XML tag, but it only works via key command. With Auto Close Tag you can configure it either way, and it has far more installs for whatever reason.

Highlight Matching Tag

Here’s the GIF from their docs:

I was going to do my own video, but I discovered that even if I have this extension off, something else in my VS Code is highlighting matching tags anyway. I’m not entirely sure what it is, which leads me to believe it might be a built-in feature now.

What I see without this extension on: a border around the matching tags.

Not specific to HTML, but if like this sort of help with matching things, you might give Bracket Pair Colorizer 2 a try, which can be quite nice for CSS and JavaScript.

Auto Rename Tag

I find this one quite useful!

I believe this functionality is actually built into the canonical Emmet, but again, VS Code doesn’t use canonical Emmet so this feature isn’t there, hence the need for this extra plugin.

Better Comments

I leave code comments fairly liberally, especially when dev’ing out new things. A convention I like is when a comment is prefixed (e.g. TODO) that it is extra important and needs attention. Better Comments allows those to look visually different.

Code Spell Checker

There is no spell-checking in VS code. I don’t love that. To me this plugin is a must-have, especially for HTML, because HTML typically has content in it, like words, that should be spelled correctly. And just like a linter, this plugin gives you squiggles when something is wrong and a menu to attempt to fix it.

Indent Rainbow

Bask in this glorious rainbow created by deepening indents:

The point is that it gives you some visual cues to what level you’re currently looking/working at. In that sense it’s kinda like the Highlight Matching Tag, but I like them both honestly. It’s most useful when you need to scroll up or down to find where the matching tag is.

Prettier

Prettier does work on HTML, but I’d almost call it a smidge controversial. For example, it breaks HTML attributes onto single lines which feels a lot like a JSX thing but less common to see in raw HTML. But sometimes there are literal side effects. Like if you type <ul><li></li><li></li></ul> on purpose like that (no whitespace) because you’re going to set all the list items inline, Prettier will break them onto their own lines, inserting whitespace, and changing the layout of what you intend. You can always fix it with a comment for Prettier to leave it alone (e.g. {/* prettier-ignore */}), but I could see it rubbing people the wrong way. There are even settings for it under HTML Whitespace Sensitivity, but it could never be perfect.

I actually got Prettier for HTML working just for this blog post so I think I’ll keep it for a while and see if I like it. I already know I like Prettier for JSX. I’m generally for as much autoformatting as possible.

Snippet

I gotta imagine there are lots of snippet plugins, but this is the only one I’ve tried and it works fine. I like how you make snippets right from existing files.

Tabnine

I heard about this one from Kyle Simpson who I think was doing some paid consulting with them or something. The point of it is that it does fancy AI-powered autocomplete suggestions, even in HTML. Check out it guessing at some attributes:

This looks like a pretty commercial product with features that push you toward paid plans for teams. I don’t really feel like getting all into that; it was just interesting to see a tool like this work with HTML.

axe Accessibility Linter

This lints your HTML for accessibility problems right in the editor. There are a bunch of rules it checks for.


  1. Did you know even though VS Code has Emmet baked right in, there is no communication between Emmet’s creator and the VS Code team? I’ve tried to facilitate that connection in the past, but failed. Point being: Emmet in VS Code would probably be better if it wasn’t just jacked in but integrated from the official packages. Emmet has new things that VS Code could use, like expansion previews.

The post VS Code Extensions for HTML appeared first on CSS-Tricks.

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

CSS-Tricks

, ,
[Top]

A Love Letter to HTML & CSS

Ashley Kolodziej — May 2021

Dear HTML & CSS

I see you.

In the back there, behind JavaScript and React and PHP and all those “real” programming languages, I see you. And I appreciate you.

I’ve seen the YouTube videos. You’ve been condensed down to a sixty-second blip on the path to bigger and better things, a one-trick div pony at the back of the race. You’re a support character. Everyone knows HTML these days. Even if that’s not the case, it’s not hard to learn, they say.

I know it’s not true.

You are the foundation of the Internet. You are the bridge between humans and information. When we say HTML isn’t an expertise in and of itself, when we take you for granted, we leave behind the people and systems who access that information using web crawlers and accessibility technology.

They say you’re not a real programming language like the others, that you’re just markup, and technically speaking, I suppose that’s right. Technically speaking, JavaScript and PHP are scripting languages. I remember when it wasn’t cool to know JavaScript, when it wasn’t a “real” language too. Sometimes, I feel like these distinctions are meaningless, like we built a vocabulary to hold you (and by extension, ourselves as developers) back. You, as a markup language, have your own unique value and strengths. Knowing how to work with you best is a true expertise, one that is too often overlooked.

Markup requires systematic thinking. What structure is the best match for this content? How can we make this content easier to discover and parse in the right order? What tags do we need to ensure a screen reader will parse your information correctly? I want you to know I know how important you are, and I still ask these questions.

I think of you every time I test a website in VoiceOver and discover it is completely unusable, with my keyboard’s focus jumping away to places I can’t actually interact with and no clear sectioning and headings to help navigate.

And to my longtime friend, CSS. I want you to know I understand you are so much more than just a pretty face. Sure, your main job is to, well, style markup. But why should that be any less celebrated than the other languages? You are the visual translation of information. What good is all the information in the world if we can’t easily understand it? You hold the keys to hierarchy and contrast and layout, the keys to visual communication.

Your language is an art. I recognize your importance, the balance of performance in rendering and specificity and predicting when and where other systems or designers might want to override something. Sure, you style, and you style well. But what the world forgets sometimes is you are, at heart, a planner: the cascading part of Cascading Style Sheets. Oh, to be JavaScript where you can do whatever you want, whenever you want, and change markup and styles on the fly. Don’t they know inline styles are some of the most specific styles around?

I know, and I respect that. There is a time and place for specificity, and I cherish your ability to manage that. I love your system of overrides, of thinking ahead to what should and shouldn’t be modifiable by another developer easily. I find the appreciation of specificity and !important and contrast and all the beautiful little things you do well increasingly lost in the pursuit of the newest and shiniest frameworks.

But I am still here for you, HTML and CSS. And I will continue to show everyone I can how much you both have to offer. Because without that foundational care and expertise, we wouldn’t be able to communicate this information at all. You are the languages at the core of equitable information distribution, and I want you to know that even if you aren’t in the spotlight right now, I remember that.

Even if it sometimes feels I’m the only person out there who still does.

With love, Ashley Kolodziej


The post A Love Letter to HTML & CSS appeared first on CSS-Tricks.

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

CSS-Tricks

, ,
[Top]

HTML Boilerplates

Manuel Matuzović goes line-by-line through a boilerplate HTML document. I like it. It’s a good reference and has a lot of the same type of stuff I tend to put in the main HTML template. It makes me think about how opinionated this kind of thing can be. Dang near every line! Not the DOCTYPE, not the <title>, but nearly everything else.

The HTML
<!DOCTYPE html> <html lang="en" class="no-js"> <head>   <meta charset="UTF-8">   <meta name="viewport" content="width=device-width">    <title>Unique page title - My Site</title>    <script type="module">     document.documentElement.classList.remove('no-js');     document.documentElement.classList.add('js');   </script>    <link rel="stylesheet" href="/assets/css/styles.css">   <link rel="stylesheet" href="/assets/css/print.css" media="print">    <meta name="description" content="Page description">   <meta property="og:title" content="Unique page title - My Site">   <meta property="og:description" content="Page description">   <meta property="og:image" content="https://www.mywebsite.com/image.jpg">   <meta property="og:image:alt" content="Image description">   <meta property="og:locale" content="en_GB">   <meta property="og:type" content="website">   <meta name="twitter:card" content="summary_large_image">   <meta property="og:url" content="https://www.mywebsite.com/page">   <link rel="canonical" href="https://www.mywebsite.com/page">    <link rel="icon" href="/favicon.ico">   <link rel="icon" href="/favicon.svg" type="image/svg+xml">   <link rel="apple-touch-icon" href="/apple-touch-icon.png">   <link rel="manifest" href="/my.webmanifest">   <meta name="theme-color" content="#FF00FF"> </head>  <body>   <!-- Content -->   <script src="/assets/js/xy-polyfill.js" nomodule></script>   <script src="/assets/js/script.js" type="module"></script> </body> </html>

Maybe my site doesn’t use any JavaScript or have no-JavaScript fallbacks so I don’t need any of the class name dancing. Maybe my site doesn’t need print styles, but I do need link prefetching. Maybe I don’t care about social images, but I do want critical CSS in the head. It’s a boilerplate, not a prescription — it’s meant to be changed.

There was a time when HTML5 Boilerplate was a huge project in this space. It has a whole GitHub Org! The boilerplate has 50,000 stars! Personally, I feel like the project lost its way when it started to have a src and dist folder and a 200-line Gulp build process, ya know? It worked best as a reference for what stuff any given web project might need, but now I feel like it is intimidating in a way it doesn’t need to be. The boilerplate index file is also quite opinionated. It assumes Normalize and Modernizr, which are certainly not deprecated projects, but also not things I see developers reaching for much anymore. It even assumes Google Analytics usage!

I have no problem with people having and sharing boilerplate documents, but considering how unavoidable being opinionated it is with them, I also like the reference guide approach. Just show me every possible thing that can go in the <head> (a lot of the value of these boilerplates), and I’ll pick and choose what I need (or may have forgotten). To that end, Josh Buchea’s HEAD project is pretty cool.


The post HTML Boilerplates appeared first on CSS-Tricks.

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

CSS-Tricks

,
[Top]

HTML Inputs and Labels: A Love Story

Most inputs have something in common — they are happiest with a companion label! And the happiness doesn’t stop there. Forms with proper inputs and labels are much easier for people to use and that makes people happy too.

A happy label and input pair

In this post, I want to focus on situations where the lack of a semantic label and input combination makes it much harder for all sorts of people to complete forms. Since millions of people’s livelihoods rely on forms, let’s get into the best tips I know for creating a fulfilling and harmonious relationship between an input and a label.

Content warning: In this post are themes of love and relationships.

The love story starts here! Let’s cover the basics for creating happy labels and inputs.

How to pair a label and an input

There are two ways to pair a label and an input. One is by wrapping the input in a label (implicit), and the other is by adding a for attribute to the label and an id to the input (explicit).

Think of an implicit label as hugging an input, and an explicit label as standing next to an input and holding its hand.

<label>    Name:   <input type="text" name="name" /> </label>

An explicit label’s for attribute value must match its input’s id value. For example, if for has a value of name, then id should also have a value of name.

<label for="name">Name: </label> <input type="text" id="name" name="name" />

Unfortunately, an implicit label is not handled correctly by all assistive technologies, even if for and id attributes are used. Therefore, it is always the best idea to use an explicit label instead of an implicit label.

<!-- IMPLICIT LABEL (not recommended for use) - the label wraps the input. --> <label>    Name:   <input type="text" name="name" /> </label>  <!-- EXPLICIT LABEL (recommended for use) - the label is connected to an input via "for" and "id" --> <label for="explicit-label-name">Name: </label> <input type="text" id="explicit-label-name" name="name" />

Each separate input element should only be paired with one label. And a label should only be paired with one input. Yes, inputs and labels are monogamous. ♥️

Note: There’s one sort of exception to this rule: when we’re working with a group of inputs, say several radio buttons or checkboxes. In these cases, a <legend> element is used to group certain input elements, such as radio buttons, and serves as the accessible label for the entire group.

Not all inputs need labels

An input with a type="submit" or type="button" does not need a label — the value attribute acts as the accessible label text instead. An input with type="hidden" is also fine without a label. But all other inputs, including <textarea> and <select> elements, are happiest with a label companion.

What goes in a label

The content that goes inside of a label should:

  • Describe its companion input. A label wants to show everyone that it belongs with its input partner.
  • Be visible. A label can be clicked or tapped to focus its input. The extra space it provides to interact with the input is beneficial because it increases the tap or click target. We’ll go into that more in just a bit.
  • Only contain plain text. Don’t add elements like headings or links. Again, we’ll go into the “why” behind this further on down.

One useful thing you can do with the content in a label is add formatting hints. For example, the label for <input type="date" id="date"> will be <label for="date"> as we’d expect. But then we can provide a hint for the user that the date needs to be entered in a specific format, say DD-DD-YYYY, in the form of a <span> between the label and input that specifies that requirement. The hint not only specifies the date format, but has an id value that corresponds to an aria-describedby attribute on the input.

<!-- Describes what the input is for - should be plain text only --> <label for="date">Start date</label> <!-- Describes additional information, usually about formatting --> <span id="date-format">(DD-MM-YYYY):</span> <input type="date" id="date" aria-describedby="date-format" min="2021-03-01" max="2031-01-01" />

This way, we get the benefit of a clear label that describes what the input is for, and a bonus hint to the user that the input needs to be entered in a specific format.

Best practices for a healthy relationship

The following tips go beyond the basics to explain how to make sure a label and input are as happy as can be.

Do: Add a label in the right place

There is a WCAG success criterion that states the visual order of a page should follow the order in which elements appear in the DOM. That’s because:

A user with low vision who uses a screen magnifier in combination with a screen reader may be confused when the reading order appears to skip around on the screen. A keyboard user may have trouble predicting where focus will go next when the source order does not match the visual order.

Think about it. If we have some standard HTML where the label comes before the input:

<label for="orange">Orange</label> <input type="checkbox" id="orange" name="orange">

That places the label before the input in the DOM. But now let’s say our label and form are inside a flexible container and we use CSS order to reverse things where the input visually comes before the label:

label { order: 2; } input { order: 1; }

A screen reader user, who is navigating between elements, might expect the input to gain focus before the label because the input comes first visually. But what really happens is the label comes into focus instead. See here for the difference between navigating with a screen reader and a keyboard.

So, we should be mindful of that. It is conventional to place the label on the right-hand side of the input for checkboxes and radio buttons. This can be done by placing the label after the input in the HTML, ensuring the DOM and visual order match.

<form>   <!-- Checkbox with label on the right -->   <span>     <input type="checkbox" id="orange" name="orange">     <label for="orange">Orange</label>   </span>   <!-- Radio button with label on the right -->   <span>     <input type="radio" id="banana" name="banana">     <label for="banana">Banana</label>   </span>   <!-- Text input with label on the left -->   <span>     <label for="apple">How do you like them apples?</label>     <input type="text" id="apple" name="apple">   </span> </form>

Do: Check inputs with a screen reader

Whether an input is written from scratch or generated with a library, it is a good idea to check your work using a screen reader. This is to make sure that:

  • All relevant attributes exist — especially the matching values of the for and id attributes.
  • The DOM matches the visual order.
  • The label text sounds clear. For example, “dd-mm-yyyy” is read out differently to its uppercase equivalent (DD-MM-YYYY).
Screen reader reading out a lower case and upper case date input hint.
Just because the letters are the same doesn’t mean that they get read the same way by a screen reader.

Over the last few years, I have used JavaScript libraries, like downshift, to build complex form elements such as autocomplete or comboboxes on top of native HTML ones, like inputs or selects. Most libraries make these complex elements accessible by adding ARIA attributes with JavaScript.

However, the benefits of native HTML elements enhanced using JavaScript are totally lost if JavaScript is broken or disabled, making them inaccessible. So check for this and provide a server-rendered, no-JavaScript alternative as a safe fallback.

Check out these basic form tests to determine how an input and its companion label or legend should be written and announced by different screen readers.

Do: Make the label visible

Connecting a label and an input is important, but just as important is keeping the label visible. Clicking or tapping a visible label focuses its input partner. This is a native HTML behavior that benefits a huge number of people.

Imagine a label wanting to proudly show its association with an input:

A visible happy label proudly showing off its input partner.
A label really wants to show off its input arm candy. 💪🍬

That said, there are going to be times when a design calls for a hidden label. So, if a label must be hidden, it is crucial to do it in an accessible way. A common mistake is to use display: none or visibility: hidden to hide a label. These CSS display properties completely hide an element — not only visually but also from screen readers.

Consider using the following code to visually hide labels:

/* For non-natively-focusable elements. For natively focusable elements */ /* Use .visually-hidden:not(:focus):not(:active) */ .visually-hidden {   border-width: 0 !important;   clip: rect(1px, 1px, 1px, 1px) !important;   height: 1px !important;   overflow: hidden !important;   padding: 0 !important;   position: absolute !important;   white-space: nowrap !important;   width: 1px !important; }

Kitty Giraudel explains in depth how to hide content responsibly.

What to Avoid

To preserve and maintain a healthy relationship between inputs and labels, there are some things not to do when pairing them. Let’s get into what those are and how to prevent them.

Don’t: Expect your input to be the same in every browser

There are certain types of inputs that are unsupported In some older desktop browsers. For example, an input that is type="date" isn’t supported in Internet Explorer (IE) 11, or even in Safari 141 (released September 2020). An input like this falls back to type="text". If a date input does not have a clear label, and it automatically falls back to a text input in older browsers, people may get confused.

Don’t: Substitute a label with a placeholder

Here is why a placeholder attribute on an input should not be used in place of a label:

  • Not all screen readers announce placeholders.
  • The value of a placeholder is in danger of being cut-off on smaller devices, or when a page is translated in the browser. In contrast, the text content of a label can easily wrap onto a new line.
  • Just because a developer can see the pale grey placeholder text on their large retina screen, in a well-lit room, in a distraction-free environment, doesn’t mean everyone else can. A placeholder can make even those with good vision scrunch their eyes up and eventually give up on a form.
An input on a mobile device where the placeholder text is cut off.
Make sure this is somewhere I can what? It’s hard to tell when the placeholder gets cut off like that.
An input where the translated placeholder is cut off.
Work on a multi-lingual site? A translated placeholder can get cut off even though the English translation is just fine. In this case, the translated placeholder should read “Durchsuchen Sie die Dokumentation.”

  • Once a character is entered into an input, its placeholder becomes invisible — both visually and to screen readers. If someone has to back-track to review information they’ve entered in a form, they’d have to delete what was entered just to see the placeholder again.
  • The placeholder attribute is not supported in IE 9 and below, and disappears when an input is focused in IE 11. Another thing to note: the placeholder color is unable to be customized with CSS in IE 11.

Placeholders are like the friend that shows up when everything is perfect, but disappears when you need them most. Pair up an input with a nice, high-contrast label instead. Labels are not flaky and are loyal to inputs 100% of the time.

The Nielsen Norman Group has an in-depth article that explains why placeholders in form fields are harmful.

Don’t: Substitute a label with another attribute or element

When no label is present, some screen readers will look for adjacent text and announce that instead. This is a hit-and-miss approach because it’s possible that a screen reader won’t find any text to announce.

The below code sample comes from a real website. The label has been substituted with a <span> element that is not semantically connected to the input.

<div>   <span>Card number</span>   <div>     <input type="text" value="" id="cardNumber" name="cardNumber" maxlength="40">   </div> </div>

The above code should be re-written to ensure accessibility by replacing the span with a label with for="cardNumber" on it. This is by far the most simple and robust solution that benefits the most people.

While a label could be substituted with a span that has an id with a value matching the input’s aria-labelledby attribute, people won’t be able to click the span to focus the input in the same way a label allows. It is always best to harness the power of native HTML elements instead of re-inventing them. The love story between native input and label elements doesn’t need to be re-written! It’s great as-is.

Don’t: Put interactive elements inside labels

Only plain text should be included inside a label. Avoid inserting things such as headings, or interactive elements such as links. Not all screen readers will announce a label correctly if it contains something other than plain text. Also, if someone wants to focus an input by clicking its label, but that label contains a link, they may click the link by mistake.

<form>   <div>     <!-- Don't do this -->     <input type="checkbox" id="t-and-c" name="name" />     <label for="t-and-c">I accept the <a href="https://link.com">terms and conditions</a></label>   </div>   <div>     <!-- Try this -->     <input type="checkbox" id="t-and-c2" name="name" />     <label for="t-and-c2">I accept the terms and conditions.</label>     <span>Read <a href="https://link.com">terms and conditions</a></span>   </div> </form>

Real-life examples

I always find that real-life examples help me to properly understand something. I searched the web and found examples of labels and inputs from a popular component library and website. Below, I explain where the elements fall short and how they can be improved to ensure a better pairing.

Component library: Material

MaterialUI is a React component library based on Google’s design system. It includes a text input component with a floating label pattern that has become a popular go-to for many designers and developers:

The floating label pattern starts with the label in the placeholder position that moves the label to its proper place above the field. The idea is that this achieves a minimal design while solving the issue of placeholders disappearing when typing.

Clicking on the input feels smooth and looks great. But that’s the problem. Its qualities are mostly skin-deep.

At the time of writing this post, some issues I found with this component include:

  • There is no option to have the label outside of the input in order to offer an increased interactive area for focusing the input.
  • There is an option to add a hint like we saw earlier. Unfortunately, the hint is only associated with the input via proximity and not through a matching id and aria-describedby. This means that not all screen readers will be able to associate the helper message with the input.
  • The label is behind the input in the DOM, making the visual order is incorrect.
  • The empty input looks look like it is already filled out, at least as long as it is not active.
  • The label slides up when the input is clicked, making it unsuitable for those who prefer reduced motion.

Adam Silver also explains why float labels are problematic and gets into a detailed critique of Material’s text input design.

Website: Huffpost

The Huffpost website has articles containing a newsletter subscription form:

Huffpost newsletter signup form
This form looks quite nice but could be improved

At the time of writing this blog post, the email input that Huffpost uses could benefit from a number of improvements:

  • The lack of a label means a smaller click or tap target. Instead of a label there is an aria-label attribute on the input.
  • The font size of the placeholder and input values are a tiny 11px, which can be hard to read.
  • The entire input disappears without JavaScript, meaning people have no way to sign up to the newsletter if JavaScript is disabled or broken.

Closing remarks

A surprising number of people struggle to enter information into poorly-constructed inputs. That list includes people with cognitive, motor and physical disabilities, autism spectrum disorders, brain injuries, and poor vision. Other people who struggle include those in a hurry, on a poor connection, on a small device, on an old device, and unfamiliar with digital forms, among many others.

Additionally, there are numerous reasons why JavaScript might break or be switched off in a browser, meaning inputs become dysfunctional or completely inaccessible. There are also people who are fully capable of viewing a web page but who may choose to use a keyboard along with a screen reader.

The message I want to get across is that happy label and input pairs are crucial. It doesn’t matter if your form is beautiful if it is unusable. I can bet that almost everyone would rather fill out an ugly but easy-to-use form rather than a pretty one that causes problems.

Thanks

I want to warmly thank the following people for helping me with this post: Eric Eggert, Adam Silver, Dion Dajka, and Kitty Giraudel. Their combined accessibility knowledge is a force to be reckoned with!

Footnotes

  • 1 The datepicker is actually well-supported in iOS 14 and very nice. One would imagine that a macOS version has got to be on the horizon.

The post HTML Inputs and Labels: A Love Story appeared first on CSS-Tricks.

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

CSS-Tricks

, , , ,
[Top]

HTML Video Sources Should Be Responsive

Scott Jehl doesn’t mince words here:

Removing media support from HTML video was a mistake. It means that for every video we embed in HTML, we’re stuck with the choice of serving source files that are potentially too large or small for many users’ devices (resulting in poor performance, wasteful data consumption, and even sub-optimal quality on larger screens), or resorting to more complicated server-side or scripted or third-party solutions to deliver a correct size.

I remember when responsive images were just starting to come out. One way to explain it was to say it’s like <video> in that you can have multiple <source> elements inside which (in supporting browsers) allowed you to specify attributes like type (e.g. video format) and media (e.g. screen size). But then

Despite being implemented in multiple browsers, the feature was removed from browsers and the HTML specification, without any proposed replacement for the functionality it once provided. One exception is the feature was never removed from Webkit, so it still works in Safari browsers, which is great.

I don’t remember that. That feels like a big WTF moment (some background). I think of the web as being tremendous at backwards compatibility. It’s a rare day when we just yank stuff, and even more rare is a yanking with no alternative whatsoever.

So now with responsive images being a success (it’s a success, right? I can’t imagine how incredibly much bandwidth it has saved the world)… can’t we… put it back?

When I have an immediate need for this, I always think of Cloudinary, because I can alter the size and format of video by changing the URL. Like here’s a video URL where the video codec is automatically determined and the size is forced down to 400px:

https://res.cloudinary.com/css-tricks/video/upload/c_scale,q_auto,vc_auto,w_400/v1612795501/intro-patreon_jpd8er.mp4

It’s nice to have tools like this, but that doesn’t mean the platform shouldn’t be helping.

Direct Link to ArticlePermalink


The post HTML Video Sources Should Be Responsive appeared first on CSS-Tricks.

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

CSS-Tricks

, , , ,
[Top]

Dynamically Switching From One HTML Element to Another in Vue

A friend once contacted me asking if I had a way to dynamically change one HTML element into another within Vue’s template block. For instance, shifting a <div> element to a <span> element based on some criteria. The trick was to do this without relying on a series of v-if and v-else code.

I didn’t think much of it because I couldn’t see a strong reason to do such a thing; it just doesn’t come up that often. Later that same day, though, he reached out again and told me he learned how to change element types. He excitedly pointed out that Vue has a built-in component that can be used as a dynamic element in the very way that he needed.

This small feature can keep code in the template nice and tidy. It can reduce v-if and v-else glut down to a smaller amount of code that’s easier to understand and maintain. This allows us to use methods or computed methods to create nicely-coded, and yet more elaborate, conditions in the script block. That’s where such things belong: in the script, not the template block.

I had the idea for this article mainly because we use this feature in several places in the design system where I work. Granted it’s not a huge feature and it is barely mentioned in the documentation, at least as far as I can tell. Yet it has potential to help render specific HTML elements in components.

Vue’s built-in <component> element

There are several features available in Vue that allow for easy dynamic changes to the view. One such feature, the built-in <component> element, allows components to be dynamic and switched on demand. In both the Vue 2 and the Vue 3 documentation, there is a small note about using this element with HTML elements; that is the part we shall now explore.

The idea is to leverage this aspect of the <component> element to swap out common HTML elements that are somewhat similar in nature; yet with different functionality, semantics, or visuals. The following basic examples will show the potential of this element to help with keeping Vue components neat and tidy.

Buttons and links are often used interchangeably, but there are big differences in their functionality, semantics, and even visuals. Generally speaking, a button (<button>) is intended for an internal action in the current view tied to JavaScript code. A link (<a>), on the other hand, is intended to point to another resource, either on the host server or an external resource; most often web pages. Single page applications tend to rely more on the button than the link, but there is a need for both.

Links are often styled as buttons visually, much like Bootstrap’s .btn class that creates a button-like appearance. With that in mind, we can easily create a component that switches between the two elements based on a single prop. The component will be a button by default, but if an href prop is applied, it will render as a link.

Here is the <component> in the template:

<component   :is="element"   :href="href"   class="my-button" >   <slot /> </component>

This bound is attribute points to a computed method named element and the bound href attribute uses the aptly named href prop. This takes advantage of Vue’s normal behavior that the bound attribute does not appear in the rendered HTML element if the prop has no value. The slot provides the inner content regardless whether the final element is a button or a link.

The computed method is simple in nature:

element () {   return this.href ? 'a' : 'button'; }

If there’s an href prop,. then an <a> element is applied; otherwise we get a <button>.

<my-button>this is a button</my-button> <my-button href="https://www.css-tricks.com">this is a link</my-button>

The HTML renders as so:

<button class="my-button">this is a button</button> <a href="https://www.css-tricks.com" class="my-button">this is a link</a>

In this case, there could be an expectation that these two are similar visually, but for semantic and accessibility needs, they are clearly different. That said, there’s no reason the two outputted elements have to be styled the same. You could either use the element with the selector div.my-button in the style block, or create a dynamic class that will change based on the element.

The overall goal is to simplify things by allowing one component to potentially render as two different HTML elements as needed — without v-if or v-else!

Ordered or unordered list?

A similar idea as the button example above, we can have a component that outputs different list elements. Since an unordered list and an ordered list make use of the same list item (<li>) elements as children, then that’s easy enough; we just swap <ul> and <ol>. Even if we wanted to have an option to have a description list, <dl>, this is easily accomplished since the content is just a slot that can accept <li> elements or <dt>/<dd>combinations.

The template code is much the same as the button example:

<component   :is="element"   class="my-list" >   <slot>No list items!</slot> </component>

Note the default content inside the slot element, I’ll get to that in a moment.

There is a prop for the type of list to be used that defaults to <ul>:

props: {   listType: {     type: String,     default: 'ul'   } }

Again, there is a computed method named element:

element () {   if (this.$  slots.default) {     return this.listType;   } else {     return 'div';   } }

In this case, we are testing if the default slot exists, meaning it has content to render. If it does, then the the list type passed through the listType prop is used. Otherwise, the element becomes a <div> which would show the “No list items!” message inside the slot element. This way, if there are no list items, then the HTML won’t render as a list with one item that says there are no items. That last aspect is up to you, though it is nice to consider the semantics of a list with no apparent valid items. Another thing to consider is the potential confusion of accessibility tools suggesting this is a list with one item that just states there are no items.

Just like the button example above, you could also style each list differently. This could be based on selectors that target the element with the class name, ul.my-list. Another option is to dynamically change the class name based on the chosen element.

This example follows a BEM-like class naming structure:

<component   :is="element"   class="my-list"   :class="`my-list__$  {element}`" >   <slot>No list items!</slot> </component>

Usage is as simple as the previous button example:

<my-list>   <li>list item 1</li> </my-list>  <my-list list-type="ol">   <li>list item 1</li> </my-list>  <my-list list-type="dl">   <dt>Item 1</dt>   <dd>This is item one.</dd> </my-list>  <my-list></my-list>

Each instance renders the specified list element. The last one, though, results in a <div> stating no list items because, well, there’s no list to show!

One might wonder why create a component that switches between the different list types when it could just be simple HTML. While there could be benefits to keeping lists contained to a component for styling reasons and maintainability, other reasons could be considered. Take, for instance, if some forms of functionality were being tied to the different list types? Maybe consider a sorting of a <ul> list that switches to a <ol> to show sorting order and then switching back when done?

Now we’re controlling the elements

Even though these two examples are essentially changing the root element component, consider deeper into a component. For instance, a title that might need to change from an <h2> to an <h3> based on some criteria.

If you find yourself having to use ternary solutions to control things beyond a few attributes, I would suggest sticking with the v-if. Having to write more code to handle attributes, classes, and properties just complicates the code more than the v-if. In those cases, the v-if makes for simpler code in the long run and simpler code is easier to read and maintain.

When creating a component and there’s a simple v-if to switch between elements, consider this small aspect of a major Vue feature.

Expanding the idea, a flexible card system

Consider all that we’ve covered so far and put it to use in a flexible card component. This example of a card component allows for three different types of cards to be placed in specific parts of the layout of an article:

  • Hero card: This is expected to be used at the top of the page and draw more attention than other cards.
  • Call to action card: This is used as a line of user actions before or within the article.
  • Info card: This is intended for pull quotes.

Consider each of these as following a design system and the component controls the HTML for semantics and styling.

In the example above, you can see the hero card at the top, a line of call-to-action cards next, and then — scrolling down a bit — you’ll see the info card off to the right side.

Here is the template code for the card component:

<component :is="elements('root')" :class="'custom-card custom-card__' + type" @click="rootClickHandler">   <header class="custom-card__header" :style="bg">     <component :is="elements('header')" class="custom-card__header-content">       <slot name="header"></slot>     </component>   </header>   <div class="custom-card__content">     <slot name="content"></slot>   </div>   <footer class="custom-card__footer">     <component :is="elements('footer')" class="custom-card__footer-content" @click="footerClickHandler">       <slot name="footer"></slot>     </component>   </footer> </component>

There are three of the “component” elements in the card. Each represents a specific element inside the card, but will be changed based on what kind of card it is. Each component calls the elements() method with a parameter identifying which section of the card is making the call.

The elements() method is:

elements(which) {   const tags = {     hero: { root: 'section', header: 'h1', footer: 'date' },     cta: { root: 'section', header: 'h2', footer: 'div' },     info: { root: 'aside', header: 'h3', footer: 'small' }   }   return tags[this.type][which]; }

There are probably several ways of handing this, but you’ll have to go in the direction that works with your component’s requirements. In this case, there is an object that keeps track of HTML element tags for each section in each card type. Then the method returns the needed HTML element based on the current card type and the parameter passed in.

For the styles, I inserted a class on the root element of the card based on the type of card it is. That makes it easy enough to create the CSS for each type of card based on the requirements. You could also create the CSS based on the HTML elements themselves, but I tend to prefer classes. Future changes to the card component could change the HTML structure and less likely to make changes to the logic creating the class.

The card also supports a background image on the header for the hero card. This is done with a simple computed placed on the header element: bg. This is the computed:

bg() {   return this.background ? `background-image: url($  {this.background})` : null; }

If an image URL is provided in the background prop, then the computed returns a string for an inline style that applies the image as a background image. A rather simple solution that could easily be made more robust. For instance, it could have support for custom colors, gradients, or default colors in case of no image provided. There’s a large number of possibilities that his example doesn’t approach because each card type could potentially have their own optional props for developers to leverage.

Here’s the hero card from this demo:

<custom-card type="hero" background="https://picsum.photos/id/237/800/200">   <template v-slot:header>Article Title</template>   <template v-slot:content>Lorem ipsum...</template>   <template v-slot:footer>January 1, 2011</template> </custom-card>

You’ll see that each section of the card has its own slot for content. And, to keep things simple, text is the only thing expected in the slots. The card component handles the needed HTML element based solely on the card type. Having the component just expect text makes using the component rather simplistic in nature. It replaces the need for decisions over HTML structure to be made and in turn the card is simply implemented.

For comparison, here are the other two types being used in the demo:

<custom-card type="cta">   <template v-slot:header>CTA Title One</template>   <template v-slot:content>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</template>   <template v-slot:footer>footer</template> </custom-card>  <custom-card type="info">   <template v-slot:header>Here's a Quote</template>   <template v-slot:content>“Maecenas ... quis.”</template>   <template v-slot:footer>who said it</template> </custom-card>

Again, notice that each slot only expects text as each card type generates its own HTML elements as defined by the elements() method. If it’s deemed in the future that a different HTML element should be used, it’s a simple matter of updating the component. Building in features for accessibility is another potential future update. Even interaction features can be expanded, based on card types.

The power is in the component that’s in the component

The oddly named <component> element in Vue components was intended for one thing but, as often happens, it has a small side effect that makes it rather useful in other ways. The <component> element was intended to dynamically switch Vue components inside another component on demand. A basic idea of this could be a tab system to switch between components acting as pages; which is actually demonstrated in the Vue documentation. Yet it supports doing the same thing with HTML elements.

This is an example of a new technique shared by a friend that has become s surprisingly useful tool in the belt of Vue features that I’ve used. I hope that this article carries forward the ideas and information about this small feature for you to explore how you might leverage this in your own Vue projects.


The post Dynamically Switching From One HTML Element to Another in Vue appeared first on CSS-Tricks.

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

CSS-Tricks

, , , , ,
[Top]