Tag: Some

Some Performance Links

Just had a couple of good performance links burning a hole in my pocket, so blogging them like a good little blogger.

Web Performance Recipes With Puppeteer

Puppeteer is an Node library for spinning up a copy of Chrome “headlessly” (i.e. no UI) and controlling it. People use it for stuff like taking a screenshot of a website or running integration tests. You can even run it in a Lambda.

Another use case is running synthetic (i.e. not based on real-users) performance tests, like some of these new Web Core Vitals

Addy Osmani lists out a bunch of these “recipes” for measuring certain performance things in Puppeteer. These would be super useful as part of a build process alongside other tests. Did the unit tests pass? Did the integration tests pass? Did the accessibility tests pass? Did the performance metrics tests pass?


BrowserStack SpeedLab

BrowserStack released a thing to measure your site and give you a performance score.

You get the tests back super quick which is cool. I can see how tools like this are good for starting conversations with teams about improving performance.

But… that number seems a little weird. They don’t exactly document how it’s calculated, but it seems to be based on stuff like Time to First Byte (TTFB) and the page load event, which aren’t particularly useful performance metrics.

It’s not bad that this tool exists or anything, but I don’t think it’s for practitioners doing performance work.


5 Common Mistakes Teams Make When Tracking Performance

Karolina Szczur from Calibre documents some common team struggles like, for example, having a team be able to identify real issues from variability noise.

Many people from different backgrounds can view performance dashboards. Not knowing what constitutes a meaningful change that needs investigation can result in false positives, lack of trust in monitoring and cycles spent looking for reasons for performance regressions or upgrades that aren’t there.


Are your JavaScript long tasks frustrating users?

50ms. That’s how long until any particular JavaScript task starts affecting user experience. Might as well track and (ideally) fix them.

When the browser’s main thread hits max CPU for more than 50ms, a user starts to notice that their clicks are delayed and that scrolling the page has become janky and unresponsive. Batteries drain faster. People rage click or go elsewhere.

The post Some Performance Links appeared first on CSS-Tricks.

CSS-Tricks

, ,

Some Typography Links

I just can’t stop opening excellent typography-related articles, which means I need to subject you to blog posts that round them up so I can clean up my open tabs.

Vistaserve is “a grass-roots web hosting initiative hailing from Thornbury, Australia. Inspired by the quirky web of the 90s, we allow users to create home pages, your own little sandbox on the World Wide Web, as it were.” Caitlin & Paul (I think the no-last-name thing is part of the aesthetic) wanted to get the fonts right, which meant removing anti-aliasing (the thing that makes fonts look good on screens!). CSS was no help. Turned out to be quite a journey involving literally rebuilding the fonts.


Thomas Bohm makes the point that the kerning around punctation may require special attention. For example, a question mark needing a little extra space or moving a superscript number away from butting against a letter.

You could do it manually with stuff like   or &hairsp in between characters. But I’m far too lazy for that unless I’m working on a very special piece. Personally, I just cross my fingers that the font I’m using is high quality enough to have thought of and implemented this sort of attention to detail.


I’m sure we’ve all seen, “The quick brown fox jumps over the lazy dog” as a tester string for type, because it uses all the characters in the alphabet. Jonathan Hoefler created some new proofing text that is much more helpful for typographers like him.

That’s deep in the type nerd weeds there. More useful perhaps is another recent post from Jonathan on pairings. I’ve probably read dozens of posts on font pairings in my life, but this one resonates the most.

Some of the most dazzling typographic pairings — and certainly my favorites — are those that use unexpected fonts together. At left, the grey flannel suit that is Tungsten Compressed is paired with crimson silk doublet of the St. Augustin Civilité, a fiery sixteenth century typeface that demands a good foil.


If you’ve got macOS Catalina, you’ve got access to some really nice fonts you might not know about that need to be manually downloaded. Ralf Herrmann has the story on what you get:

You can download the fonts right from Font Book

I get Erik Kennedy’s Learn UI Design newsletter, and he mentions using Calena in it…

Overall, Canela walks this balance between the warmth of human handwriting and stately details. It makes me think of something literary, which is why I used it for project in one of the new video lessons in Learn UI Design.


Mark Boulton has a cool new site: TypeSpecimens.

Type specimens are curious objects. They aim to inspire designers. They are tools with which to make design decisions. They are also marketing material for foundries. This project will dig into specimens from these three perspectives: as artefacts made by and for font designers to evolve type culture; as tools for font users to make decisions about choosing and using type; and as effective marketing tools.

The post Some Typography Links appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

Some Innocent Fun With HTML Video and Progress

The idea came while watching a mandatory training video on bullying in the workplace. I can just hear High School Geoff LOL-ing about a wimp like me have to watch that thing.

But here we are.

The video UI was actually lovely, but it was the progress bar that really caught my attention – or rather the [progress].value. It was a simple gradient going from green to blue that grew as the video continued playing.

If only I had this advice in high school…

I already know it’s possible to create the same sort gradient on the <progress> element. Pankaj Parashar demonstrated that in a CSS-Tricks post back in 2016.

I really wanted to mock up something similar but haven’t played around with video all that much. I’m also no expert in JavaScript. But how hard can that actually be? I mean, all I want to do is get know how far we are in the video and use that to update the progress value. Right?

My inner bully made so much fun of me that I decided to give it a shot. It’s not the most complicated thing in the world, but I had some fun with it and wanted to share how I set it up in this demo.

The markup

HTML5 all the way, baby!

<figure>   <video id="video" src="http://html5videoformatconverter.com/data/images/happyfit2.mp4"></video>   <figcaption>     <button id="play" aria-label="Play" role="button">►</button>     <progress id="progress" max="100" value="0">Progress</progress>     </figcaotion> </figure>

The key line is this:

<progress id="progress" max="100" value="0">Progress</progress>

The max attribute tells us we’re working with 100 as the highest value while the value attribute is starting us out at zero. That makes sense since it allows us to think of the video’s progress in terms of a percentage, where 0% is the start and 100% is the end, and where our initial starting point is 0%.

Styling

I’m definitely not going to get deep into the process of styling the <progress> element in CSS. The Pankaj post I linked up earlier already does a phenomenal job of that. The CSS we need to paint a gradient on the progress value looks like this:

/* Fallback stuff */ progress[value] {   appearance: none; /* Needed for Safari */   border: none; /* Needed for Firefox */   color: #e52e71; /* Fallback to a solid color */ }  /* WebKit styles */ progress[value]::-webkit-progress-value {   background-image: linear-gradient(     to right,     #ff8a00, #e52e71   );   transition: width 1s linear; }  /* Firefox styles */ progress[value]::-moz-progress-bar {   background-image: -moz-linear-gradient(     to right,     #ff8a00, #e52e71   ); }

The trick is to pay attention to the various nuances that make it cross-browser compatible. Both WebKit and Mozilla browsers have their own particular ways of handling progress elements. That makes the styling a little verbose but, hey, what can you do?

Getting the progress value from a video

I knew there would be some math involved if I wanted to get the current time of the video and display it as a value expressed as a percentage. And if you thought that being a nerd in high school gained me mathematical superpowers, well, sorry to disappoint.

I had to write down an outline of what I thought needed to happen:

  • Get the current time of the video. We have to know where the video is at if we want to display it as the progress value.
  • Get the video duration. Knowing the video’s length will help express the current time as a percent.
  • Calculate the progress value. Again, we’re working in percents. My dusty algebra textbook tells me the formula is part / whole = % / 100. In the context of the video, we can re-write that as currentTime / duration = progress value.

That gives us all the marching orders we need to get started. In fact, we can start creating variables for the elements we need to select and figure out which properties we need to work with to fill in the equation.

// Variables const progress = document.getElementById( "progress" );  // Properties // progress.value = The calculated progress value as a percent of 100 // video.currentTime = The current time of the video in seconds // video.duration = The length of the video in seconds

Not bad, not bad. Now we need to calculate the progress value by plugging those things into our equation.

function progressLoop() {   setInterval(function () {     document.getElementById("progress").value = Math.round(       (video.currentTime / video.duration) * 100     );   }); }

I’ll admit: I forgot that the equation would result to decimal values. That’s where Math.round() comes into play to update those to the nearest whole integer.

That actually gets the gradient progress bar to animate as the video plays!

I thought I could call this a win and walk away happy. Buuuut, there were a couple of things bugging me. Plus, I was getting errors in the console. No bueno.

Showing the current time

Not a big deal, but certainly a nice-to-have. We can chuck a timer next to the progress bar and count seconds as we go. We already have the data to do it, so all we need is the markup and to hook it up.

Let’s add a wrap the time in a <label> since the <progress> element can have one.

<figure>   <video controls id="video" src="http://html5videoformatconverter.com/data/images/happyfit2.mp4"></video>   <figcaption>     <label id="timer" for="progress" role="timer"></label>     <progress id="progress" max="100" value="0">Progress</progress>     </figcaotion> </figure>

Now we can hook it up. We’ll assign it a variable and use innerHTML to print the current value inside the label.

const progress = document.getElementById("progress"); const timer = document.getElementById( "timer" );  function progressLoop() {   setInterval(function () {     progress.value = Math.round((video.currentTime / video.duration) * 100);     timer.innerHTML = Math.round(video.currentTime) + " seconds";   }); }  progressLoop();

Hey, that works!

Extra credit would involve converting the timer to display in HH:MM:SS format.

Adding a play button

The fact there there were two UIs going on at the same time sure bugged me. the <video> element has a controls attribute that, when used, shows the video controls, like play, progress, skip, volume, and such. Let’s leave that out.

But that means we need — at the very minimum — to provide a way to start and stop the video. Let’s button that up.

First, add it to the HTML:

<figure>   <video id="video" src="http://html5videoformatconverter.com/data/images/happyfit2.mp4"></video>   <figcaption>     <label id="timer" for="progress" role="timer"></label>     <button id="play" aria-label="Play" role="button">►</button>     <progress id="progress" max="100" value="0">Progress</progress>     </figcaotion> </figure>

Then, hook it up with a function that toggles the video between play and pause on click.

button = document.getElementById( "play" );  function playPause() {    if ( video.paused ) {     video.play();     button.innerHTML = "❙❙";   }   else  {     video.pause();      button.innerHTML = "►";   } }  button.addEventListener( "click", playPause ); video.addEventListener("play", progressLoop);

Hey, it’s still working!

I know it seems weird to take out the rich set of controls that HTML5 offers right out of the box. I probably wouldn’t do that on a real project, but we’re just playing around here.

Cleaning up my ugly spaghetti code

I really want to thank my buddy Neal Fennimore. He took time to look at this with me and offer advice that not only makes the code more legible, but does a much, much better job defining states…

// States const PAUSED = 'paused'; const PLAYING = 'playing';  // Initial state let state = PAUSED;

…doing a proper check for the state before triggering the progress function while listening for the play, pause and click events…

// Animation loop function progressLoop() {   if(state === PLAYING) {     progress.value = Math.round( ( video.currentTime / video.duration ) * 100 );     timer.innerHTML = Math.round( video.currentTime ) + ' seconds';     requestAnimationFrame(progressLoop);   } }  video.addEventListener('play', onPlay); video.addEventListener('pause', onPause); button.addEventListener('click', onClick);

…and even making the animation more performant by replacing setInterval with requestAnimationFrame as you can see highlighted in that same snippet.

Here it is in all its glory!

Oh, and yes: I was working on this while “watching” the training video. And, I aced the quiz at the end, thank you very much. 🤓

The post Some Innocent Fun With HTML Video and Progress appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]

Some Little Improvements to My VS Code Workflow (Workspaces, Icons, Tasks)

I did a little thing the other day that I didn’t know was possible until then. I had a project folder open in VS Code like I always do, and I added another different root folder to the window. I always assumed when you had a project open, it was one top level root folder and that’s it, if you needed another folder elsewhere open, you would open that in another window. But nope!

We kind of have a “duo repo” thing going on at CodePen (one is the main Ruby on Rails app, and one is our microservices), and now I can open them both together:

Multiple folders open at once. This means I don’t need to deal with my symlinks anymore.

Now I can search across both projects and basically just pretend like it’s one big project.

When you do that for the first time and then close the VS Code window, it will ask you if you want to save a “Workspace.” Meh, maybe later, I always thought. I knew what it meant, but I was too lazy to deal with it. It’ll make a file, I thought, and I don’t really have a place for files like that. (I’d avoid the repo itself, just because I don’t want to force my system on anyone else.)

Well, I finally got over it and did it. I chucked all my .code-workspace files into a local folder. They are actually quite useful as files, because I can put the files in my Dock and one-click open my Workspace just how I like it.

Custom Workspace icons

Workspace files have special little icons like this:

The icon is a little generic, but I like it. A document with a little tiny VS Code icon below it.

Since I’m putting these in my Dock, I saw that as a cool opportunity to make them into custom icons! That’ll make it super clear for me and a little more delightful to use since I’ll probably reach for them many times a day.

Taking a little inspiration from the original, I snagged the SVG logo and plopped it on the bottom-right of my project logos.

Changing logos on macOS is as simple as “Get Info” on the file, clicking the logo in that panel, then pasting the image.

Now I can keep them in my Dock and open everything with a single click:

Launch terminal commands when opening a project

Now that I have these really handy one-click icons for opening my projects, I thought, “How cool would it be if it kicked off the commands to start the project too!” Apparently, that’s what Tasks are for, and it wasn’t too hard to set up (thanks, Andrew!). Right next to that settings file, at .vscode/tasks.json, is where I have this:

{   "version": "2.0.0",   "tasks": [     {       "label": "Run Gulp",       "type": "shell",       "command": "gulp",       "task": "default",       "presentation": {         "focus": false,         "panel": "shared",         "showReuseMessage": true,         "clear": true       },       "runOptions": {         "runOn": "folderOpen"       }     }   ] } 

That kicks off the command gulp for me whenever I open this Workspace. I guess you have to run the task once manually (Terminal → Run Task) so that it has the right permissions, then it works from there on out.

Overrides

I don’t think this is specific to Workspaces necessarily, but I really like how you can have a file like .vscode/settings.json in a project folder to override VS Code settings for a particular project.

For example, here on CSS-Tricks, I have a super basic Sass setup where Gulp preprocesses .scss into .css. That’s all fine, but it’s likely that I’ll search for a selector at some point. I don’t need to see it in .css because I’m not working in vanilla CSS. Like ever. I can put this in that settings file, and know that it’s just for this project, rather than all my projects:

{   "search.exclude": {     "**/*.css": true,   } }

The post Some Little Improvements to My VS Code Workflow (Workspaces, Icons, Tasks) appeared first on CSS-Tricks.

CSS-Tricks

, , , , , , ,
[Top]

How (some) good corporate engineering blogs are written

Interesting research from Dan Luu:

… it’s pretty common for my personal blog to get more traffic than the entire corp eng blog for a company with a nine to ten figure valuation and it’s not uncommon for my blog to get an order of magnitude more traffic.

I think this is odd because tech companies in that class often have hundreds to thousands of employees. They’re overwhelmingly likely to be better equipped to write a compelling blog than I am and companies get a lot more value from having a compelling blog than I do.

First, yes. There is a crapload of value in having a good blog (top of funnel traffic, showcasing culture for hiring, establishing industry leadership…) yet so few companies do it well even when they have more than enough resources to do so.

Dan doesn’t just speculate on this, he interviewed people at companies that have actually good engineering blogs: Heap, Segment, and Cloudflare. Then he listed their internal process for blogging. The first step in all three is the same: “Someone has an idea to write a post”. That makes sense, but I would think there is something deeper going on with good blogs: engineers that want to come up with ideas because it is encouraged and incentivized. And then after the ball is rolling, there is a positive feedback loop and as few blockers as possible.

Random observations from me:

  • We recently started using Appcues at CodePen, and it was on our radar at all because people at CodePen read their blog and liked it.
  • While Appcues largely blogs about stuff that is directly related to stuff their software can help with, Logrocket, a software product for tracking JavaScript errors, has a blog that isn’t terribly different than CSS-Tricks. It’s just about front-end everything and every single blog post has a section in it that is a pitch for the product. Looks like they’ve been doing it for about 3 years now, so my hunch is that it works extremely well.
  • All the browser vendors to a pretty good job of blogging overall, but at the same time, feel a bit disjointed. What blog(s) should I be reading for Mozilla/Firefox stuff? I don’t know really. Is it the official looking one? Or the “hacks” one? Or the planet one? Or nightly one? Or the one for releases? Google seems to have the same problem. There isn’t an obvious hub of writing.
  • Stripe has a strong engineering blog, but then take it to another level by producing a fancy publication (Increment) that is both online and in print.

Direct Link to ArticlePermalink

The post How (some) good corporate engineering blogs are written appeared first on CSS-Tricks.

CSS-Tricks

, , , , ,
[Top]

Some Typography Links

I just can’t stop bookmarking great links related to typography. I’m afraid I’m going to have to subject you, yet again, to a bunch of them all grouped up. So those of you that care about web type stuff, enjoy.


I know there are lots of good reasons to be excited about variable fonts. The design possibilities of endless variations in one file is chief among them. But I remain the most excited about the performance benefits. Having a single file that elegantly handles the thicker weights (for bolding) and italics is so cool. I can’t wait to wave my fist saying back in my day we had to load multiple files for our font variations!

Mandy Michael digs into the performance implications in a deeper way than just reducing the number of requests.

Even if you consider the slightly larger file sizes, when combined with improved font compression formats like WOFF2, font subsetting and font loading techniques like font-display: swap; we end up in a situation where we can still get smaller overall font file sizes as well as a significant increase in stylistic opportunity.


Anna Monus did some variable font performance testing as well, evaluating the extreme case of loading 12 variations of a font against a variable font. Even though the copy of the variable font she had for Roboto was massive (over 1MB), there was a perf gain compared against loading 12 variations.


Roboto is on Google Fonts, of course, and it’s got the #1 position by far. But Google Fonts has Inter now, and I’d expect that leap up in the charts as it’s got a style that everyone seems to like and can work with just about anything.


Seeing a variable font control a smiley face is never not gonna make me happy. Don’t miss that first face-ness slider, lollllz.


Klint Finley on the proliferation of high-quality open-source fonts for WIRED. Sometimes they are backed by companies with thick wallets, which makes sense. But the motivation for doing it varies. Sometimes quality is the goal. Like open-source anything, lots of contributions, can, if handled well, lead to a better product. But open-source doesn’t always mean there isn’t a business possibility, and if not, not everyone cares about turning a profit on everything.


Speaking of open-source fonts, Collletttivo is an open-source font foundry with a good dozen typefaces, including a variable font one. It’s a super fun site to explore with the little fake windows you open up and move around.


There’s a new mac app called FontGoggles for poking into a font file and taking a look at what it offers. Seems like that would be easy but it really isn’t. I like that it supports WOFF/2 as that’s pretty much all we deal with on the web.

Also, remember there is a website that looks around in font files with the best name ever.


Font Match allows you to put fonts on top of each other for comparisons. Seems like it’s more for large type and comparing their features, while Font style matcher is more about comparing paragraph text.

In fact, using Font style matcher to make a perfect font fallback is one of my all-time favorite CSS-Tricks. Sssshh… don’t tell anybody but I’m compiling those all-time favorites into a book, like this chapter. You’d have to subscribe to read it, because that’s kind of the point: I’d like to sell the book. So if you happen to subscribe now, there is stuff to read there, but you’d be a very early supporter for the rest of it.

The post Some Typography Links appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

Why Do Some HTML Elements Become Deprecated?

The internet has been around for a long while, and over time we’ve changed the way we think about web design. Many old techniques and ways of doing things have gotten phased out as newer and better alternatives have been created, and we say that they have been deprecated.

Deprecated. It’s a word we use and see often. But have you stopped to think about what it means in practice? What are some examples of deprecated web elements, and why don’t we use them any more?

What is deprecation?

In everyday English, to “deprecate” something is to express disapproval of it. For example, you might be inclined to deprecate a news story you don’t like.

When we’re speaking in a technical sense, however, deprecation is the discouragement of use for an old feature. Often, the old feature remains functional in the interests of backward compatibility (so legacy projects don’t break). In essence, this means that you can technically still do things the legacy way. It’ll probably still work, but maybe it’s better to use the new way. 

Another common scenario is when technical elements get deprecated as a prelude to their future removal (which we sometimes call “sunsetting” a feature). This provides everybody time to transition from the old way of working to the new system before the transition happens. If you follow WordPress at all, they recently did this with their radically new Gutenberg editor. They shipped it, but kept an option available to revert to the “classic” editor so users could take time to transition. Someday, the “classic” editor will likely be removed, leaving Gutenberg as the only option for editing posts. In other words, WordPress is sunsetting the “classic” editor.

That’s merely one example. We can also look at HTML features that were once essential staples but became deprecated at some point in time.

Why do HTML elements get deprecated?

Over the years, our way of thinking about HTML has evolved. Originally, it was an all-purpose markup language for displaying and styling content online.

Over time, as external stylesheets became more of a thing, it began to make more sense to think about web development differently — as a separation of concerns where HTML defines the content of a page, and CSS handles the presentation of it.

This separation of style and content brings numerous benefits:

  • Avoiding duplication: Repeating code for every instance of red-colored text on a page is unwieldy and inefficient when you can have a single CSS class to handle all of it at once. 
  • Ease of management: With all of the presentation controlled from a central stylesheet, you can make site-wide changes with little effort.
  • Readability: When viewing a website’s source, it’s a lot easier to understand the code that has been neatly abstracted into separate files for content and style. 
  • Caching: The vast majority of websites have consistent styling across all pages, so why make the browser download those style definitions again and again? Putting the presentation code in a dedicated stylesheet allows for caching and reuse to save bandwidth. 
  • Developer specialization: Big website projects may have multiple designers and developers working on them, each with their individual areas of expertise. Allowing a CSS specialist to work on their part of the project in their own separate files can be a lot easier for everybody involved. 
  • User options: Separating styling from content can allow the developer to easily offer display options to the end user (the increasingly popular ‘night mode’ is a good example of this) or different display modes for accessibility. 
  • Responsiveness and device independence: separating the code for content and visual presentation makes it much easier to build websites that display in very different ways on different screen resolutions.

However, in the early days of HTML there was a fair amount of markup designed to control the look of the page right alongside the content. You might see code like this: 

<center><font face="verdana" color="#2400D3">Hello world!</font></center>

…all of which is now deprecated due to the aforementioned separation of concerns. 

Which HTML elements are now deprecated?

As of the release of HTML5, use of the following elements is discouraged:

  • <acronym> (use <abbr> instead)
  • <applet> (use <object>)
  • <basefont> (use CSS font properties, like font-size, font-family, etc.)
  • <big> (use CSS font-size)
  • <center> (use CSS text-align)
  • <dir> (use <ul>)
  • <font> (use CSS font properties)
  • <frame> (use <iframe>)
  • <frameset> (not needed any more)
  • <isindex> (not needed any more)
  • <noframes> (not needed any more)
  • <s> (use text-decoration: line-through in CSS)
  • <strike> (use text-decoration: line-through in CSS)
  • <tt> (use <code>)

There is also a long list of deprecated attributes, including many elements that continue to be otherwise valid (such as the align attribute used by many elements). The W3C has the full list of deprecated attributes.

Why don’t we use table for layouts any more?

Before CSS became widespread, it was common to see website layouts constructed with the <table> element. While the <table> element is not deprecated, using them for layout is strongly discouraged. In fact, pretty much all HTML table attributes that were used for layouts have been deprecated, such as cellpadding, bgcolor and width

At one time, tables seemed to be a pretty good way to lay out a web page. We could make rows and columns any size we wanted, meaning we could put everything inside. Headers, navigation, footers… you name it!

That would create a lot of website code that looked like this:

<table border="0" cellpadding="0" cellspacing="0" width="720">   <tr>     <td colspan="10"><img name="logobar" src="logobar.jpg" width="720" height="69" border="0" alt="Logo"></td>   </tr>   <tr>     <td rowspan="2" colspan="5"><img name="something" src="something.jpg" width="495" height="19" border="0" alt="A picture of something"></td>     <td>Blah blah blah!</td>     <td colspan="3">    <tr>   <!--  and so on --> </table>

There are numerous problems with this approach:

  • Complicated layouts often end up with tables nested inside other tables, which creates a headache-inducing mess of code. Just look at the source of any email newsletter.
  • Accessibility is problematic, as screen readers tend to get befuddled by the overuse of tables.
  • Tables are slow to render, as the browser waits for the entire table to download before showing it on the screen.
  • Responsible and mobile-friendly layouts are very difficult to create with a table-based layout. We still have not found a silver bullet for responsive tables (though many clever ideas exist).

Continuing the theme of separating content and presentation, CSS is a much more efficient way to create the visual layout without cluttering the code of the main HTML document. 

So, when should we use<table>? Actual tabular data, of course! If you need to display a list of baseball scores, statistics or anything else in that vein, <table> is your friend. 

Why do we still use <b> and <i> tags?

“Hang on just a moment,” you might say. “How come bold and italic HTML tags are still considered OK? Aren’t those forms of visual styling that ought to be handled with CSS?”

It’s a good question, and one that seems difficult to answer when we consider that other tags like <center> and <s> are deprecated. What’s going on here?

The short and simple answer is that <b> and <i> would probably have been deprecated if they weren’t so widespread and useful. CSS alternatives seem somewhat unwieldy by comparison:

<style>   .emphasis { font-weight:bold } </style>      This is a <span class="emphasis">bold</span> word!  This is a <span style="font-weight:bold">bold</span> word!  This is a <b>bold</b> word!

The long answer is that these tags have now been assigned some semantic meaning, giving them value beyond pure visual presentation and allowing designers to use them to confer additional information about the text they contain.

This is important because it helps screen readers and search crawlers better understand the purpose of the content wrapped in these tags. We might italicize a word for several reasons, like adding emphasis, invoking the title of a creative work, referring to a scientific name, and so on. How does a screen reader know whether to place spoken emphasis on the word or not?

<b> and <i>have companions, including <strong>, <em> and <cite>. Together, these tags make the meaning context of text clearer:

  • <b> is for drawing attention to text without giving it any additional importance. It’s used when we want to draw attention to something without changing the inflection of the text when it is read by a screen reader or without adding any additional weight or meaning to the content for search engines.
  • <strong> is a lot like <b> but signals the importance of something. It’s the same as changing the inflection of your voice when adding emphasis on a certain word.
  • <i> italicizes text without given it any additional meaning or emphasis. It’s perfect for writing out something that is normally italicized, like the scientific name of an animal.
  • <em> is like <i> in that it italicizes text, but it provides adds additional emphasis (hence the tag name) without adding more importance in context. (‘I’m sure I didn’t forget to feed the cat’). 
  • <cite> is what we use to refer to the title of a creative work, say a movie like The Silence of the Lambs. This way, text is styled but doesn’t affect the way the sentence would be read aloud. 

In general, the rule is that <b> and <i> are to be used only as a last resort if you can’t find anything more appropriate for your needs. This semantic meaning allows <b> and <i> to continue to have a place in our modern array of HTML elements and survive the deprecation that has befallen other, similar style tags.

On a related note, <u> — the underline tag — was at one time deprecated, but has since been restored in HTML5 because it has some semantic uses (such as annotating spelling errors).

There are many other HTML elements that might lend styling to content, but primarily serve to provide semantic meaning to content. Mandy Michael has an excellent write-up that covers those and how they can be used (and even combined!) to make the most semantic markup possible.

Undead HTML attributes

Some deprecated elements are still in widespread use around the web today. After all, they still work — they’re just discouraged.

This is sometimes because word hasn’t gotten around that that thing you’ve been using for ages isn’t actually the way it’s done any more. Other times, it’s due to folks who don’t see a compelling reason to change from doing something that works perfectly well. Hey, CSS-Tricks still uses the teletype element for certain reasons.

One such undead HTML relic is the align attribute in otherwise valid tags, especially images. You may see <img> tags with a border attribute, although that attribute has long been deprecated. CSS, of course, is the preferred and modern method for that kind of styling presentation.


Staying up to date with deprecation is key for any web developer. Making sure your code follows the current recommendations while avoiding legacy elements is an essential best practice. It not only ensures that your site will continue to work in the long run, but that it will play nicely with the web of the future.

Questions? Post a comment! You can also find me over at Angle Studios where I work.

The post Why Do Some HTML Elements Become Deprecated? appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]

Just Dropping Some Type Links

I’ve had a bunch of tabs open that just so happen to all be related to typography, so I figured I’d give myself the mental release of closing them by blogging them. How’s that for a blog post format for ya: whatever random tabs you’ve had open for far too long.

  • Times New Roman is popular on the web in the sense that it’s a default font installed on most computers and safe to use without having to load any web fonts. But it’s also the default font that (all?) web browsers use if you don’t declare a font-family at all so, in that sense, it sometimes feels like a site is broken on accident when Times is used. Typewolf has a nice list of alternatives if you like the vibe but need something different.
  • Speaking of Times, err, The New York Times profiles TypeThursday with a pretty funny correction where they got the typeface name wrong.
  • In the last month of 2019, Tyopgraphica published their favorite typefaces of 2018. Fern grabs me.
  • Una Kravets has a “designing in the browser” video about typography on the Chrome Developers channel on YouTube. About 11 minutes in, she gets into variable fonts which are just incredible. I know they are capable of all sorts of amazing things (even animation), but I remain the most excited about performance: loading one font and having tons of design control.
  • Florens Verschelde’s “A short history of body copy sizes on the Web” gets into how typical font size usage has crept up and up over the years.
  • Alina Sava makes the argument that font licensing is ill. Primarily: pricing web fonts based on page views. As someone who works on some high-traffic / fairly-low-profit websites, it’s hard to disagree.
  • Matej Latin covers five fonts designed for coding that have ligatures. Ya know, instead of != you get , but only visually rather than actually changing the characters that are used as I did there. Ligatures are a neat trick to use (another trick: ligatures as icons), but Matthew Butterick says “hell no”: The ligature introduces an ambiguity that wasn’t there before. I find it notable that Operator Mono chose not to go there. I feel like I overheard a discussion about it once but can’t dig it up now. I know there is a way to add them, and it’s a little surprising to me that’s legal.
  • Trent popped some new fonts on his blog and shared his font shopping list.
  • You might have noticed some new fonts around here on CSS-Tricks as well, as of a few weeks ago. I just wanted to freshen up the place as I was getting sick of looking at system fonts (they started looking bad to me on Catalina, which is something Andy Baio pointed out is a Chrome Bug, but still). The CSS-Tricks logo has long been Gotham Rounded, so I went back to Hoefler&Co. for the font choices here to kinda stay in the family. The headers use Ringside, monospace content uses Operator Mono, and the body uses Sentinel.

The post Just Dropping Some Type Links appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]

Some CSS Grid Strategies for Matching Design Mockups

The world of web development has always had a gap between the design-to-development handoff. Ambitious designers want the final result of their effort to look unique and beautiful (and true to their initial vision), whereas many developers find more value in an outcome that is consistent, dependable, and rock solid (and easy to code). This dynamic can result in sustained tension between the two sides with both parties looking to steer things their own way.

While this situation is unavoidable to some extent, new front-end technology can play a role in bringing the two sides closer together. One such technology is CSS grid. This post explores how it can be used to write CSS styles that match design layouts to a high degree of fidelity (without the headache!).

A common way that designers give instructions to front-end developers is with design mockups (by mockups, we’re talking about deliverables that are built in Sketch, XD, Illustrator, Photoshop etc). All designers work differently to some degree (as do developers), but many like to base the structure of their layouts on some kind of grid system. A consistent grid system is invaluable for communicating how a webpage should be coded and how it should respond when the size of the user’s screen differs from the mockup. As a developer, I really appreciate designers who take the trouble to adopt a well thought-out grid system.

A 12-column layout is particularly popular, but other patterns are common as well. Software like Sketch and XD makes creating pages that follow a preset column layout pretty easy — you can toggle an overlay on and off with the click of a button.

A grid layout designed in Sketch (left) and Adobe XD (right)

Once a grid system is implemented, most design elements should be positioned squarely within it. This approach ensures that shapes line up evenly and makes for a more appealing appearance. In addition to being visually attractive, a predictable grid gives developers a distinct target to shoot for when writing styles.

Unfortunately, this basic pattern can be deceptively difficult to code accurately. Frameworks like Bootstrap are often used to create grid layouts, but they come with downsides like added page weight and a lack of fine-grained control. CSS grid offers a better solution for the front-end perfectionist. Let’s look at an example.

A 14-column grid layout

The design above is a good application for grid. There is a 14-column pattern with multiple elements positioned within it. While the boxes all have different widths and offsets, they all adhere to the same grid. This layout can be made with flexbox — and even floats — but that would likely involve some very specific math to get a pixel-perfect result across all breakpoints. And let’s face it: many front-end developers don’t have the patience for that. Let’s look at three CSS grid layout strategies for doing this kind of work more easily.

Strategy 1: A basic grid

See the Pen
Basic Grid Placement
by chris geel (@RadDog25)
on CodePen.

The most intuitive way to write an evenly spaced 12-column layout would probably be some variation of this. Here, an outer container is used to control the outside gutter spacing with left and right padding, and an inner row element is used to restrain content to a maximum width. The row receives some grid-specific styling:

display: grid; grid-template-columns: repeat(12, 1fr); grid-gap: 20px;

This rule defines the grid to consist of 12 columns, each having a width of one fractional unit (fr). A gap of 20px between columns is also specified. With the column template set, the start and end of any child column can be set quite easily using the grid-column property. For example, setting grid-column: 3/8 positions that element to begin at column three and span five columns across to column eight.

We can already see a lot of value in what CSS grid provides in this one example, but this approach has some limitations. One problem is Internet Explorer, which doesn’t have support for the grid-gap property. Another problem is that this 12-column approach does not provide the ability to start columns at the end of gaps or end columns at the start of gaps. For that, another system is needed.

Strategy 2: A more flexible grid

See the Pen
More Flexible Grid Placement
by chris geel (@RadDog25)
on CodePen.

Although grid-gap may be a no go for IE, the appearance of gaps can be recreated by including the spaces as part of the grid template itself. The repeat function available to grid-template-columns accepts not just a single column width as an argument, but repeating patterns of arbitrary length. To this end, a pattern of column-then-gap can be repeated 11 times, and then the final column can be inserted to complete the 12-column / 11 interior gap layout desired:

grid-template-columns: repeat(11, 1fr 20px) 1fr;

This gets around the IE issue and also allows for columns to be started and ended on both columns or gaps. While being a nice improvement over the previous method, it still has some room to grow. For example, what if a column was to be positioned with one side spanning to the outer edge of the screen, and the other fit within the grid system? Here’s an example:

A grid Layout with an that’s item flush to the outer edge

In this layout, the card (our left column) begins and ends within the grid. The main image (our right column) begins within the grid as well, but extends beyond the grid to the edge of the screen. Writing CSS for this can be a challenge. One approach might be to position the image absolutely and pin it to the right edge, but this comes with the downside of taking it out of the document flow (which might be a problem if the image is taller than the card). Another idea would be to use floats or flexbox to maintain document flow, but this would entail some tricky one-off calculation to get the widths and spacing just right. Let’s look at a better way.

Strategy 3: An even more flexible grid

See the Pen
Right Edge Aligned image with grid
by chris geel (@RadDog25)
on CodePen.

This technique builds on the idea introduced in the last revision. Now, instead of having the grid exist within other elements that define the gutter sizes and row widths, we’re integrating those spaces with the grid’s pattern. Since the gutters, columns, and gaps are all incorporated into the template, child elements can be positioned easily and precisely on the grid by using the grid-column property.

$ row-width: 1140px; $ gutter: 30px; $ gap: 20px; $ break: $ row-width + 2 * $ gutter; $ col-width-post-break: ($ row-width - 11 * $ gap) / 12;    .container {   display: grid;   grid-template-columns: $ gutter repeat(11, calc((100% - 2 * #{$ gutter} - 11 * #{$ gap})/12) #{$ gap}) calc((100% - 2 * #{$ gutter} - 11 * #{$ gap})/12) $ gutter;   @media screen and (min-width: #{$ break}) {     grid-template-columns: calc(0.5 * (100% - #{$ row-width})) repeat(11, #{$ col-width- post-break} #{$ gap}) #{$ col-width-post-break} calc(0.5 * (100% - #{$ row-width}));   } }

Yes, some math is required to get this just right. It’s important to have the template set differently before and after the maximum width of the row has been realized. I elected to use SCSS for this because defining variables can make the calculation a lot more manageable (not to mention more readable for other developers). What started as a 12-part pattern grew to a 23-part pattern with the integration of the 11 interior gaps, and is now 25 pieces accounting for the left and right gutters.

One cool thing about this approach is that it can be used as the basis for any layout that adheres to the grid once the pattern is set, including traditionally awkward layouts that involve columns spanning to outside edges. Moreover, it serves as a straightforward way to precisely implement designs that are likely to be handed down in quality mockups. That is something that should make both developers and designers happy!

There are a couple of caveats…

While these techniques can be used to crack traditionally awkward styling problems, they are not silver bullets. Instead, they should be thought of as alternative tools to be used for the right application.

One situation in which the second and third layout patterns are not appropriate are layouts that require auto placement. Another would be production environments that need to support browsers that don’t play nice with CSS grid.

The post Some CSS Grid Strategies for Matching Design Mockups appeared first on CSS-Tricks.

CSS-Tricks

, , , , ,
[Top]

Some Things You Oughta Know When Working with Viewport Units

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

Summarized in this graphic:

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

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

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

I use this a lot:

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

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

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

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

html, body {    height: 100%; }

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

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

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

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

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

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

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

CSS-Tricks

, , , , , ,
[Top]