Collective #508

Front-end Developer Handbook 2019 Cody Lindley wrote this guide that outlines and discusses the practice of front-end engineering, how to learn it and what tools are used when practicing it in 2019. Check it out Our Sponsor Visual Composer founder had an AMA Read more

Table Design Patterns On The Web

dreamt up by webguru in Uncategorized | Comments Off on Table Design Patterns On The Web

Table Design Patterns On The Web

Table Design Patterns On The Web

Huijing Chen



Tables are a design pattern for displaying large amounts of data in rows and columns, making them efficient for doing comparative analysis on categorical objects. Tables have been used for this purpose as early as the 2nd century and when the world started to go digital, tables came along with us.

It was inevitable that the web would support the display of data in a tabular format. HTML tables present tabular data in a semantic and structurally appropriate manner. However, the default styles on HTML tables are not exactly the most aesthetically pleasing thing you’ve ever seen. Depending on the desired visual design, some effort was required on the CSS front to prettify those tables. A decade ago, an article with the “Top 10 CSS Table Designs” was published on Smashing Magazine, and it still continues to get a lot of traffic to this day.

The web has evolved a lot over the past decade, and it’s more convenient than ever to make your site or application adapt to the viewport it is viewed in. That being said, we have to continue to make considered design choices that do not compromise on accessibility. Since tables don’t seem to be falling out of favor anytime soon, let’s see how tables can be created on the web in 2019.

CSS-Only Options

If your dataset isn’t that large, and features like pagination and sorting are not necessary, then consider a JavaScript-free option. You can get some pretty nice results that work well on a whole gamut of screen sizes without the added weight of a large library.

Unfortunately, without the help of JavaScript for some DOM manipulation on the accessibility front, we only have a handful of CSS-only options. But for small data sets, they are often sufficient.

Option 1: Do Nothing

We’re going to start off with a low-effort scenario. If your data fits in a table with only a few columns and lots of rows, then such a table is pretty much mobile-ready to begin with.


A table with few columns and many rows displayed on narrow and wide screens
A table with a few columns and many rows displayed on narrow and wide screens (Large preview)

The issue you’d have is probably having too much room on wider screens, so it might be advisable to “cap” the maximum width of the table with a max-width while letting it shrink as necessary on a narrow screen.

See the Pen Table #1: Few columns, many rows by Chen Hui Jing (@huijing) on CodePen.

This sort of a pattern works best if your data itself isn’t lines and lines of text. If they are numeric, or short phrases, you can probably get away with not doing much.

Option 2: Style The Scroll

David Bushell wrote up his technique for responsive tables back in 2012, which involved invoking overflow and allowing users to scroll to see more data. One could argue that this isn’t exactly a responsive solution, but technically, the container is responding to the width of the viewport.


Style the table in a way that users know there’s more data on scroll.
When styling tables, allow users to scroll to see more data. (Large preview)

Let’s look at the “basic” overflow first. Imagine me using air-quotes around basic, because the styling for the scrolling shadows is anything but. Still, in this instance, “basic” refers to the fact that the table does not transform in any way.

See the Pen Table #3: Style the scroll (basic) by Chen Hui Jing (@huijing) on CodePen.

This technique for doing scrolling shadows comes from Roma Komarov and Lea Verou riffing off each other’s ideas to create magic. It hinges on using multiple gradients (linear and radial) as background images on the containing element, and using background-attachment: local to position the background relative to its contents.

What’s nice about this technique is that for browsers that don’t support scrolling shadows, you can still scroll the table as per normal. It doesn’t break the layout at all.

Another scrolling option would be to flip the table headers from a row configuration to a column configuration, while applying a horizontal scroll onto the <tbody> element’s contents. This technique leverages Flexbox behavior to transform the table’s rows into columns.

By applying display: flex to the table, it makes the <thead> and <tbody> both flex children, which are by default laid out next to each other on the same flex line.

We also make the <tbody> element a flex container, thus making all the <tr> elements within it flex children laid out in a single flex line as well. Lastly, every table cell has to have their display set to block instead of the default table-cell.

The advantage of this technique is that the headers are always in view, like a fixed header effect, so users don’t lose context as they scroll through the columns of data. One thing to take note of is that this technique results in a discrepancy of the visual and source order, and this makes things slightly unintuitive.

Sprinkle On Some JavaScript

As mentioned earlier, layout options that involving morphing the table by modifying display values sometimes have negative implications for accessibility, which require some minor DOM manipulation to rectify.

In addition, there are a number of user experience tips when it comes to designing data tables from Andrew Coyle, including features like pagination, sorting, filtering, and so on (features that do require some JavaScript to enable).

If you’re working with a relatively simpler dataset, perhaps you would like to write your own functions for some of these features.

Rows To Blocks, With Accessibility Fix

As far as I know of, this responsive data table technique came about from the CSS-Tricks article “Responsive Data Tables” by Chris Coyier back in 2011. It has since been adapted and expanded upon by many others.

The gist of this technique is to make use of a media query to switch the display property of the table element and its children to block on a narrow viewport.


Table rows become individual stacked blocks on narrow viewports
Collapsing rows into blocks (Large preview)

On a narrow screen, the table headers are visually hidden, but still exist in the accessibility tree. By applying data attributes to the table cells, we can then display labels for the data via CSS, while keeping the content of the label in the HTML. Please refer to the CodePen below for how the mark-up and styles look like:

See the Pen Table #2: Rows to blocks by Chen Hui Jing (@huijing) on CodePen.

The original method applies a width on the pseudo-element displaying the label text, but that means you’d need to know the amount of space your label needed to begin with. The above example uses a slightly different approach, whereby the label and data are each on opposite sides of their containing block.

We can achieve such an effect via auto-margins in a flex formatting context. If we set the display property for each <td> element to flex, because pseudo-elements generate boxes as if they were immediate children of their originating element, they become flex children of the <td>.

After that, it’s a matter of setting margin-right: auto on the pseudo-element to push the cell’s content to the far end edge of the cell.

Another approach doing the narrow viewport layout is using a combination of Grid and display: contents. Please note that display: contents in supporting browsers has issues with accessibility at the moment, and this method shouldn’t be used in production until those bugs are fixed.

But maybe you’re reading this after those bugs have been resolved, in that case, here’s an alternative layout option.

See the Pen Table #2: Rows to blocks (alt) by Chen Hui Jing (@huijing) on CodePen.

Each <tr> element is set to display: grid, and each <td> element is set to display: contents. Only the immediate children of a grid container participate in a grid formatting context; in this case, it’s the <td> element.

When display: contents is applied to the <td>, it gets “replaced” by its contents, in this case, the pseudo-element and the <span> within the <td> become the grid children instead.

What I like about this approach is the ability to use max-content to size the column of pseudo-elements, ensuring that the column will always be the width of the longest label, without us having to manually assign a width value for it.

In future, when the sizing values of min-content, max-content and fit-content (covered by the CSS Intrinsic & Extrinsic Sizing Module Level 3) are supported as general width and height values, we’ll have even more options for laying things out.

The downside to this approach is you do need that additional <span> or <p> around the content in your table cell if it didn’t have one already, otherwise, there’d be no way to apply styles to it.

Simple Pagination

This example shows a basic pagination implementation that was modified off this CodePen by Gjore Milevski to paginate on table rows instead of divs. It is an extension of the “style the scroll” example discussed in the previous section.

See the Pen Table #4: Simple pagination by Chen Hui Jing (@huijing) on CodePen.

From a layout perspective, Flexbox comes in very handy for positioning the pagination elements across various viewport sizes. Different project designs will have different requirements, but the versatility of Flexbox should allow you to cater for these differences accordingly.

In this case, the pagination is centred on the page and above the table. The controls for navigating backward and forward are placed on either side of the page indicators on wider screens, but all four appear above the page indicators on narrow screens.

We can do this by levaraging the order property. Visual reordering of content should always be done with consideration because this property does not change the source order — only how it appears on screens.

Simple Sorting

This example shows a basic sorting implementation modified off this code snippet by Peter Noble to cater for both text and numerals:

See the Pen #Table 5: Simple sorting by Chen Hui Jing (@huijing) on CodePen.

It would be useful to have some sort of indicator of which column is currently being sorted and in what order. We can do that with the addition of CSS classes which can then be styled however you want. In this case, the indicator symbols are pseudo-elements that are toggled when the target header is clicked.

This example is a basic filtering functionality that iterates through all the textual content of each table cell and applies a CSS class to hide all rows that do not match the search input field.

See the Pen Table #6: Simple filtering by Chen Hui Jing (@huijing) on CodePen.

Such an implementation is relatively naive, and if your use case calls for it, it might make sense to search per column instead. In that scenario, it might be a good idea to have each input field as part of the table in their respective columns.

Let A Library Handle It

The above JavaScript snippets serve to demonstrate how tables with larger amounts of data can be enhanced to make life easier for users of those tables. But with really large datasets, it might probably make sense to use an existing library to manage your large tables.

The column toggle pattern is one whereby non-essential columns are hidden on smaller screens. Normally, I’m not a fan of hiding content simply because the viewport is narrow, but this approach by Maggie Costello Wachs of Filament Group resolves that qualm of mine by providing a drop-down menu which allows users to toggle the hidden columns back into view.

The above article was published back in 2011, but Filament Group has since developed a full suite of responsive table plugins known as Tablesaw, which includes features like sorting, row selection, internationalization and so on.

The column toggle feature in TableSaw also no longer depends on jQuery, unlike the examples from the original article. Tablesaw is one of the only libraries I could find that does not have a dependency on jQuery at the moment.

Wrapping Up

There is a myriad of table design patterns out there, and which approach you pick depends heavily on the type of data you have and the target audience for that data. At the end of the day, tables are a method for the organization and presentation of data. It is important to figure out which information matters most to your users and decide on an approach that best serves their needs.

Further Reading

Smashing Editorial
(ra, il)

Source: Smashing Magazine, Table Design Patterns On The Web

Designing Emotional Interfaces Of The Future

dreamt up by webguru in Uncategorized | Comments Off on Designing Emotional Interfaces Of The Future

Designing Emotional Interfaces Of The Future

Designing Emotional Interfaces Of The Future

Gleb Kuznetsov



Emotions play a vital role in our decision-making process. One second of emotion can change the whole reality for people engaging with a product.

Humans are an emotionally driven species; we choose certain products not because of what makes sense, but because of how we think they will make us feel. The interfaces of the future will use the concept of emotions within the foundation of product design. The experiences that people use will be based both on intellectual quotient (IQ) and emotional quotient (EQ).

This article is my attempt to look into the future and see what interfaces we will design in the next ten years. We’ll be taking a closer look at the three mediums for interaction:

  1. Voice
  2. Augmented Reality (AR)
  3. Virtual Reality (VR)

Developing For Virtual Reality

It’s not that difficult to create content for VR nowadays. Still, if you’re looking for a way to get a better understanding of VR development, working a demo project can help. Learn more →

Practical Examples Of Future Emotional Interfaces

How will interfaces look like in the future? Even though we do not have an answer to this question just yet, we can discuss what characteristics interfaces might have. In my opinion, I’m sure that we will eventually move away from interfaces full of menus, panels, buttons, and move towards more ‘natural interfaces’, i.e. interfaces that extend our bodies. The interfaces of the future will not be locked in a physical screen, but instead they will use the power of all five senses. Because of that, they will require a less learning curve — ideally, no learning curve at all.

The Importance Of EQ Emotional Intelligence In Business

Apart from making the experience more natural and reducing the learning curve, designing for emotion has another benefit for product creators: it improves user adoption of the product. It’s possible to use humans’ ability to act on emotions to create better user engagement.

Voice Interfaces That Feel Real

Products that use voice as the primary interface are becoming more and more popular. Many of us use Amazon Echo and Apple Siri for daily routine activities such as setting an alarm clock or making an appointment. But a majority of voice interaction systems available on the market today still have a natural limitation: they do not take user emotions into account. As a result, when users interact with products like Google Now, they have a strong sense of communicating with a machine — not a real human being. The system responds predictably, and their responses are scripted. It’s impossible to have a meaningful dialogue with such a system.

But there are some completely different systems available on the market today. One of them is Xiaoice, a social chatbot application. This app has an emotional computing framework at its core; the app is built on the idea that it’s essential to establish an emotional connection with the user first. Xiaoice can dynamically recognize emotion and engage the user throughout long conversations with relevant responses. As a result, when users interact with Xiaoice they feel like they’re having a conversation with a real human being.

The limitation of Xiaoice is that it’s a text-based chat app. It’s evident that you can achieve a more powerful effect by making voice-based interactions (the human voice has different characteristics such as a tone that can convey a powerful spectrum of emotions).

Many of us have seen the power of voice-based interactions in the film “Her” (2013). Theodore (the main character played by Joaquin Phoenix) fell in love with Samantha (a sophisticated OS). This also makes us believe that one of the primary purposes of voice-based systems of the future will be a virtual companion to users. The most interesting thing about this film is that Theodore did not have a visual image of the Samantha — he only had her voice. To build that kind of intimacy, it’s essential to generate responses that reflect a consistent personality. This will make the system both predictable and trustworthy.

Technology is still a long away from a system like Samantha, but I believe that voice-first multimodal interfaces will be the next chapter in the evolution of voice-enabled interfaces. Such interfaces will use voice as a primary way of interaction and provide additional information in a context that creates and builds a sense of connection.

An example of a voice interface designed for Brain.ai (Image credit: Gleb Kuznetsov)

The Evolution Of AR Experience

Augmented Reality (AR) is defined as a digital overlay on top of the real world and transforms the objects around us into interactive digital experiences. Our environment becomes more ‘intelligent’ and users have an illusion of ‘tangible’ objects on the tips of their fingers, which establishes a deeper connection between a user and a product (or content).

Reimagine Existing Concepts Using AR

The unique aspect of AR is that it gives us an extraordinary ability to physically interact with digital content. It allows us to see things that we could not see before and this helps us learn more about the environment around us. This AR property helps designers to create new level experiences using familiar concepts.

For example, by using mobile AR, it’s possible to create a new level of in-flight experience that allows a passenger to see detailed information about her class or current flight progress:

AR in flight experience for Airbus A380. (Image credit: Gleb Kuznetsov)

AR helps us find our way through spaces and get the required information at a glance. For example, AR can be used to create rich contextual hints for your current location. The technology known as SLAM (Simultaneous Localization And Mapping) is perfect for this. SLAM allows real-time mapping of an environment and also makes it possible to place multimedia content into the environment.

There are massive opportunities for providing value to users. For example, users can point their devices at a building and learn more about it right there on their screens. It significantly reduces the effort and allows for an emotional experience of ease by allowing navigation and access.

Providing additional information in context (Image credit: Gleb Kuznetsov)

The environment around us (such as walls or floors) can become a scene for interactivity in ways that used to be limited to our smartphones and computers.

The concept that you see below does just that; it uses a physical object (white wall) as a canvas for the content usually delivered using a digital device:

The concept of interactive walls — a digital overlay on top of the real world. (Image credit: Gleb Kuznetsov)

Avoiding Information Overload

Many of us saw the video called “HYPER-REALITY”. In this video, the physical and digital worlds have merged, and the user is overwhelmed with a vast amount of information.

Technology allows us to display several different objects at the same time. When it’s misused, it can easily cause overload.

Information overload is a serious issue that has a negative impact on user experience and avoiding it will be one of the goals of designing for AR. Well-designed apps will filter out elements that are irrelevant to users using the power of AI.

Advanced Personalization

Personalization in digital experience happens when the system curates the content or functionality to users’ needs and expectations in real time. Many modern mobile apps and websites use the concept of personalization to provide relevant content. For example, when you visit Netflix, the list of movies you see is personalized based on your interests.

AR glasses allow creating a new level of personalization, i.e. an ‘advanced’ level of personalization. Since the system ‘sees’ what the user sees, it’s possible to utilize this information to make a relevant recommendation or provide additional information in context. Just imagine that you’ll soon be wearing AR glasses, and the information that is transferred to your retina will be tailored to your needs.

Here’s a foretaste of what’s in store for us:

Moving From Augmented Reality Towards Virtual Reality To Create An Immersive Experience

AR experience has a natural limitation. As users, we have a clear line between us and content; this line separates one world (AR) with another (real world). This line causes a sense that the AR world is clearly not real.

You probably know how to solve this limitation, i.e. with virtual reality (VR), of course. VR is not exactly a new medium, but it’s only been in the last few years that technology has reached a point where it allowed designers to create immersive experiences.

Immersive VR experiences remove the barrier between the real world and digital. When you put on a VR headset, it’s difficult for your brain to process whether the information that you are receiving is real. The idea of how VR experiences can look in the nearest future is well explained in the movie “Ready Player One”:

Here is what designers need to remember when creating immersive virtual environments:

  1. Write a story
    Meaningful VR has a strong story at its core. That’s why before you even start designing for a VR environment, you need to write a narrative for the user journey. A powerful tool known as a ‘storyboard’ can help you with that. Using a storyboard, it’s possible to create a story and examine all the possible outcomes. When you examine your story, you will see when and how to use both visual and audio cues to create an immersive experience.
  2. Create a deeper connection with a character
    In order to make users believe that all things around them in VR are real, we need to create a connection with the characters played by the users. One of the most obvious solutions is to include a representation of users’ hands in the virtual scene. This representation should be of actual hands — not just a rigged replica. It’s vital to consider different factors (such as gender or skin color) because it’ll make interactions more realistic.
    A user can look at his or her hands and see themselves appear as a character. (Source: leapmotion)

    It’s also possible to bring some objects from real life to a VR environment in order to create this connection. For instance, a mirror. When the user looks at a mirror and sees their character in the reflection, it enables more realistic interactions between the user and virtual characters.


    A VR user looks into a virtual mirror and sees himself as a character in a VR environment. (Image credit: businesswire)
    A virtual reality user looks into a virtual mirror and sees himself as a character in a VR environment. Credits: businesswire. (Large preview)
  3. Use gestures instead of menus
    When designing immersive VR experiences, we can’t rely on traditional menus and buttons. Why? Because it is relatively easy to break a sense of immersion by showing a menu. Users will know that everything around them is not real. Instead of using traditional menus, designers need to rely on gestures. The design community is still in the process of defining a universal language for using gestures, and taking part in this activity is fun and exciting exercise. The tricky part is to make gestures familiar and predictable for users.
    Hovercast VR menu is an attempt to reuse existing concepts of interaction for VR experience. Unfortunately, this concept can break the sense of immersion. New medium requires a new model of interaction.
  4. Interact with elements in the VR environment
    To create an environment that feels real, we need to give the user the ability to interact with objects in that reality. Ideally, all objects in the environment can be designed in a way that allows users to touch and inspect them. Such objects will act as stimuli and will help you create a more immersive experience. Touch is extremely important for exploring the environment; the most important information that babies get in the first days is received through touch.
  5. Share emotion in VR
    VR has a real opportunity to become a new level of social experience. But to make it happen, we need to solve one significant problem, i.e. bring the non-verbal cues into the interaction.

    When we interact with other people, a significant part on information that we get comes from body language. Surprise, disgust, anger — all these emotions are in our facial expressions, and during face-to-face interactions, we infer information from the eye region. It’s important to provide this information when people interact in a VR environment to create more realistic interactions.

    The good news is that the head-mounted devices (HMDs) will soon cover emotion recognition. Almost any area of human-to-human interaction will benefit from facial expressions in VR.

    Sharing emotions in VR space (Source: Rachel Metz of MITReview)
  6. Design sound and music suitabke for a VR environment
    Audio is a huge component of the immersive experience. It’s impossible to create a genuinely immersive experience without designing sound for the environment. The sound can both be used as a background element (i.e., ambient sound of wind) or directional. In the latter case, the sound can be used as a cue — by playing with directionality (where the sound comes from) and distance (it’s possible to focus user attention on particular elements).

    When it comes to designing audio for VR, it’s essential to make the sound 3D. 2D sound doesn’t work for VR very well because it makes everything too flat. The 3D sound is the sound that you can hear in every direction around you — front, behind, above and beyond — all over the place. You don’t need specialized headphones to experience 3D sound; it’s possible to create it using standard stereo speakers of HMD.

    Head tracking is another critical aspect of a good sound design. It’s vital to make sounds behave in a realistic manner. That’s why when a user moves his head, the sound should change according to the head movement.

  7. Prevent motion sickness
    Motion sickness is one of the primary pain-points in VR. It’s a condition in which a disagreement exists between visually perceived movement and the vestibular system’s sense of movement. It’s vital to keep users comfortable while they experience VR.

    There are two popular theories what causes motion sickness in VR:

    • ‘Sensory Conflict’ Theory
      According to this theory, motion sickness occurs as a result of a sensory disagreement between expected motion and motion that is actually experienced.
    • ‘Eye Movement’ Theory
      In the book “The VR Book: Human-Centered Design For Virtual Reality”, Jason Jerald mentions that motion sickness occurs because of the unnatural eye motion that is required to keep the scene’s image stable on the retina.

    Here are a few tips that will help you prevent users from reaching for the sickbag:

    • Physical body movement should match with visual movement. Sometimes even a small visual jitter can have an enormously negative impact on the experience.
    • Let users rest between moving scenes (this is especially important when the VR experience is really dynamic).
    • Reduce virtual rotations.

Conclusion

When we think about the modern state of product design, it becomes evident that we are only at the tip of the iceberg because we’re pretty limited to flat screens.

We’re witnessing a fundamental shift in Human-Computer Interaction (HCI) — rethinking the whole concept of digital experience. In the next decade, designers will break the glass (the era of mobile devices as we know them today) and move to the interfaces of the future — sophisticated voice interfaces, advanced ARs, and truly immersive VRs. And when it comes to creating a new experience, it’s essential to understand that the only boundary we have are our brains telling us it’s got to be how it’s always been.

Smashing Editorial
(cc, ra, yk, il)

Source: Smashing Magazine, Designing Emotional Interfaces Of The Future

The Smashing Survey: Join In!

dreamt up by webguru in Uncategorized | Comments Off on The Smashing Survey: Join In!

The Smashing Survey: Join In!

The Smashing Survey: Join In!

Rachel Andrew



Our entire aim here at Smashing Magazine — and my focus as Editor-in-Chief — is to provide the most helpful and interesting content and resources for web professionals. We aim not only to introduce new tools, technologies, and best practices, but also to give you handy resources to refer back to and put on interesting live events such as our conferences and webinars.

To be able to do that well, we need to understand the people who read Smashing Magazine, come to our conferences, and sign up as members. Given that we don’t ever get to meet or interact with the majority of folks who visit the site, this can make it quite difficult for us to better understand our readers and subscribers. Many of our Smashing Members join us in Slack, and we get to chat with conference attendees. However, these two groups are small in comparison to our worldwide audience.

So today, we’ve decided to launch a Smashing Survey which will help us create even more relevant content and shape the future of Smashing. The information will be used only here at Smashing to guide our content and our work, to ensure that we are doing the best we can for those who you who give us your time and attention.


The Smashing Survey 2019
The survey contains up to 35 questions and will take you only 5–10 minutes to complete. Join in!

We look forward to learning more about your experience with Smashing Magazine, and the things that matter to you. We promise to use that information to provide the resources that you need.

Smashing Editorial
(ra, vf, il)

Source: Smashing Magazine, The Smashing Survey: Join In!

Introducing The Component-Based API

dreamt up by webguru in Uncategorized | Comments Off on Introducing The Component-Based API

Introducing The Component-Based API

Introducing The Component-Based API

Leonardo Losoviz



An API is the communication channel for an application to load data from the server. In the world of APIs, REST has been the more established methodology, but has lately been overshadowed by GraphQL, which offers important advantages over REST. Whereas REST requires multiple HTTP requests to fetch a set of data to render a component, GraphQL can query and retrieve such data in a single request, and the response will be exactly what is required, without over or under-fetching data as typically happens in REST.

In this article, I will describe another way of fetching data which I have designed and called “PoP” (and open sourced here), which expands on the idea of fetching data for several entities in a single request introduced by GraphQL and takes it a step further, i.e. while REST fetches the data for one resource, and GraphQL fetches the data for all resources in one component, the component-based API can fetch the data for all resources from all components in one page.

Using a component-based API makes most sense when the website is itself built using components, i.e. when the webpage is iteratively composed of components wrapping other components until, at the very top, we obtain a single component that represents the page. For instance, the webpage shown in the image below is built with components, which are outlined with squares:


Screenshot of a component-based webpage
The page is a component wrapping components wrapping components, as shown by the squares. (Large preview)

A component-based API is able to make a single request to the server by requesting the data for all of the resources in each component (as well as for all of the components in the page) which is accomplished by keeping the relationships among components in the API structure itself.

Among others, this structure offers the following several benefits:

  • A page with many components will trigger only one request instead of many;
  • Data shared across components can be fetched only once from the DB and printed only once in the response;
  • It can greatly reduce — even completely remove — the need for a data store.

We will explore these in details throughout the article, but first, let’s explore what components actually are and how we can build a site based on such components, and finally, explore how a component-based API works.

Recommended reading: A GraphQL Primer: Why We Need A New Kind Of API

Building A Site Through Components

A component is simply a set of pieces of HTML, JavaScript and CSS code put all together to create an autonomous entity. This can then wrap other components to create more complex structures, and be itself wrapped by other components, too. A component has a purpose, which can range from something very basic (such as a link or a button) to something very elaborate (such as a carousel or a drag-and-drop image uploader). Components are most useful when they are generic and enable customization through injected properties (or “props”), so that they can serve a wide array of use cases. In the utmost case, the site itself becomes a component.

The term “component” is often used to refer both to functionality and design. For instance, concerning functionality, JavaScript frameworks such as React or Vue allow to create client-side components, which are able to self-render (for instance, after the API fetches their required data), and use props to set configuration values on their wrapped components, enabling code reusability. Concerning design, Bootstrap has standardized how websites look and feel through its front-end component library, and it has become a healthy trend for teams to create design systems to maintain their websites, which allows the different team members (designers and developers, but also marketers and salesmen) to speak a unified language and express a consistent identity.

Componentizing a site then is a very sensible way to make the website become more maintainable. Sites using JavaScript frameworks such as React and Vue are already component-based (at least on the client-side). Using a component library like Bootstrap doesn’t necessarily make the site be component-based (it could be a big blob of HTML), however, it incorporates the concept of reusable elements for the user interface.

If the site is a big blob of HTML, for us to componentize it we must break the layout into a series of recurring patterns, for which we must identify and catalogue sections on the page based on their similarity of functionality and styles, and break these sections down into layers, as granular as possible, attempting to have each layer be focused on a single goal or action, and also trying to match common layers across different sections.

Note: Brad Frost’s “Atomic Design” is a great methodology for identifying these common patterns and building a reusable design system.


Identifying elements to componentize a webpage
Brad Frost identifies five distinct levels in atomic design for creating design systems. (Large preview)

Hence, building a site through components is akin to playing with LEGO. Each component is either an atomic functionality, a composition of other components, or a combination of the two.

As shown below, a basic component (an avatar) is iteratively composed by other components until obtaining the webpage at the top:

Sequence of components produced, from an avatar all the way up to the webpage. (Large preview)

The Component-Based API Specification

For the component-based API I have designed, a component is called a “module”, so from now on the terms “component” and “module” are used interchangeably.

The relationship of all modules wrapping each other, from the top-most module all the way down to the last level, is called the “component hierarchy”. This relationship can be expressed through an associative array (an array of key => property) on the server-side, in which each module states its name as the key attribute and its inner modules under the property modules. The API then simply encodes this array as a JSON object for consumption:

// Component hierarchy on server-side, e.g. through PHP:
[
  "top-module" => [
    "modules" => [
      "module-level1" => [
        "modules" => [
          "module-level11" => [
            "modules" => [...]
          ],
          "module-level12" => [
            "modules" => [
              "module-level121" => [
                "modules" => [...]
              ]
            ]
          ]
        ]
      ],
      "module-level2" => [
        "modules" => [
          "module-level21" => [
            "modules" => [...]
          ]
        ]
      ]
    ]
  ]
]

// Component hierarchy encoded as JSON:
{
  "top-module": {
    modules: {
      "module-level1": {
        modules: {
          "module-level11": {
            ...
          },
          "module-level12": {
            modules: {
              "module-level121": {
                ...
              }
            }
          }
        }
      },
      "module-level2": {
        modules: {
          "module-level21": {
            ...
          }
        }
      }
    }
  }
}

The relationship among modules is defined on a strictly top-down fashion: a module wraps other modules and knows who they are, but it doesn’t know — and doesn’t care — which modules are wrapping him.

For instance, in the JSON code above, module module-level1 knows it wraps modules module-level11 and module-level12, and, transitively, it also knows it wraps module-level121; but module module-level11 doesn’t care who is wrapping it, consequently is unaware of module-level1.

Having the component-based structure, we can now add the actual information required by each module, which is categorized into either settings (such as configuration values and other properties) and data (such as the IDs of the queried database objects and other properties), and placed accordingly under entries modulesettings and moduledata:

{
  modulesettings: {
    "top-module": {
      configuration: {...},
      ...,
      modules: {
        "module-level1": {
          configuration: {...},
          ...,
          modules: {
            "module-level11": {
              repeat...
            },
            "module-level12": {
              configuration: {...},
              ...,
              modules: {
                "module-level121": {
                  repeat...
                }
              }
            }
          }
        },
        "module-level2": {
          configuration: {...},
          ...,
          modules: {
            "module-level21": {
              repeat...
            }
          }
        }
      }
    }
  },
  moduledata: {
    "top-module": {
      dbobjectids: [...],
      ...,
      modules: {
        "module-level1": {
          dbobjectids: [...],
          ...,
          modules: {
            "module-level11": {
              repeat...
            },
            "module-level12": {
              dbobjectids: [...],
              ...,
              modules: {
                "module-level121": {
                  repeat...
                }
              }
            }
          }
        },
        "module-level2": {
          dbobjectids: [...],
          ...,
          modules: {
            "module-level21": {
              repeat...
            }
          }
        }
      }
    }
  }
}

Following, the API will add the database object data. This information is not placed under each module, but under a shared section called databases, to avoid duplicating information when two or more different modules fetch the same objects from the database.

In addition, the API represents the database object data in a relational manner, to avoid duplicating information when two or more different database objects are related to a common object (such as two posts having the same author). In other words, database object data is normalized.

Recommended reading: Building A Serverless Contact Form For Your Static Site

The structure is a dictionary, organized under each object type first and object ID second, from which we can obtain the object properties:

{
  databases: {
    primary: {
      dbobject_type: {
        dbobject_id: {
          property: ...,
          ...
        },
        ...
      },
      ...
    }
  }
}

This JSON object is already the response from the component-based API. Its format is a specification all by itself: As long as the server returns the JSON response in its required format, the client can consume the API independently of how it is implemented. Hence, the API can be implemented on any language (which is one of the beauties of GraphQL: being a specification and not an actual implementation has enabled it to become available in a myriad of languages.)

Note: In an upcoming article, I will describe my implementation of the component-based API in PHP (which is the one available in the repo).

API response example

For instance, the API response below contains a component hierarchy with two modules, page => post-feed, where module post-feed fetches blog posts. Please notice the following:

  • Each module knows which are its queried objects from property dbobjectids (IDs 4 and 9 for the blog posts)
  • Each module knows the object type for its queried objects from property dbkeys (each post’s data is found under posts, and the post’s author data, corresponding to the author with the ID given under the post’s property author, is found under users)
  • Because the database object data is relational, property author contains the ID to the author object instead of printing the author data directly.
{
  moduledata: {
    "page": {
      modules: {
        "post-feed": {
          dbobjectids: [4, 9]
        }
      }
    }
  },
  modulesettings: {
    "page": {
      modules: {
        "post-feed": {
          dbkeys: {
            id: "posts",
            author: "users"
          }
        }
      }
    }
  },
  databases: {
    primary: {
      posts: {
        4: {
          title: "Hello World!",
          author: 7
        },
        9: {
          title: "Everything fine?",
          author: 7
        }
      },
      users: {
        7: {
          name: "Leo"
        }
      }
    }
  }
}

Differences Fetching Data From Resource-Based, Schema-Based And Component-Based APIs

Let’s see how a component-based API such as PoP compares, when fetching data, to a resource-based API such as REST, and to a schema-based API such as GraphQL.

Let’s say IMDB has a page with two components which need to fetch data: “Featured director” (showing a description of George Lucas and a list of his films) and “Films recommended for you” (showing films such as Star Wars: Episode I — The Phantom Menace and The Terminator). It could look like this:


Next-generation IMDB
Components ‘Featured director’ and ‘Films recommended for you’ for the next-generation IMDB site. (Large preview)

Let’s see how many requests are needed to fetch the data through each API method. For this example, the “Featured director” component brings one result (“George Lucas”), from which it retrieves two films (Star Wars: Episode I — The Phantom Menace and Star Wars: Episode II — Attack of the Clones), and for each film two actors (“Ewan McGregor” and “Natalie Portman” for the first film, and “Natalie Portman” and “Hayden Christensen” for the second film). The component “Films recommended for you” brings two results (Star Wars: Episode I — The Phantom Menace and The Terminator), and then fetches their directors (“George Lucas” and “James Cameron” respectively).

Using REST to render component featured-director, we may need the following 7 requests (this number can vary depending on how much data is provided by each endpoint, i.e. how much over-fetching has been implemented):

GET - /featured-director
GET - /directors/george-lucas
GET - /films/the-phantom-menace
GET - /films/attack-of-the-clones
GET - /actors/ewan-mcgregor
GET - /actors/natalie-portman
GET - /actors/hayden-christensen

GraphQL allows, through strongly typed schemas, to fetch all the required data in one single request per component. The query to fetch data through GraphQL for the component featuredDirector looks like this (after we have implemented the corresponding schema):

query {
  featuredDirector {
    name
    country
    avatar
    films {
      title
      thumbnail
      actors {
        name
        avatar
      }
    }
  }
}

And it produces the following response:

{
  data: {
    featuredDirector: {
      name: "George Lucas",
      country: "USA",
      avatar: "...",
      films: [
        { 
          title: "Star Wars: Episode I - The Phantom Menace",
          thumbnail: "...",
          actors: [
            {
              name: "Ewan McGregor",
              avatar: "...",
            },
            {
              name: "Natalie Portman",
              avatar: "...",
            }
          ]
        },
        { 
          title: "Star Wars: Episode II - Attack of the Clones",
          thumbnail: "...",
          actors: [
            {
              name: "Natalie Portman",
              avatar: "...",
            },
            {
              name: "Hayden Christensen",
              avatar: "...",
            }
          ]
        }
      ]
    }
  }
}

And querying for component “Films recommended for you” produces the following response:

{
  data: {
    films: [
      { 
        title: "Star Wars: Episode I - The Phantom Menace",
        thumbnail: "...",
        director: {
          name: "George Lucas",
          avatar: "...",
        }
      },
      { 
        title: "The Terminator",
        thumbnail: "...",
        director: {
          name: "James Cameron",
          avatar: "...",
        }
      }
    ]
  }
}

PoP will issue only one request to fetch all the data for all components in the page, and normalize the results. The endpoint to be called is simply the same as the URL for which we need to get the data, just adding an additional parameter output=json to indicate to bring the data in JSON format instead of printing it as HTML:

GET - /url-of-the-page/?output=json

Assuming that the module structure has a top module named page containing modules featured-director and films-recommended-for-you, and these also have submodules, like this:

"page"
  modules
    "featured-director"
      modules
        "director-films"
          modules
            "film-actors"
  "films-recommended-for-you"
    modules
      "film-director"

The single returned JSON response will look like this:

{
  modulesettings: {
    "page": {
      modules: {
        "featured-director": {
          dbkeys: {
            id: "people",
          },
          modules: {
            "director-films": {
              dbkeys: {
                films: "films"
              },
              modules: {
                "film-actors": {
                  dbkeys: {
                    actors: "people"
                  },
                }
              }
            }
          }
        },
        "films-recommended-for-you": {
          dbkeys: {
            id: "films",
          },
          modules: {
            "film-director": {
              dbkeys: {
                director: "people"
              },
            }
          }
        }
      }
    }
  },
  moduledata: {
    "page": {
      modules: {
        "featured-director": {
          dbobjectids: [1]
        },
        "films-recommended-for-you": {
          dbobjectids: [1, 3]
        }
      }
    }
  },
  databases: {
    primary: {
      people {
        1: {
          name: "George Lucas",
          country: "USA",
          avatar: "..."
          films: [1, 2]
        },
        2: {
          name: "Ewan McGregor",
          avatar: "..."
        },
        3: {
          name: "Natalie Portman",
          avatar: "..."
        },
        4: {
          name: "Hayden Christensen",
          avatar: "..."
        },
        5: {
          name: "James Cameron",
          avatar: "..."
        },
      },
      films: {
        1: { 
          title: "Star Wars: Episode I - The Phantom Menace",
          actors: [2, 3],
          director: 1,
          thumbnail: "..."
        },
        2: { 
          title: "Star Wars: Episode II - Attack of the Clones",
          actors: [3, 4],
          thumbnail: "..."
        },
        3: { 
          title: "The Terminator",
          director: 5,
          thumbnail: "..."
        },
      }
    }
  }
}

Let’s analyze how these three methods compare to each other, in terms of speed and the amount of data retrieved.

Speed

Through REST, having to fetch 7 requests just to render one component can be very slow, mostly on mobile and shaky data connections. Hence, the jump from REST to GraphQL represents a great deal for speed, because we are able to render a component with only one request.

PoP, because it can fetch all data for many components in one request, will be faster for rendering many components at once; however, most likely there is no need for this. Having components be rendered in order (as they appear in the page), is already a good practice, and for those components which appear under the fold there is certainly no rush to render them. Hence, both the schema-based and component-based APIs are already pretty good and clearly superior to a resource-based API.

Amount of Data

On each request, data in the GraphQL response may be duplicated: actress “Natalie Portman” is fetched twice in the response from the first component, and when considering the joint output for the two components, we can also find shared data, such as film Star Wars: Episode I — The Phantom Menace.

PoP, on the other hand, normalizes the database data and prints it only once, however, it carries the overhead of printing the module structure. Hence, depending on the particular request having duplicated data or not, either the schema-based API or the component-based API will have a smaller size.

In conclusion, a schema-based API such as GraphQL and a component-based API such as PoP are similarly good concerning performance, and superior to a resource-based API such as REST.

Recommended reading: Understanding And Using REST APIs

Particular Properties Of A Component-Based API

If a component-based API is not necessarily better in terms of performance than a schema-based API, you may be wondering, then what am I trying to achieve with this article?

In this section, I will attempt to convince you that such an API has incredible potential, providing several features which are very desirable, making it a serious contender in the world of APIs. I describe and demonstrate each of its unique great features below.

The Data To Be Retrieved From The Database Can Be Inferred From The Component Hierarchy

When a module displays a property from a DB object, the module may not know, or care, what object it is; all it cares about is defining what properties from the loaded object are required.

For instance, consider the image below. A module loads an object from the database (in this case, a single post), and then its descendant modules will show certain properties from the object, such as title and content:


Shown data is defined at different intervals
While some modules load the database object, others load properties. (Large preview)

Hence, along the component hierarchy, the “dataloading” modules will be in charge of loading the queried objects (the module loading the single post, in this case), and its descendant modules will define what properties from the DB object are required (title and content, in this case).

Fetching all the required properties for the DB object can be done automatically by traversing the component hierarchy: starting from the dataloading module, we iterate all its descendant modules all the way down until reaching a new dataloading module, or until the end of the tree; at each level we obtain all required properties, and then merge all properties together and query them from the database, all of them only once.

In the structure below, module single-post fetches the results from the DB (the post with ID 37), and submodules post-title and post-content define properties to be loaded for the queried DB object (title and content respectively); submodules post-layout and fetch-next-post-button do not require any data fields.

"single-post"
  => Load objects with object type "post" and ID 37
  modules
    "post-layout"
      modules
        "post-title"
          => Load property "title"
        "post-content"
          => Load property "content"
    "fetch-next-post-button"

The query to be executed is calculated automatically from the component hierarchy and their required data fields, containing all the properties needed by all the modules and their submodules:

SELECT 
  title, content 
FROM 
  posts 
WHERE
  id = 37

By fetching the properties to retrieve directly from the modules, the query will be automatically updated whenever the component hierarchy changes. If, for instance, we then add submodule post-thumbnail, which requires data field thumbnail:

"single-post"
  => Load objects with object type "post" and ID 37
  modules
    "post-layout"
      modules
        "post-title"
          => Load property "title"
        "post-content"
          => Load property "content"
        "post-thumbnail"
          => Load property "thumbnail"
    "fetch-next-post-button"

Then the query is automatically updated to fetch the additional property:

SELECT 
  title, content, thumbnail 
FROM 
  posts 
WHERE
  id = 37

Because we have established the database object data to be retrieved in a relational manner, we can also apply this strategy among the relationships between database objects themselves.

Consider the image below: Starting from the object type post and moving down the component hierarchy, we will need to shift the DB object type to user and comment, corresponding to the post’s author and each of the post’s comments respectively, and then, for each comment, it must change the object type once again to user corresponding to the comment’s author.

Moving from a database object to a relational object (possibly changing the object type, as in post => author going from post to user, or not, as in author => followers going from user to user) is what I call “switching domains”.


Showing data for relational objects
Changing the DB object from one domain to another. (Large preview)

After switching to a new domain, from that level at the component hierarchy downwards, all required properties will be subjected to the new domain:

  • name is fetched from the user object (representing the post’s author),
  • content is fetched from the comment object (representing each of the post’s comments),
  • name is fetched from the user object (representing the author of each comment).

Traversing the component hierarchy, the API knows when it is switching to a new domain and, appropriately, update the query to fetch the relational object.

For example, if we need to show data from the post’s author, stacking submodule post-author will change the domain at that level from post to the corresponding user, and from this level downwards the DB object loaded into the context passed to the module is the user. Then, submodules user-name and user-avatar under post-author will load properties name and avatar under the user object:

"single-post"
  => Load objects with object type "post" and ID 37
  modules
    "post-layout"
      modules
        "post-title"
          => Load property "title"
        "post-content"
          => Load property "content"
        "post-author"
          => Switch domain from "post" to "user", based on property "author"
          modules
            "user-layout"
              modules
                "user-name"
                  => Load property "name"
                "user-avatar"
                  => Load property "avatar"
    "fetch-next-post-button"

Resulting in the following query:

SELECT 
  p.title, p.content, p.author, u.name, u.avatar 
FROM 
  posts p 
INNER JOIN 
  users u 
WHERE 
  p.id = 37 AND p.author = u.id

In summary, by configuring each module appropriately, there is no need to write the query to fetch data for a component-based API. The query is automatically produced from the structure of the component hierarchy itself, obtaining what objects must be loaded by the dataloading modules, the fields to retrieve for each loaded object defined at each descendant module, and the domain switching defined at each descendant module.

Adding, removing, replacing or altering any module will automatically update the query. After executing the query, the retrieved data will be exactly what is required — nothing more or less.

Observing Data And Calculating Additional Properties

Starting from the dataloading module down the component hierarchy, any module can observe the returned results and calculate extra data items based on them, or feedback values, which are placed under entry moduledata.

For instance, module fetch-next-post-button can add a property indicating if there are more results to fetch or not (based on this feedback value, if there aren’t more results, the button will be disabled or hidden):

{
  moduledata: {
    "page": {
      modules: {
        "single-post": {
          modules: {
            "fetch-next-post-button": {
              feedback: {
                hasMoreResults: true
              }
            }
          }
        }
      }
    }
  }
}

Implicit Knowledge Of Required Data Decreases Complexity And Makes The Concept Of An “Endpoint” Become Obsolete

As shown above, the component-based API can fetch exactly the required data, because it has the model of all components on the server and what data fields are required by each component. Then, it can make the knowledge of the required data fields implicit.

The advantage is that defining what data is required by the component can be updated just on the server-side, without having to redeploy JavaScript files, and the client can be made dumb, just asking the server to provide whatever data it is that it needs, thus decreasing the complexity of the client-side application.

In addition, calling the API to retrieve the data for all components for a specific URL can be carried out simply by querying that URL plus adding the extra parameter output=json to indicate returning API data instead of printing the page. Hence, the URL becomes its own endpoint or, considered in a different way, the concept of an “endpoint” becomes obsolete.


Requests to fetch resources with different APIs
Requests to fetch resources with different APIs. (Large preview)

Retrieving Subsets Of Data: Data Can Be Fetched For Specific Modules, Found At Any Level Of The Component Hierarchy

What happens if we don’t need to fetch the data for all modules in a page, but simply the data for a specific module starting at any level of the component hierarchy? For instance, if a module implements an infinite-scroll, when scrolling down we must fetch only new data for this module, and not for the other modules on the page.

This can be accomplished by filtering the branches of the component hierarchy that will be included in the response, to include properties only starting from the specified module and ignore everything above this level. In my implementation (which I will describe in an upcoming article), the filtering is enabled by adding parameter modulefilter=modulepaths to the URL, and the selected module (or modules) is indicated through a modulepaths[] parameter, where a “module path” is the list of modules starting from the top-most module to the specific module (e.g. module1 => module2 => module3 has module path [module1, module2, module3] and is passed as a URL parameter as module1.module2.module3).

For instance, in the component hierarchy below every module has an entry dbobjectids:

"module1"
  dbobjectids: [...]
  modules
    "module2"
      dbobjectids: [...]
      modules
        "module3"
          dbobjectids: [...]
        "module4"
          dbobjectids: [...]
        "module5"
          dbobjectids: [...]
          modules
            "module6"
              dbobjectids: [...]

Then requesting the webpage URL adding parameters modulefilter=modulepaths and modulepaths[]=module1.module2.module5 will produce the following response:

"module1"
  modules
    "module2"
      modules
        "module5"
          dbobjectids: [...]
          modules
            "module6"
              dbobjectids: [...]

In essence, the API starts loading data starting from module1 => module2 => module5. That’s why module6, which comes under module5, also brings its data while module3 and module4 do not.

In addition, we can create custom module filters to include a pre-arranged set of modules. For instance, calling a page with modulefilter=userstate can print only those modules which require user state for rendering them in the client, such as modules module3 and module6:

"module1"
  modules
    "module2"
      modules
        "module3"
          dbobjectids: [...]
        "module5"
          modules
            "module6"
              dbobjectids: [...]

The information of which are the starting modules comes under section requestmeta, under entry filteredmodules, as an array of module paths:

requestmeta: {
  filteredmodules: [
    ["module1", "module2", "module3"],
    ["module1", "module2", "module5", "module6"]
  ]
}

This feature allows to implement an uncomplicated Single-Page Application, in which the frame of the site is loaded on the initial request:

"page"
  modules
    "navigation-top"
      dbobjectids: [...]
    "navigation-side"
      dbobjectids: [...]
    "page-content"
      dbobjectids: [...]

But, from them on, we can append parameter modulefilter=page to all requested URLs, filtering out the frame and bringing only the page content:

"page"
  modules
    "navigation-top"
    "navigation-side"
    "page-content"
      dbobjectids: [...]

Similar to module filters userstate and page described above, we can implement any custom module filter and create rich user experiences.

The Module Is Its Own API

As shown above, we can filter the API response to retrieve data starting from any module. As a consequence, every module can interact with itself from client to server just by adding its module path to the webpage URL in which it has been included.

I hope you will excuse my over-excitement, but I truly can’t emphasize enough how wonderful this feature is. When creating a component, we don’t need to create an API to go alongside with it to retrieve data (REST, GraphQL, or anything at all), because the component is already able to talk to itself in the server and load its own data — it is completely autonomous and self-serving.

Each dataloading module exports the URL to interact with it under entry dataloadsource from under section datasetmodulemeta:

{
  datasetmodulemeta: {
    "module1": {
      modules: {
        "module2": {
          modules: {
            "module5":  {
              meta: {
                dataloadsource: "https://page-url/?modulefilter=modulepaths&modulepaths[]=module1.module2.module5"
              },
              modules: {
                "module6": {
                  meta: {
                    dataloadsource: "https://page-url/?modulefilter=modulepaths&modulepaths[]=module1.module2.module5.module6"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Fetching Data Is Decoupled Across Modules And DRY

To make my point that fetching data in a component-based API is highly decoupled and DRY (Don’t Repeat Yourself), I will first need to show how in a schema-based API such as GraphQL it is less decoupled and not DRY.

In GraphQL, the query to fetch data must indicate the data fields for the component, which may include subcomponents, and these may also include subcomponents, and so on. Then, the topmost component needs to know what data is required by every one of its subcomponents too, as to fetch that data.

For instance, rendering the <FeaturedDirector> component might require the following subcomponents:

Render <FeaturedDirector>:
  
Country: {country} {foreach films as film} {/foreach}
Render <Film>:
Title: {title} Pic: {thumbnail} {foreach actors as actor} {/foreach}
Render <Actor>:
Name: {name} Photo: {avatar}

In this scenario, the GraphQL query is implemented at the <FeaturedDirector> level. Then, if subcomponent <Film> is updated, requesting the title through property filmTitle instead of title, the query from the <FeaturedDirector> component will need to be updated, too, to mirror this new information (GraphQL has a versioning mechanism which can deal with this problem, but sooner or later we should still update the information). This produces maintenance complexity, which could be difficult to handle when the inner components often change or are produced by third-party developers. Hence, components are not thoroughly decoupled from each other.

Similarly, we may want to render directly the <Film> component for some specific film, for which then we must also implement a GraphQL query at this level, to fetch the data for the film and its actors, which adds redundant code: portions of the same query will live at different levels of the component structure. So GraphQL is not DRY.

Because a component-based API already knows how its components wrap each other in its own structure, then these problems are completely avoided. For one, the client is able to simply request the required data it needs, whichever this data is; if a subcomponent data field changes, the overall model already knows and adapts immediately, without having to modify the query for the parent component in the client. Therefore, the modules are highly decoupled from each other.

For another, we can fetch data starting from any module path, and it will always return the exact required data starting from that level; there are no duplicated queries whatsoever, or even queries to start with. Hence, a component-based API is fully DRY. (This is another feature that really excites me and makes me get wet.)

(Yes, pun fully intended. Sorry about that.)

Retrieving Configuration Values In Addition To Database Data

Let’s revisit the example of the featured-director component for the IMDB site described above, which was created — you guessed it! — with Bootstrap. Instead of hardcoding the Bootstrap classnames or other properties such as the title’s HTML tag or the avatar max width inside of JavaScript files (whether they are fixed inside the component, or set through props by parent components), each module can set these as configuration values through the API, so that then these can be directly updated on the server and without the need to redeploy JavaScript files. Similarly, we can pass strings (such as the title Featured director) which can be already translated/internationalized on the server-side, avoiding the need to deploy locale configuration files to the front-end.

Similar to fetching data, by traversing the component hierarchy, the API is able to deliver the required configuration values for each module and nothing more or less.

The configuration values for the featured-director component might look like this:

{
  modulesettings: {
    "page": {
      modules: {
        "featured-director": {
          configuration: {
            class: "alert alert-info",
            title: "Featured director",
            titletag: "h3"
          },
          modules: {
            "director-films": {
              configuration: {
                classes: {
                  wrapper: "media",
                  avatar: "mr-3",
                  body: "media-body",
                  films: "row",
                  film: "col-sm-6"
                },
                avatarmaxsize: "100px"
              },
              modules: {
                "film-actors": {
                  configuration: {
                    classes: {
                      wrapper: "card",
                      image: "card-img-top",
                      body: "card-body",
                      title: "card-title",
                      avatar: "img-thumbnail"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Please notice how — because the configuration properties for different modules are nested under each module’s level — these will never collide with each other if having the same name (e.g. property classes from one module will not override property classes from another module), avoiding having to add namespaces for modules.

Higher Degree Of Modularity Achieved In The Application

According to Wikipedia, modularity means:

The degree to which a system’s components may be separated and recombined, often with the benefit of flexibility and variety in use. The concept of modularity is used primarily to reduce complexity by breaking a system into varying degrees of interdependence and independence across and ‘hide the complexity of each part behind an abstraction and interface’.

Being able to update a component just from the server-side, without the need to redeploy JavaScript files, has the consequence of better reusability and maintenance of components. I will demonstrate this by re-imagining how this example coded for React would fare in a component-based API.

Let’s say that we have a <ShareOnSocialMedia> component, currently with two items: <FacebookShare> and <TwitterShare>, like this:

Render <ShareOnSocialMedia>:
  <ul>
    <li>Share on Facebook: <FacebookShare url={window.location.href} /></li>
    <li>Share on Twitter: <TwitterShare url={window.location.href} /></li>
  </ul>

But then Instagram got kind of cool, so we need to add an item <InstagramShare> to our <ShareOnSocialMedia> component, too:

Render <ShareOnSocialMedia>:
  <ul>
    <li>Share on Facebook: <FacebookShare url={window.location.href} /></li>
    <li>Share on Twitter: <TwitterShare url={window.location.href} /></li>
    <li>Share on Instagram: <InstagramShare url={window.location.href} /></li>
  </ul>

In the React implementation, as it can be seen in the linked code, adding a new component <InstagramShare> under component <ShareOnSocialMedia> forces to redeploy the JavaScript file for the latter one, so then these two modules are not as decoupled as they could be.

In the component-based API, though, we can readily use the relationships among modules already described in the API to couple the modules together. While originally we will have this response:

{
  modulesettings: {
    "share-on-social-media": {
      modules: {
        "facebook-share": {
          configuration: {...}
        },
        "twitter-share": {
          configuration: {...}
        }
      }
    }
  }
}

After adding Instagram we will have the upgraded response:

{
  modulesettings: {
    "share-on-social-media": {
      modules: {
        "facebook-share": {
          configuration: {...}
        },
        "twitter-share": {
          configuration: {...}
        },
        "instagram-share": {
          configuration: {...}
        }
      }
    }
  }
}

And just by iterating all the values under modulesettings["share-on-social-media"].modules, component <ShareOnSocialMedia> can be upgraded to show the <InstagramShare> component without the need to redeploy any JavaScript file. Hence, the API supports the addition and removal of modules without compromising code from other modules, attaining a higher degree of modularity.

Native Client-Side Cache/Data Store

The retrieved database data is normalized in a dictionary structure, and standardized so that, starting from the value on dbobjectids, any piece of data under databases can be reached just by following the path to it as indicated through entries dbkeys, whichever way it was structured. Hence, the logic for organizing data is already native to the API itself.

We can benefit from this situation in several ways. For instance, the returned data for each request can be added into a client-side cache containing all data requested by the user throughout the session. Hence, it is possible to avoid adding an external data store such as Redux to the application (I mean concerning the handling of data, not concerning other features such as the Undo/Redo, the collaborative environment or the time-travel debugging).

Also, the component-based structure promotes caching: the component hierarchy depends not on the URL, but on what components are needed in that URL. This way, two events under /events/1/ and /events/2/ will share the same component hierarchy, and the information of what modules are required can be reutilized across them. As a consequence, all properties (other than database data) can be cached on the client after fetching the first event and reutilized from then on, so that only database data for each subsequent event must be fetched and nothing else.

Extensibility And Re-purposing

The databases section of the API can be extended, enabling to categorize its information into customized subsections. By default, all database object data is placed under entry primary, however, we can also create custom entries where to place specific DB object properties.

For instance, if the component “Films recommended for you” described earlier on shows a list of the logged-in user’s friends who have watched this film under property friendsWhoWatchedFilm on the film DB object, because this value will change depending on the logged-in user then we save this property under a userstate entry instead, so when the user logs out, we only delete this branch from the cached database on the client, but all the primary data still remains:

{
  databases: {
    userstate: {
      films: {
        5: { 
          friendsWhoWatchedFilm: [22, 45]
        },
      }
    },
    primary: {
      films: {
        5: { 
          title: "The Terminator"
        },
      }
      "people": {
        22: {
          name: "Peter",
        },
        45: {
          name: "John",
        },
      },
    }
  }
}

In addition, up to a certain point, the structure of the API response can be re-purposed. In particular, the database results can be printed in a different data structure, such as an array instead of the default dictionary.

For instance, if the object type is only one (e.g. films), it can be formatted as an array to be fed directly into a typeahead component:

[
  { 
    title: "Star Wars: Episode I - The Phantom Menace",
    thumbnail: "..."
  },
  { 
    title: "Star Wars: Episode II - Attack of the Clones",
    thumbnail: "..."
  },
  { 
    title: "The Terminator",
    thumbnail: "..."
  },
]

Support For Aspect-Oriented Programming

In addition to fetching data, the component-based API can also post data, such as for creating a post or adding a comment, and execute any kind of operation, such as logging the user in or out, sending emails, logging, analytics, and so on. There are no restrictions: any functionality provided by the underlying CMS can be invoked through a module — at any level.

Along the component hierarchy, we can add any number of modules, and each module can execute its own operation. Hence, not all operations must necessarily be related to the expected action of the request, as when doing a POST, PUT or DELETE operation in REST or sending a mutation in GraphQL, but can be added to provide extra functionalities, such as sending an email to the admin when a user creates a new post.

So, by defining the component hierarchy through dependency-injection or configuration files, the API can be said to support Aspect-oriented programming, “a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns.”

Recommended reading: Protecting Your Site With Feature Policy

Enhanced Security

The names of the modules are not necessarily fixed when printed in the output, but can be shortened, mangled, changed randomly or (in short) made variable any way intended. While originally thought for shortening the API output (so that module names carousel-featured-posts or drag-and-drop-user-images could be shortened to a base 64 notation, such as a1, a2 and so on, for the production environment), this feature allows to frequently change the module names in the response from the API for security reasons.

For instance, input names are by default named as their corresponding module; then, modules called username and password, which are to be rendered in the client as <input type="text" name="{input_name}"> and <input type="password" name="{input_name}"> respectively, can be set varying random values for their input names (such as zwH8DSeG and QBG7m6EF today, and c3oMLBjo and c46oVgN6 tomorrow) making it more difficult for spammers and bots to target the site.

Versatility Through Alternative Models

The nesting of modules allows to branch out to another module to add compatibility for a specific medium or technology, or change some styling or functionality, and then return to the original branch.

For instance, let’s say the webpage has the following structure:

"module1"
  modules
    "module2"
      modules
        "module3"
        "module4"
          modules
            "module5"
              modules
                "module6"

In this case, we’d like to make the website also work for AMP, however, modules module2, module4 and module5 are not AMP compatible. We can branch these modules out into similar, AMP-compatible modules module2AMP, module4AMP and module5AMP, after which we keep loading the original component hierarchy, so then only these three modules are substituted (and nothing else):

"module1"
  modules
    "module2AMP"
      modules
        "module3"
        "module4AMP"
          modules
            "module5AMP"
              modules
                "module6"

This makes it fairly easy to generate different outputs from a single codebase, adding forks only here and there as needed, and always scoped and restrained to individual modules.

Demonstration Time

The code implementing the API as explained in this article is available in this open-source repository.

I have deployed the PoP API under https://nextapi.getpop.org for demonstration purposes. The website runs on WordPress, so the URL permalinks are those typical to WordPress. As noted earlier, through adding parameter output=json to them, these URLs become their own API endpoints.

The site is backed by the same database from the PoP Demo website, so a visualization of the component hierarchy and retrieved data can be done querying the same URL in this other website (e.g. visiting the https://demo.getpop.org/u/leo/ explains the data from https://nextapi.getpop.org/u/leo/?output=json).

The links below demonstrate the API for cases described earlier on:


Example of JSON code returned by the API
Example of JSON code returned by the API. (Large preview)

Conclusion

A good API is a stepping stone for creating reliable, easily maintainable and powerful applications. In this article, I have described the concepts powering a component-based API which, I believe, is a pretty good API, and I hope I have convinced you too.

So far, the design and implementation of the API have involved several iterations and taken more than five years — and it’s not completely ready yet. However, it is in a pretty decent state, not ready for production but as a stable alpha. These days, I am still working on it; working on defining the open specification, implementing the additional layers (such as rendering) and writing documentation.

In an upcoming article, I will describe how my implementation of the API works. Until then, if you have any thoughts about it — regardless whether positive or negative — I would love to read your comments below.

Smashing Editorial
(rb, ra, yk, il)

Source: Smashing Magazine, Introducing The Component-Based API

Monthly Web Development Update 1/2019: Rethinking Habits And Finding Custom Solutions

dreamt up by webguru in Uncategorized | Comments Off on Monthly Web Development Update 1/2019: Rethinking Habits And Finding Custom Solutions

Monthly Web Development Update 1/2019: Rethinking Habits And Finding Custom Solutions

Monthly Web Development Update 1/2019: Rethinking Habits And Finding Custom Solutions

Anselm Hannemann



What could be better than starting the new year with some new experiments? Today I figured it was time to rethink JavaScript tooling in one of my projects. And since we wrote everything in plain ECMAScript modules already, I thought it would be easy to serve them natively now and remove all the build and transpilation steps. Until I realized that — although we wrote most code ourselves — we have a couple of third-party dependencies in there and, of course, not all of them are ECMAScript modules. So for now, I have to give up my plans to remove all the build steps and continue to bundle and transpile things, but I’ll try to figure out a better solution to modernize and simplify our tooling setup while providing a smaller bundle to our users.

Another experiment: Just a few weeks ago I had to build a simple “go to the top of the page” button for a website. I used requestAnimationFrame and similar stuff to optimize event handling, but today I found a way nicer and more efficient solution that uses IntersectionObserver to toggle the button on the viewport. You will find that article in the JavaScript section below. The reason I wanted to share these little stories is because I believe that the most important thing is that we review our habits and current solutions and see whether there are better, newer, simpler ideas that could improve a product. Keep playing, keep researching, and be sure to rethink existing systems from time to time.

News

UI/UX

Web Performance

JavaScript


Infographic showing how authentication and verification work without a password
Passwordless authentication? The WebAuthn API makes it possible. (Image credit)

CSS


An example text with randomly generated underlines.
Una Kravet’s “super underline” example uses randomly generated underlines for each element. Made possible with Houdini and the Paint API. (Image credit)

Work & Life

  • “Feeling a sense of accomplishment is an important part of our sense of self-worth. Beating up on yourself because you think you could have accomplished more can dent your confidence and self-esteem and leave you feeling depleted at the end of the day.” Lisa Evans shares what we can do to avoid falling into that trap.
  • Itamar Turner-Trauring shares his thoughts on how to get a job with a good work-life balance when you’re competing against people who are willing to work long hours.
  • Is it a good idea to provide healthcare and treatment based on digital products like apps? And if so, what are the requirements, the standards for this? How can we ensure this is done ethically correct? How do we set the limits, the privacy boundaries, how far do we allow companies to go with experiments here? Would personalized content be fine? Is it okay to share data collected from our devices with healthcare providers or insurances? These are questions we will have to ask ourselves and find an individual answer for.
  • This article about how Millenials became the burnout generation hit me hard this week. I see myself in this group of people described as “Millenials” (I do think it affects way more people than just the 20-year-olds) and I could relate to so many of the struggles mentioned in there that I now think that these problems are bigger than I ever imagined. They will affect society, politics, each individual on our planet. Given that fact, it’s crazy to hear that most people today will answer that they don’t have a friend they could talk to about their fears and anything else that disturbs them while two decades ago the average answer was still around five. Let’s assure our friends that we’re there for them and that they can talk to us about tough things. 2019 should be a year in which we — in our circle of influence — make it great to live in a human community where we can think with excitement and happiness about our friends, neighbors, and people we work with or talk to on the Internet.
  • We all try to accommodate so many things at the same time: being successful and productive at work, at home, with our children, in our relationships, doing sports, mastering our finances, and some hobbies. But we blindly ignore that it’s impossible to manage all that on the same level at the same time. We feel regret when we don’t get everything done in a specific timeframe such as at the end of a calendar year. Shawn Blanc argues that we should celebrate what we did do instead of feeling guilty for what we didn’t do.

Going Beyond…

  • There are words, and then there are words. Many of us know how harmful “just” can be as a word, how prescriptive, how passively aggressive it is. Tobias Tom challenges whether “should” is a useful word by examining the implicit and the result of using it in our daily language. Why “should” can be harmful to you and to what you want to achieve.
  • “We all know what we stand for. The trick is to state our values clearly — and to stand by them,” says Ben Werdmuller and points out how important it is to think about your very own red line that you don’t want to cross regardless of external pressure you might face or money you might get for it.
  • Exciting news for climate improvement this week: A team of arborists has successfully cloned and grown saplings from the stumps of some of the world’s oldest and largest coast redwoods, some of which were 3,000 years old and measured 35 feet in diameter when they were cut down in the 19th and 20th centuries. Earlier this month, 75 of the cloned saplings were planted at the Presidio National Park in San Francisco. What makes this so special is the fact that these ancient trees can sequester 250 tons of carbon dioxide from the atmosphere over their lives, compared to 1 ton for an average tree.
  • The ongoing technological development and strive to build new services that automate more and more things make it even more critical to emphasize human connection. Companies that show no effort in improving things for their clients, their employees, or the environment will begin to struggle soon, Ryan Paugh says.
  • We usually don’t expect much nice news about technology inventions from the car industry and their willingness to share it with others. But Toyota now has decided to share their automated safety system ‘Guardian’ with competitors. It uses self-driving technology to keep cars from crashing. “We will not keep it proprietary to ourselves only. But we will offer it in some way to others, whether that’s through licensing or actual whole systems,” says Gill Pratt from the company.

Thank you for reading! I’m happy to be back with this new edition of my Web Development Update in 2019 and grateful for all your ongoing support. It makes me happy to hear that so many people find this resource helpful. So if you enjoyed it, please feel free to share it with people you know, give me feedback, or support it with a small amount of money. —Anselm

Smashing Editorial
(cm)

Source: Smashing Magazine, Monthly Web Development Update 1/2019: Rethinking Habits And Finding Custom Solutions

Grabbing Visual Attention With The Visual Cortex

dreamt up by webguru in Uncategorized | Comments Off on Grabbing Visual Attention With The Visual Cortex

Grabbing Visual Attention With The Visual Cortex

Grabbing Visual Attention With The Visual Cortex

Susan Weinschenk



(This is a sponsored post.) You are designing a landing page. The goal of the page is to get people to notice, and hopefully click on a button on the screen to subscribe to a monthly newsletter. “Make sure the button captures people’s attention” is the goal you’ve been given.

So how, exactly, do you do that?

Research on the visual cortex in the brain can give you some ideas. The visual cortex is the part of the brain that processes visual information. Each of the senses has an area of the brain where the signals for that sensory perception are usually sent and processed. The visual cortex is the largest of the sensory cortices because we are very visual animals.

Recommended reading: What Is The Role Of Creativity In UX Design?

The Pre-Attention Areas Of The Visual Cortex

There are special areas of the visual cortex that process visual information very quickly. These are called the “pre-attention” areas because they process information faster than someone may realize they’ve even noticed something visually.

Within the visual cortex are four areas called V1, V2, V3 and V4. These are the “pre-attention” areas of the visual cortex, and they are dedicated to very small and specific visual elements.

Let’s take a look at each one:

Orientation

If one item is oriented differently than others, then it is noticed right away:


An image of fifteen short lines with one that stands out because it is oriented differently
(Large preview)

Size And Shape

If one item is either a different size or shape than others then it is noticed right away:


An image of twelve circles with one larger than the rest
(Large preview)

Color

If one item is a different color than others around it then it is noticed right away:


An image of thirteen black circles with one of them shown in red
(Large preview)

Movement

If one item moves in quickly, especially if it zooms in from starting at a small size and then becoming larger quickly (think tiger running quickly towards you), that grabs attention.

But Only One At A Time

The interesting, not immediately obvious factor here is that if you use these factors together at the same time then nothing really attracts attention.


An abstract image of colorful circles in different sizes
(Large preview)

If you want to capture attention then, pick one of the methods and use it only.

Take a look at the two designs presented below. Which one draws your attention to the idea that you should enroll?


A minimalistic image that uses mostly two colors
(Large preview)

An image using a variety of colors and tones
(Large preview)

Obviously, the image that has just one color area draws your attention more, rather than the one area that is color.

The Fusiform Facial Area

The pre-attention areas of the visual cortex are not the only visual/brain connection to use. Another area of the brain you can tap to grab attention on a page could be the Fusiform Facial Area (or FFA).

The FFA is a special part of the brain that is sensitive to human faces. The FFA is located in the mid/social part of the brain near the amygdala which processes emotions. Faces grab attention because of the FFA.


A screenshot of the WIX website with a smiling person presented on the front page
(Large preview)

The FFA identifies:

  • Is this a face?
  • Someone I know?
  • Someone I know personally?
  • What are they feeling?

What stimulates the FFA?

  • Faces that look straight out stimulate the FFA.
  • Faces that are in profile may eventually stimulate the FFA, but not as quickly. In the example below the face is in profile and obscured by hair. It may not stimulate the FFA at all.

  • An image of a woman with her face covered by her hair so that her facial features cannot be seen well
    (Large preview)
  • Even inanimate objects like the picture of the car below may stimulate the FFA area if they have things that look like facial parts such as eyes and a mouth.

A picture of a car that looks like it has facial parts such as eyes and a mouth (front)
(Large preview)

Looking Where The Face Looks?

You may have seen the heat maps that show that if you show a face and the face is looking at an object (for example, a button or a product) on the screen then the person looking at the page will also look at the same object. Here’s an example:


An advertisement for Sunsilk Shampoo in which the lady in the picture is looking at the product compared to a picture of her looking straight
(Large preview)

The red areas show where people looked most. When the model looks at the shampoo bottle then people tend to look there too.

But be careful about drawing too many conclusions from this. Although the research shows that people’s eye gaze will follow the eye gaze of the photo, that doesn’t necessarily mean that people will take action. Highly emotional facial expressions lead to more action taking than just eye gaze.

Recommended reading: The Importance Of Macro And Micro-Moment Design

Takeaways

If you want to grab someone’s visual attention:

  • Use the pre-attention areas of the visual cortex: make everything on the page plain except for one element.

or

  • Show a large face, facing forward;
  • If you want to spur action have the face show a strong emotion;
  • Resist the urge to use many methods at once, such as a face, and color, and size, and shape, and orientation.

This article is part of the UX design series sponsored by Adobe. Adobe XD tool is made for a fast and fluid UX design process, as it lets you go from idea to prototype faster. Design, prototype and share — all in one app. You can check out more inspiring projects created with Adobe XD on Behance, and also sign up for the Adobe experience design newsletter to stay updated and informed on the latest trends and insights for UX/UI design.

Smashing Editorial
(cm, ms, yk, il)

Source: Smashing Magazine, Grabbing Visual Attention With The Visual Cortex

HTML5 Input Types: Where Are They Now?

dreamt up by webguru in Uncategorized | Comments Off on HTML5 Input Types: Where Are They Now?

HTML5 Input Types: Where Are They Now?

HTML5 Input Types: Where Are They Now?

Drew McLellan



One of the stand-out headline features of HTML5 for many designers and developers was the addition of a number of new types of form input that could be used. For years, we’d been confined to using single-line text inputs (type="text") and laying on JavaScript and user instructions to try an accurately capture valid data of different types through that one unsophisticated field.

HTML5 brought with it new values of the type attribute that enabled us to be much more specific about the types of data we needed to capture through the field, with the promise being that the browser would then provide the interface and validation required to coerce the user into completing the field accurately.

From URLs to emails, and from search fields to dates, the hope was that instead of needing to write cumbersome JavaScript to try and validate those fields, we could just leave it to the browser to do that hard work for us. What’s more, by adding what it knows about the user’s context (type of device, type of interaction, timezones, and so on) the browser would be able to do a much better job of tailoring the interface to meet the user’s needs that we ever could as page authors.

Recommended reading: UX And HTML5: Let’s Help Users Fill In Your Mobile Form

Having new items in a spec is one thing, but it doesn’t really mean too much unless the browsers our audience are using support those features. These new values of the type attribute had the big advantage of falling back to type="text" if the browser had no support, but this may have also come at the cost of removing the browsers makers’ imperative when it came to implementing those new types in their products.

It’s the start of 2019, and HTML5 has been the current version of HTML now for more than four years. Which of those new types have been implemented, which can we use, and are there any we should be avoiding?

  1. Search Fields
  2. Telephone Number Fields
  3. URL Fields
  4. Email Fields
  5. Number Fields
  6. Range Fields
  7. Color Fields
  8. Date Fields

1. Search Fields

The type="search" input is intended to be used for search fields. Functionally, these are very the same as basic text fields, but having a dedicated type enables the browser to apply different styling. This is particularly useful if the user’s operating system has a set style for search fields, as this enables the browser to style the search fields on web pages to match.

The specification states that the difference between search and text is purely stylistic, so it may be best to avoid this if you intend to restyle the field with CSS anyway. There appears to be no semantic advantage to its use.

Can I Use input-search? Data on support for the input-search feature across the major browsers from caniuse.com.

Recommendation

Use type="search" if you intend to leave the styling of the search field up to the browser.

2. Telephone Number Fields

The type="tel" input is used for entering telephone numbers. These are like the unique usernames used by Whatsapp. If you’re unsure, ask your grandparents.

Internationally, telephone numbers take on lots of different formats, for both technical and localization reasons. Due to this, the tel input doesn’t attempt to validate the format of a phone number. You can make use of the associated validation tools such as the pattern attribute on the tag, or the setCustomValidity() JavaScript method to enforce a format if required.

On desktop browsers, the use of telephone fields seems to have little impact. On devices with virtual keyboards, however, they can be really useful. For example, on iOS, focusing input on a telephone field brings up a numeric keypad ready for keying in a number. In addition, the device’s autocomplete mechanisms kick in and suggest phone numbers that can be autofilled with a single tap.

Can I Use input-email-tel-url? Data on support for the input-email-tel-url feature across the major browsers from caniuse.com.

Recommendation

Use type="tel" for any phone number fields. It’s very useful where implemented, and comes at no cost when it’s not.

3. URL Fields

The type="url" field can be used for capturing URLs. You might use this when asking a user to input their website address for a business directory, for example. The curious thing about the URL field is that it takes only full, absolute URLs. There’s no option to be able to capture just a domain name, or just a path, for example. This does restrict its usefulness in some respects, as I imagine CMS and web app developers would have found lots of uses for a field that accepts and validates relative paths.

While this would be a valid absolute URL:

https://twitter.com/drewm

Both of these would not pass the field’s validation:

smashingmagazine.com
/2019/01/css-multiple-column-layout-multicol/

It feels like a missed opportunity that different parts of a URL cannot be specified, but that’s what we have. Browser support is across the board pretty great, with virtual keyboard devices offering some customization for URL entry. iOS customizes its keyboard with ., / and an autocomplete button for common TLDs such as .com and for my locale, .co.uk. This is a good example of the browser being able to offer more intelligent choices than we can as web developers.

Can I Use input-email-tel-url? Data on support for the input-email-tel-url feature across the major browsers from caniuse.com.

Recommendation

Use type="tel" whenever you need to collect a full, absolute URL. Browser support is great, but remember that it’s no good for individual URL components.

4. Email Fields

Possibly one of the most commonly used of the newer options is type="email" for email addresses. Much like we’ve seen with telephone numbers and URLs, devices with virtual keyboards customize the keys (to include things like @ buttons) and enable autofill from their contacts database.

Desktop browsers make use of this too, with Safari on macOS also enabling autofill for email fields, based on data in the system Contacts app.

Email addresses often seem like they follow a very simple format, but the variations actually make them quite complex. A naive attempt to validate email addresses can result in a perfectly good address being marked as invalid, so it’s great to be able to lean on the browser’s more sophisticated and well-tested validation methods to check the format.

Usefully, the multiple attribute can be added to email fields to collect a list of email addresses. In this case, each email address in the list is individually validated.

<input type="email" multiple>

Can I Use input-email-tel-url? Data on support for the input-email-tel-url feature across the major browsers from caniuse.com.

Recommendation

Use type="email" for email address fields whenever possible.


A combined screenshot showing the three custom keyboards offered by Safari on iOS for telephone, email and number field types.
Safari on iOS shows custom keyboards for telephone, email and number fields, amongst others. (Large preview)

5. Number Fields

The type="number" field is designed for numerical values, and has some very useful attributes along with it in the shape of min, max and step. A valid value for a number field must be a floating point number between any minimum and maximum value specified by the min and max attributes.

If step is set, then a valid value is divisible by the step value.

<input type="number" min="10" max="30" step="5">

Valid input for the above field would be 10, 15, 20, 25 and 30, with any other value being rejected.

Browser support is broad, again with virtual keyboards often defaulting to a numeric input mode for keying in values.

Some desktop browsers (including Chrome, Firefox and Safari, but not Edge) add toggle buttons for nudging the values up and down by the value of step, or if no step is specified, the default step appears to be 1 in each implementation.

Can I Use input-number? Data on support for the input-number feature across the major browsers from caniuse.com.

Recommendation

Use type="number" for any floating point numbers, as it’s widely supported and can help prevent accidental input.

6. Range Fields

Less obvious in use that some of the other types, type="range" can be thought of as being an alternative for type="number" where the user doesn’t care about the exact value.

Range fields take, and will often use, the same min, max and step attributes as number fields, and browsers almost universally display this as a graphical slider. The user doesn’t necessarily get to see the exact value they’re setting.

Range fields might be useful for those sorts of questions on forms like “How likely are you to recommend this to a friend?” with “Likely” at one end and “Unlikely” at the other. The user could slide the slider to wherever they think represents their opinion, and under the hood that gets submitted as a numerical value that you can store and process.

Browser support is good, although the appearance varies between implementations.

Can I Use input-range? Data on support for the input-range feature across the major browsers from caniuse.com.

Recommendation

The uses for type="range" might be a bit niche, but support is good and the slider provides a user-friendly input method where appropriate.

7. Color Fields

The type="color" field is design for capturing RGB colors in hexadecimal notation, such as #aabbcc. The HTML specification calls this a “color well control”, with the intention that the browser should provide a user-friendly color picker of some sort.

Some browsers do provide this, notably Chrome and Firefox both providing access to the system color picker through a small color swatch.

Neither IE nor Safari provide any support here, leaving the user to figure out that they’re supposed to enter a 7-digit hex number all by themselves.

Color fields might find use in theming for personalization and in CMS use, but unless the users are sufficiently technical to deal with hex color codes, it may be better not to rely on the browser providing a nice UI for these.

Can I Use input-color? Data on support for the input-color feature across the major browsers from caniuse.com.

#### Recommendation

Unless you know your users will be happy to fall back to entering hexadecimal color codes, it’s best not to rely on browsers supporting `type=”color”`.


A combined screenshot showing the different visual representations of range, color and date fields in three different browsers: Edge, Firefox and Chrome.
Range, color and date fields as displayed by Edge, Firefox and Chrome. (Large preview)

8. Date Fields

HTML5 introduced a number of different `type` values for creating inputs for dates and times. These included `date`, `time`, `datetime-local`, `month` and `week`.

At first glance, these appear to be heaven-sent, as collecting dates in a form is a difficult experience for both developer and user, and they’re needed pretty frequently.

The promise here is that the new field types enable the browser to provide a standardized, accessible and consistent user interface to capture dates and times from the user with ease. This is really important, as date and time formats vary world-over based on both language and locale, and so a friendly browser interface that translates an easy-to-use date selection into an unambiguous technical date format really does sound like the ideal solution.

As such, valid input for `type=”date”` field is an unambiguous _year-month-day_ value such as `2019-01-16`. Developers like these, as they map pretty much to the ISO 8601 date format, which is used in most technical contexts. Unfortunately, few regular human beings use this date format and aren’t likely to reach for it when asked to provide a date in a single empty text field.

And, of course, a single empty text field is what the user is presented with if their browser does not provide a user interface for picking dates. In those cases, it then becomes very difficult for a user to enter a valid date value unless they happen to be familiar with the format required or the input is annotated with clear instructions.

Many browsers do provide a good user interface for picking dates, however. Firefox has a really excellent date picker, and Chrome and Edge also have pretty good interfaces. However, there’s no support in poor old IE and none in Safari, which could be an issue.

Can I Use input-datetime? Data on support for the input-datetime feature across the major browsers from caniuse.com.

Recommendation

While convenient where it works, the failure mode of type="date" and its associated date and time types is very poor. This makes it a risky choice that could leave users struggling to meet validation criteria.

Conclusion

A lot has changed in the browser landscape in the four years since the HTML5 specification became a recommendation. Support for the newer types of input is fairly strong — particularly in mobile devices with virtual keyboards such as tablets and phones. In most cases, these inputs are safe to use and provide some extra utility to the user.

There are a couple of notable exceptions, the worst of which being the date and time fields, which not only lack utility, but also have more patchy browsers support. When support isn’t available, the fallback mode of these fields is poor. In these cases, it might be best to stick to JavaScript-based solutions for progressively enhancing the basic type="text" input fields.

If you’d like to read more, I’d thoroughly recommend the MDN web docs on these field types, and as ever, the W3C specification.

https://cdn.jsdelivr.net/gh/ireade/caniuse-embed/caniuse-embed.min.js

Smashing Editorial
(ra, il)

Source: Smashing Magazine, HTML5 Input Types: Where Are They Now?

How Improving Website Performance Can Help Save The Planet

dreamt up by webguru in Uncategorized | Comments Off on How Improving Website Performance Can Help Save The Planet

How Improving Website Performance Can Help Save The Planet

How Improving Website Performance Can Help Save The Planet

Jack Lenox



You may not think about it often, but the Internet uses a colossal amount of electricity. This electricity needs to be produced somewhere. In most countries, this means the burning of fossil fuels. This, in turn, means that the Internet’s carbon footprint has grown to the point where it may have eclipsed global air travel, and this makes the Internet the largest coal-fired machine on Earth.

The Mozilla Internet Health Report 2018 states that — especially as the Internet expands into new territory — “sustainability should be a bigger priority.” But as it stands, websites are growing ever more obese, which means that the energy demand of the Internet is continuing to grow exponentially.

All the while, the impacts of climate change grow worse and more numerous with each passing year. The vast majority of climate scientists attribute the increasing ferocity and frequency of extreme weather events around the world to climate change, which they largely attribute to human activity. While some question the science, even the world’s largest oil companies now accept it, and concede that their business models need to change.

Every country on Earth (with the exception of the US), is signed up to the Paris Climate Agreement. Although the US controversially pulled out, many of America’s most influential individuals, cities, states, and companies — representing more than half the US population and economy — have retained their commitment to the agreement by way of the America’s Pledge initiative.

As web developers, it’s understandable to feel that this is not an issue over which we have any influence, but this isn’t true. Many efforts are afoot to improve the situation on the web. The Green Web Foundation maintains an ever-growing database of web hosts who are either wholly powered by renewable energy or are at least committed to being carbon neutral. In 2013, A List Apart published Sustainable Web Design by James Christie. For the last three years, the SustainableUX conference has seen experts in web sustainability sharing their knowledge across an array of web-based disciplines.

Since 2009, Greenpeace has been putting pressure on big Internet companies to clean up their energy mix by way of their Clicking Clean campaign. Partly as a result of this campaign, Google announced last year that for the first time it had purchased enough renewable energy to match 100% of its global consumption for operations.

So, apart from powering servers with renewable energy, what else can web developers do about climate change?

“You Can’t Manage What You Can’t Measure”

Perhaps the biggest win when it comes to making websites more sustainable is that performance, user experience and sustainability are all neatly intertwined. The key metric for measuring the sustainability of a digital product is its energy usage. This includes the work done by the server, the client and the intermediary communications networks that transmit data between the two.

With that in mind, perhaps the first thing to consider is how do we measure the energy usage of our website? This is actually a trickier undertaking than you might imagine, and it’s difficult to get precise data here. There are, however, some good fallbacks which we can use that demonstrate energy usage. These include data transfer (i.e. how much data does the browser have to download to display your website) and resource usage of the hardware serving and receiving the website. An obvious metric here is CPU usage, but memory usage and other forms of data storage also play their part.

Data transfer is one thing that we can measure quite easily. All of the major browsers provide developer tools that allow us to measure network activity. In this screenshot below, for example, we can see that loading the Smashing Magazine website for the first time incurs just under a megabyte of data transfer. Firefox’s developer tools actually provide us with two numbers: the first is the uncompressed size of the files that have been transferred, and the latter is the compressed size.


SmashingMag - Firefox Developer Edition
(Large preview)

The most common tool for compressing assets as they travel across the network is gzip, so the difference between those two numbers is typically a result of gzip’s work. This latter number represents how much data has actually been transmitted and is the one to keep an eye on.

Note: There are plenty of other tools that provide us with a metric for data transfer including the much revered WebPagetest.

For measuring CPU usage, Chrome provides us with a granular Task Manager that shows the memory footprint, CPU usage and network activity of individual tabs. For the more adventurous/technical, the top (table of processes) command provides similar metrics on most Unix-like operating systems such as macOS and Ubuntu. Generally speaking, we can also run the top command on any server to which we have shell access.

Fortunately, there are efforts such as WebsiteCarbon and Ecograder that seek to translate these metrics into a specific CO2 figure (in the case of WebsiteCarbon) or a score (in the case of Ecograder).

Sustainable Web Design

Now we know how to measure the impact of our site, it’s time to think about how we can optimize things to make it more sustainable, more performant, and generally a better experience to use.

There are some existing works we can draw on to help us here. In 2016, O’Reilly published “Designing For Sustainability” by Tim Frick. In this book, Tim takes us on a tour of the whys and hows of sustainable design. But we can also draw on a wealth of existing ideas, conference talks and articles which — while not having an explicit focus on sustainability — have a huge overlap with the philosophy of sustainable web design. Particularly good examples here are Brad Frost’s side-project, “Death To Bullshit”, Heydon Pickering’s articles and talks about writing less damn code, and Adam Silver’s blog post, “Designing For Actual Performance.”

If we’re doing a complete redesign of a website, or starting a new one from scratch, we can start with some really high-level questions here. For example, what actually deserves or needs to be on a homepage? And more specifically, what value does each element on a homepage bring? As Heydon Pickering puts it:

“The most performant, accessible and easily maintainable feature of a website is the one that you don’t make in the first place.”

I work on the WordPress.com VIP team, so in this vein, I decided to challenge myself by putting together a minimalist WordPress theme to see how far I could take the techniques of sustainable web design. The result is a theme called Susty, and it can be seen in action on the accompanying website I put together: sustywp.com. In that particular example, the website is delivered in just over 6KB of data transfer, which feels good given that the median website is about 1.5MB.

So, what did I do? Well, I’ll tell you.

Reduce Network Requests

As I have outlined above, network requests are something we can easily measure, so they make for a good starting point. In putting Susty together, I noticed there were a number of HTTP requests going on that didn’t appear to be necessary. For example, WordPress bundles some CSS and JavaScript that detects the usage of emojis and makes sure they don’t appear as illegal characters. There’s nothing inherently wrong with this, but if you aren’t planning to use emojis, or you’re happy and confident that the various system defaults will have you covered, you can prevent these from loading.

This represents a relatively meager saving, but by establishing a philosophy of pruning unwanted code and requests from our pages, we can make much more significant performance improvements. For example:

  • Are we loading the whole of jQuery for some basic DOM operations?
    Could we achieve the same ends with pure JavaScript? You can read about more advanced dead code elimination (aka tree shaking) in this post for Google by Jeremy Wagner.
  • Do we have a carousel of images?
    Do we really need all those images? Are they significantly enhancing the user experience? Or could we reduce it to just one, strong image? Or even randomly show one of a selection of images, to give a sense of dynamism to returning users? By the way, the research that has been done here shows that most users neither like nor engage with carousels.
  • If we are using a lot of images, would we benefit from providing our images using the WebP format for those browsers that support it?
    For the longest time, WebP’s support has been frustratingly limited. But with Firefox due to begin support for it in version 65 (due in January 2019), it’s only a matter of time before remaining stragglers like Safari catch up.
  • Are we loading hundreds of kilobytes of web fonts?
    Are we using all of the web fonts that we’re loading? Do we even need web fonts? Most devices these days have a stack of half-decent fonts, could we just specify a list of fonts we’d like to see arranged by preference? If we must use web fonts, we should make sure our fonts are as performant as is reasonably possible.
  • Are we embedding YouTube videos?
    An embedded YouTube video typically adds about a megabyte of data transfer before anyone even interacts with it. If only a fraction of our users are actually going to sit and watch the embedded video on our website, could we just link to it instead?

Scrutinise Everything

In this vein, we can also interrogate every aspect of our pages. What really deserves to be there? Does our sidebar add any real value, or have we just put one there because convention dictates that websites have sidebars? So, we’ve added one and filled it with crap.

With Susty, I’ve experimented with the somewhat unorthodox approach of relegating the navigation to its own page. This allows me to have pages that are stripped down to literally the bare essentials, with additional content only being loaded at the user’s explicit request. Susty is so lightweight and so fast that I realized through some user research (aka my partner) that the loading of the menu didn’t really feel like a new page, so I decided to make it look like an overlay, with a cross to dismiss that actually just takes you back to the previous page.

As well as helping me to create pleasingly lightweight pages, the relegated navigation also removes the need for any fancy hide/reveal code for showing it. At this point, I’d like to make it clear that Susty is an example of taking sustainable web design techniques to an extreme (I’m not suggesting it’s an archetype of a good website).

Write CSS Like Your Grandmother

When it comes to serious performance enhancement, we should bear in mind that literally every character of code counts. Every character represents a byte, and even after they’ve been compressed by gzip, they’re still taking up weight. CSS is a domain where we often see a lot of bloat. Fortunately, there are a growing number of increasingly complex tools that can help you weed out unused CSS. This fantastic post by Sarah Dayan outlines how she reduced her CSS bundle from 259KB to 9KB!

If we’re starting from scratch, perhaps we should think more deeply about how we write CSS in the first place. Heydon Pickering wrote an excellent post about how we can write CSS in a way that plays to the strengths of how the syntax was designed, and how this can help developers prevent repetition. Heydon also points out how much wastage goes on with excessive usage of divs and classes — both in HTML and CSS.

What Are You Analyzing?

It seems to have become more-or-less ubiquitous on the web for everyone to analyze what their website’s visitors do via tools like Google Analytics, KISSmetrics, Piwik, etc. While I have no doubt that there are legitimate use cases, do we really need analytics on every website? I, for one, have typically added Google Analytics to every site I manage as a matter of course. But it dawned on me relatively recently that for most of the websites in question, this has been an almost completely pointless endeavor: “Oh, six people came to this post via Facebook today.” Who cares?

Unless you really need it, and you’re going to analyze and act upon the data, just ditch analytics and find a better way to spend your time than gawping at the mundanity of how many people visited website X today.

As well as adding to your page weight, usage of something like Google Analytics raises ethical questions around the data you’re collecting on your users on Google’s behalf, i.e. there’s a reason Google provides you with Analytics for free.

Let’s Not Forget The Basics

There’s so much information around these days about the following, but we should never get complacent and forget about them. Alongside everything above, we absolutely should always minify HTML, CSS, and JavaScript, and concatenate where appropriate. We should also compress all images to ensure they are as small as possible, use the right formats in the right settings, and use progressive rendering.

Server-Side Performance

So far, our focus has been almost entirely on the front-end, but a lot of this is made irrelevant if we don’t also optimize things on the server-side. I’ve already mentioned it a couple of times, but we should absolutely enable gzip compression at all times.

We should make serving our website as easy for our server as possible. I predominantly use Nginx, and I have a particular fondness for FastCGI cache and have found it to be especially efficient. If you have shell access to your own server, here’s a post that explains how to configure it. There are less technical options if you don’t have (or don’t want) as much control over your server. A particular favorite in the WordPress space is WP Super Cache.

We should use HTTP2 over HTTPS. Using HTTPS opens up a world of new web technologies like service workers that allow us to treat the network itself as a nice-to-have. If you want to learn more about this, I highly recommend Jeremy Keith’s new book, “Going Offline.”

Note: You also may want to investigate Google’s PageSpeed Module, available for both Apache and Nginx.

Finally, the biggest impact we can have here is to host our websites in data centers powered by renewable energy. In the UK, I can highly recommend Krystal and Kualo in terms of companies with which I directly host my sites. (For a full directory of green web hosts, check out The Green Web Foundation.)

In Conclusion

I hope I have convinced you that it’s worth putting in the effort to make our websites more sustainable. Especially given that in the process we also make our websites:

  • More performant,
  • More user-friendly,
  • More accessible,
  • More server-friendly,
  • Better optimized for search engines.

A response that some people have to the idea of sustainable web design — which is not unreasonable — is that it seems to be a very small concession to the environmental cause. Of course, how much of an impact you can have depends on how busy the websites are that you work on. But as well as helping the web become a bit more environmentally friendly, sustainable web design is fundamentally best practice web design.

It’s also worth thinking about offsetting the carbon emissions that you can’t avoid. Carbon offsetting is sometimes derided, and with good cause. The main problem with offsetting is that typically the term over which carbon will be offset is quite long. For example, with tree planting, the figure given for an amount of carbon sequestering is typically based over a 100-year period. So, in terms of reducing carbon emissions now, it’s not really a solution. But it is better than nothing.

The motto of myclimate is to do your best, and offset the rest. I have written a blog post about rolling your own carbon offset scheme. I also highly recommend the 1% For The Planet initiative. Finally, if you are a business owner and would like to join an alliance of companies that want to see better social, environmental and economic justice, check out the Certified B Corporation scheme.

Smashing Editorial
(ra, il)

Source: Smashing Magazine, How Improving Website Performance Can Help Save The Planet

Web Standards: The What, The Why, And The How

dreamt up by webguru in Uncategorized | Comments Off on Web Standards: The What, The Why, And The How

Web Standards: The What, The Why, And The How

Web Standards: The What, The Why, And The How

Amy Dickens



The World Wide Web is an interesting place.

As the Internet has grown and become more common place, it has become a gigantic instrument of change in terms of the way in which we interact with the world and each other.

Like many people, my intro to web development at school was kind of bleak. Our school ICT (Information Computing Technology) lessons taught us very little, using Dreamweaver (back when it was a Macromedia product) as a platform to visually edit a personal website with the biggest lesson being “what is a hyperlink”. We didn’t even view the HTML source of our own websites!

So my education around HTML and CSS came largely from messing around with the “view source” option in websites. I learned through copy-pasting bits and pieces together to create my own websites and downloading templates for bootstrap, before I knew what bootstrap actually was.

Why Am I Telling You This?

Having recently surveyed my Twitter followers (it’s an exact science 😜), I discovered that a large chunk of people (43% of the people who voted), knew little to nothing about Web Standards and only 5% of those who voted were active contributors.

https://platform.twitter.com/widgets.js

When you look at the ways in which people learn to do web development, it is totally understandable that this might be the case. The volume of online tutorials, boot-camps and online resources for learning how to build websites has lead to an increasing amount of self-taught web developers (like me) building stuff for the web.

This is one of the great successes of the Internet; anyone can learn almost anything  —  and there being more and more resources for learning outside of academia is really positive in terms of lowering barriers to access web development as a career.

Even with free resources online there are still a number of barriers in learning how to be a web developer. I’m not saying these don’t exist — they really do — and we should be doing more as a community to tackle these.

But with the diversification of learning processes comes several challenges, including information overwhelm and knowledge gaps.

When learning how to build web-flavored things, it is very easy to get wrapped up in “how do I build the thing?” This can result in not equally considering the “why should I build it this way?” or “what are all the options for building the thing?

Consequently, it is equally as easy to become overwhelmed with the many number of ways to solve your web related problem. This can result in picking the first solution from the results of an internet search, without considering whether it is the better (in terms of most robust, accessible and secure) of the options available. 

Web Standards and the documentation to support Web Standards, provide a lot of insight about ‘the why’ and ‘the what’ of the world wide web. They are a fantastic resource for any web developer and help you to build things for the web that are functional, accessible and cross-compatible.

This post is designed to help anyone with an interest in the web who wants to get to know more about web standards. We will cover:

  • An introduction to web standards (what are they, why do they exist and who makes them);
  • How to navigate and make use of standards in your work;
  • Ways you can get involved in contributing to new and existing standards.

Let’s begin our introduction to web standards by asking, “Why do we need standards for the web?

The World Wide Web Before Standards

We can think of the world wide web as an information ecosystem. People create content that is fed into the web. This content is then passed through a browser to allow people to access that information. 


An illustration the world wide web as an information ecosystem
(Large preview)

Before Web Standards, there weren’t many fixed rules for any part of this system; no formal rules as to how the content should be created, nor any requirements in terms of how a browser should serve up that information to the people that are requesting it.

So, in a way, the web operated a bit like that children’s toy where you have to sort the different shaped blocks into the correct holes. In this analogy, the different types of browsers are the different shaped holes and the content or websites, are the brightly colored blocks.


The sorting shape toy and its differently shaped coloured blocks
The sorting shape toy and its colorful blocks (Large preview)

In the past, as a content creator you would make a website to fit the browser it would be intended for. For example, you would create an IE-shaped block to be able to pass this through the Internet Explorer hole.

This meant that this website block you had created would only fit through that one hole and you would need to rebuild your content into other shapes for it to be viewed using any of the other browsers.


Fitting an internet explorer sized block into an internet explorer sized hole
Fitting an IE-sized block into an IE-sized hole (Large preview)

Developers in the 90s would often have to make three or four versions of every website they built, so that it would be compatible with each of the browsers available at the time. And what is more, browser makers in attempts to better their competition would introduce “features” that diversified their approach from their competitors.

In the beginning, it was probably fairer to say our Internet browser to content-matching toy looked more like this:


A sorting toy with three round holes and one square hole
A sorting toy with three round holes and one square hole (Large preview)

This was because browsers were built to handle pretty much the same stuff, which was largely text-based content. So, for the most part, a website block would fit through the majority of the holes, with the exception of maybe one where it might fit — but not perfectly. 

As the browsers developed, they begin to add features (e.g. by changing their shape) and it became more and more difficult to make a block that would pass through each of the browser holes. This even meant that a block that could once fit through one particular hole, didn’t fit through that hole any longer; adding these features into the browser would often result in poor reverse compatibility.


Four versions of a hole that starts out circular but changes with each version to become more diamond like in shape.
A hole that changes over time means all blocks will not always fit through. (Large preview)

This was really damaging for some developers. It created a system in which compatibility was limited to the content creators that could afford to continuously update and refactor their websites for each of the available browsers. For everyone else, every time a new feature or version was released, there was a chance your website would no longer work with that browser.

Web standards were introduced to protect the web ecosystem, to keep it open, free and accessible to all. Putting the web in a protective bubble and disbanding with the idea of having to build websites to suit specific browsers.


Putting the web in a protective bubble and disbanding with the idea of having to build websites to suit specific browsers.
(Large preview)

When standards were introduced, browser makers were encouraged to adhere to a standardized way of doing things — resulting in cross-compatibility becoming easier for content makers and there no longer being the need to build multiple versions of the same website.

Note: There are still a number of nuances about cross-compatibility amongst browsers. Even today, over 20 years since standards were introduced, we aren’t quite at “one-size fits all” just yet.

Here’s a quick look at some of the key moments in the history of web browser development:

Year Key moments
1990 Sir Tim Berners Lee releases the WorldWideWeb, the first way in which to browse the web.
1992 MidasWWW was developed as another WWW browser, which included a source code viewer.
1992 Also in 1992 Lynx was released, which was a text-based web browser, it could not display images or any other graphic content.
1993 NCSA Mosaic was released, this is the browser that is credit for being the first to popularize web browsing as it allowed the display of image embedded within text.
1995 Microsoft released Internet Explorer, previously Cello or Mosaic browsers were used on Windows products.
1996 Opera was released publicly, it was previously a research project for a Norwegian telecoms company Telnor.
2003 Safari was released by Apple, previously Macintosh computers shipped with Netscape Navigator or Cyberdog.
2004 In the wake of Netscape Navigator’s demise, Firefox was launched as a free, open-source browser.
2008 Chrome was launched by Google and within six years grew to encompass the majority of the browser market.
2015 Microsoft released Edge, the new browser for Microsoft, replacing Internet Explorer from Windows 10 onwards.

Source: “Web Browsers: A Brief History” by Rhiannon Williams

Why We Need Standards

Knowing a bit about the history of standards and why they were introduced, we can start to see the benefits of having standards for the World Wide Web. But why is it important that we continue to contribute to Web Standards? Here are just a few reasons: 

Keeping The Web Free And Accessible To All

Without the Web Standards community, browser makers would be the ones making decisions on what should and shouldn’t be features of the world wide web. This could lead to the web becoming a monopolized commodity, where only the largest players would have a say in what the future holds.

Helping Make Source Code Simpler; Reducing Development And Maintenance Time

As more browsers appeared and browser makers began to diversify in their approach, it became more and more difficult to create content that would be served in the same way across multiple browsers. This increased the amount of work required to make a fully compatible website, including bloating the source code for a web page. As developers today we still have to do the odd include [X script] so this works on [X web browser], but without Web Standards, this would be much worse.

Making The Web A More Accessible Place

Web standards help to standardize the way in which a website can interact with assistive technologies. Meaning that browser makers and web developers can incorporate instructions into their pages which can be interpreted by assistive technologies to maintain a common (or sometimes better) end-user experience.

Allowing For Backward Compatibility And Validation

Web standards have created a foundation which allows for new websites, that comply with standards, to work with older browser versions. This idea of backward compatibility is super important for keeping the web accessible. It doesn’t guarantee older browsers will show your content exactly as you expect, but it will ensure that the structure of the web document is understood and displayed accordingly. 

Helping Maintain Better SEO (Search Engine Optimization)

Another of the major hidden benefits (at the time that Web Standards was first introduced) was that a Web Standards compliant website was more discover-able by search engines. This became more evident when the Google search became the major player in the search engine world in the early 2000s.

Creating A Pool Of Common Knowledge

A world with web standards creates a place in which a set of rules exists, rules that every developer can follow, understand and become familiar with. In theory, this means that one developer could build a website that complies with standards and another developer could pick up where the former left off without much trouble. In reality, standards provide the foundation for this; but the idea relies heavily on developers writing well-documented code. 

Who Decides On What Becomes A Web Standard?

Standards are created by people. In the web and Internet space, there is a strong culture of consensus — which means a lot of talking and a lot of discussions.

The groups through which standards are developed are sometimes referred to as “Standards Development Organisations” or SDOs. Key SDOs in the web space include the Internet Engineering Task Force (IETF), the World Wide Web Consortium (W3C), the WHATWG, and ECMA TC39. Historically there were also groups like the Web Standards Project (WaSP), that advocated for Web Standards to be adopted by organizations.

The groups that work on the Internet and Web Standards generally operate under a royalty-free regime. That means when you make use of a web standard you don’t have to pay anyone — like someone who might hold a relevant patent. Whilst the idea that you might have to pay royalties to someone to build a web browser or website might seem absurd right now, it wasn’t too long ago that organizations like BT were trying to assert ownership of the concept of the hyperlink. Standards organizations like the ones listed below help keep the web free (or free from licensing fees at least).

What Is IETF?

The IETF is the grandparent of Internet standards organizations. It’s where underlying Internet technologies like TCP/IP (Transmission Control Protocol/Internet Protocol) and DNS (Domain Name System) are standardized. Another key technology developed in IETF is something called Hyper-Text Transport Protocol (HTTP) which you may have heard of.

If you’ve been paying attention to the rise of HTTP2 and the subsequent development of (UDP-based) HTTP3, this is where that work happens. Most of the work in IETF is focused on the lower levels of the Open Systems Interconnection model.

What Is W3C?

The World Wide Web Consortium (W3C) is an international community where member organizations, a full-time staff, invited experts and the public work together to develop Web Standards. Led by Web inventor and Director Tim Berners-Lee and CEO Jeffrey Jaffe, W3C’s mission is to lead the Web to its full potential.

The community was founded in 1994 at MIT (Massachusetts Institute of Technology) in collaboration with CERN. At the time of this post, W3C has 475 member companies and organizations and exists as a consortium between 4 academic institutions: MIT (USA), ERCIM (France), KEIO University (Japan) and Beihang University (China).

Work in W3C happens in working groups and community groups. Community groups are where a lot of initial innovation happens around new web technologies. New web standards can be produced by community groups but they are officially seen as “pre-standard.” Community groups are open for anyone to participate, whether or not the organization you work for or are affiliated with is a W3C member.

W3C working groups are where new web standards are officially minted. Working groups usually start with a submission of a standard, often something that is already shipping in some browsers. However, technical work on refining these standards happens within these groups before the standard goes for final approval as a “W3C Recommendation.” By the time something reaches “recommendation” phase in W3C, it’s most often implemented and in wide use across the web. 

Working groups are more difficult for people who are not affiliated with a member organization to become a part of. However, you may become an invited expert to a group. One reason why working groups are a little more difficult to join and operate with more process is that they also act as an intellectual property holder  —  through joining a W3C working group organizations and companies agree to the royalty-free licensing laid out in W3C’s patent policy.

W3C Advisory Board member Natasha Rooney has put together a great document, W3C Process Document for Busy People, that explains a lot of the ins and outs of working in W3C.

What Is The WHATWG?

The WHATWG was originally a splinter group from the W3C. It was formed in 2007 because some browser vendors didn’t agree with the direction in which the W3C was pushing HTML. WHATWG continues to be the place where HTML is developed and evolved. However, the community of participation in the HTML specification still includes many people from the W3C community, and many WHATWG-affiliated people participate in W3C working groups. 

At the time of this post, the relationship between the W3C and the WHATWG remains in flux. From a developer perspective, this doesn’t matter too much because developers can rely on resources like MDN to reflect the “truth” of which web technologies can be used in specific browsers. However, it has led to a lack of clarity, in terms of where to participate in the development of certain standards. WHATWG also has its own royalty-free license agreement  — the WHATWG participation agreement

What Is The “Why CG”?

The Web Incubator Community Group (WICG, pronounced Why-CG) is a special community group, within W3C, where some new and emerging web technologies are discussed and developed.

If you have a great idea for a new standard, a new feature for an existing standard or a new technology you think ought to be incorporated into the web, it’s worth checking here first to see if something like it is already being discussed. If it is, great! Jump into these discussions and lend your support. If not, then suggest it! That’s what this group is for.

What Is The ECMA TC39?

Ecma is a standards organization for information and communication systems, which was founded in 1961 to standardize computer systems in Europe. Its name comes from being previously known as the “European Computer Manufacturers Association” but it is now referred to as “Ecma International  —  European association for standardizing information and communication systems” since the organization went global in 1994.

The ECMA-262 standard outlines the ECMAScript Language Specification, which is the standardized specification of the scripting language known as JavaScript. There are ten editions of ECMA-262 that have been published (the tenth edition was published in June 2018).

TC39 (Technical Committee 39) is the committee that evolves JavaScript. Like the other groups listed here, its members are companies which include most of the major browser makers. The committee has regular meetings which are attended by delegates sent from the member organizations and also by invited experts. The TC39 operates on achieving consensus, as with many of the other groups, and the agreements made often lead to obligations for its members (in terms of future features that member organizations will need to implement). The TC39 process includes accelerating proposals through a set of stages, the progression of a proposal from one stage to the next must be approved by the committee. 

What Was The Web Standards Project?

The Web Standards Project was formed in 1998 as a resistance to the feature face-off happening between browsers in the 90s; with a primary goal of getting browser makers to comply with the standards set forth by the W3C.

As the organization grew and the browser wars ended, the project began to shift focus. The group began working with browser makers on improving their standards support, consulting software makers that created tooling for website creation and educating web designers and developers on the importance of web standards. The last of these points, resulted in the creation of the InterAct web curriculum framework which is now maintained by W3C.

The Web Standards Project ceased to be active in 2013. A final blog post was created on March 1st that gives thanks to the hard work of the members and supporters of the project. In the closing remarks of this post, readers are reminded that the job of the Web Standards Project is not entirely over, and that the responsibility now lies with thousands of developers who continue to care about ensuring the web remains a free, open, inter-operable and accessible resource.

How Does Something Become A Web Standard?

So, how are standards made? The short answer is through LOTS of discussions.

Proposals for new standards usually start as a discussion within a community group (this is especially the case in W3C) or through issues raised on the relevant GitHub repository.

Across the different SDOs, there seems to then be a common theme of ascension; after the discussion has begun, it then moves up within the organization, and at each level, a deciding committee needs to reach a consensus to approve the elevation of that discussion. This is repeated until the discussion becomes a proposal, then that proposal becomes a draft and the draft goes on to become an official standard. 


After an idea has been presented, a discussion begins among a deciding committee that needs to reach a consensus to approve the elevation of that discussion. This is repeated until the discussion becomes a proposal, then a draft, and finally an official standard.
(Large preview)

Now as previously mentioned, when something isn’t an official standard, this does not necessarily mean that it is not in use within some browsers. In fact, by the time something becomes a standard, it is likely to already have widespread use across many of the available browsers. In this instance, the role of the standard is part of the normalizing and adoption process for new features; it sets out the expected use for something and then outlines how browser makers and developers can conform to this expectation. 

What Is TPAC?

Every year, W3C holds one massive event, a week-long multi-group meeting punctuated by a one-day unconference on the Wednesday (the Technical Plenary) combined with a meeting of its Advisory Committee (a group consisting of one person for every organization or company that is a W3C member). Put Technical Plenary and Advisory Committee together, and you get TPAC (often pronounced tee-pac). Although it’s a W3C-run event, you will often find people “from” WHATWG, IETF or TC39 here as well.

This past year, Samsung Internet people came together to participate in TPAC. We also sponsored diversity scholarships which are intended to bring people from under-represented groups to TPAC and to the Web Standards community.

My First TPAC

When I first heard the team talking about TPAC, I had no idea what to expect. After reading up about the event on the TPAC website, I signed myself up and booked my travel. Soon enough, I was on a train from London to Lyon with the team. 


The banner at the front entrance of the TPAC venue
The banner at the front entrance of the TPAC venue (Large preview)

On arrival, I was given my Lanyard and a map of the various rooms where all the action was happening. My goal, for the three days I was attending, was to join in with as much accessibility type things as I could. Having arrived shortly after things had begun on my first day, I stood staring at a closed door for the Accessibility Guidelines working group that I wanted to sit in on. Lots of things went through my mind at that moment; “Perhaps I should wait until the break?” “No, don’t be silly, that’s still an hour away.” “Maybe I should knock?” “But wouldn’t that be more interruptive than just going in?” “Maybe I shouldn’t go in at all…” But after a few minutes, I worked up the courage to walk into the room.
 
There was a round table set up (which is typical of a lot of these sessions) with folks sitting at the tables with laptops; along with a number of seats arranged around the edge of the room for people to join in a more observational role. Each group also had a chat room on IRC, which anyone from the W3C membership could join (whether attending TPAC in person or not). I sat at the end of one of the tables; though I’m still not sure whether that was the proper thing to do in terms of etiquette. 


The gigantic bear statue outside of the Cité Centre de Congrès de Lyon, which was the venue for TPAC 2018.
The gigantic bear statue outside of the Cité Centre de Congrès de Lyon, which was the venue for TPAC 2018. (Large preview)

Initially, I was worried that my presence stuck out as much as the gigantic bear statue outside the venue; but no-one in the room paid any mind to my arrival and so the discussion continued. The group was about to move onto receiving an update on the work being done by the Silver Task Force; a community group that is trying to make the accessibility standards themselves more accessible. 

It was really interesting to sit at the table for these discussions. Whilst as a first-time attendee, some of the language took some getting used to (terms like ‘conformance’ and ‘normative’); it was super nice to be inside of a room full of people who cared so much about accessibility. Many of the attendees of this working group spoke from a position of lived experience in terms of using the web with an accessibility requirement. Having spent my last three years researching accessibility requirements in digital music technology, I felt quite at home following along with the questions raised by the members of this group.

The work showcased by the Silver Task Force in this first discussion really sparked an interest for me. It felt like quite a refreshing viewpoint of how to make standards, in general, more accessible and frame them in such a way that makes for easier navigation and more tailored advice and guidance. For the following few days, I joined this (much smaller) group and had the chance to input into the conversations  —  which was really positive. Since TPAC, I have joined the community group for the Silver Task Force and have plans to join the weekly meetings in the new year. 


The Samsung group posing for an after-dinner picture around the table
Our Samsung group out to dinner during the week TPAC. (Large preview)

One of the nice things about TPAC (for those not chairing a working group or in some sort of leading role) was the ability to dip in and out of sessions. In amongst the things I attended over the few days I was at TPAC, there was a session from the Web Incubator community group (WICG), a developer meet-up with talks from prominent community members and demonstrations of new web technologies, and a Diversity and Inclusion for W3C meeting. An extra added bonus of going to TPAC with the Samsung Internet team was that we got to meet up with people from our team based in Korea, as well as other Samsung team members from the USA. 

How To Use Web Standards In Your Work

So, now that you know the why and wherefore of Web Standards, how do you go about using web standards in your work?

Mozilla Developer Network Web Docs (MDN Web Docs)

We (the Samsung Internet team) recommend that if you’re interested in learning more about a particular web standard or technology, you start with the MDN (Mozilla Developer Network) Web Docs. Whilst MDN WebDocs started as Mozilla Project, more recently it has become the place web developers go for cross-browser documentation on web platform technologies.


The MDN web docs homepage
The MDN Web Docs homepage (Large preview)

Last year, Samsung joined Bocoup, Google and Microsoft and W3C to form the MDN WebDocs Product Advisory Board to help ensure that MDN maintains this position.

When you search a technology in MDN, you will see a browser compatibility matrix letting you know what the browser support is. You will also find a link to the most relevant and up to date version of the standard. When you follow a link to a standard, you will be directed to the relevant web page outlining that standard and its technical specifications. These pages can be a little overwhelming at first, as they are somewhat ‘academic’ in structure. 

To give you some tips on navigating the documentation, let’s take a look at a standard I’m most familiar with: the W3C Web Content Accessibility Guidelines (2.1).


The Web Content Accessibility Guidelines (WCAG 2.1) web standard home page
The WCAG 2.1 web standard home page (Large preview)

This is the format of a W3C web standard. It features a table of contents on the left-hand side of the page while the content is organized into very structured headers — starting with the version, reports and editors details. These headers in standards are often used to quote the relevant parts of a standard “Oh, but WCAG 2.1 1.2.2 says”; but for those without the alphanumeric memory of a hard-disk, do not fear, it is not a requirement that you have to know these things by heart.

My first piece of advice about navigating web standards is to try not to be overwhelmed by these. If you’ve come from the non-academic route into web development like me, the structure of these documents can at first seem quite formal, and the language can feel this way, too. Don’t let this be a reason to navigate away from using this as a source of information  —  as quite frankly it is the best source of information available for finding out how and why web things work in the way that they do.

Here are some quick tips for working with web standards:

  • The TL;DR version
    Firstly, it’s important to understand that there isn’t a TL;DR for web standards. The reason they are these long and comprehensive documents is because they have to be. There can’t be any stone unturned when it comes to exacting the structure and expected us of web development things. However (a pro tip, and a way to avoid information overwhelm), is to start with the abstract of the standard and follow any links to introductory documents. In my example, the WCAG 2.1 standard document leads us to another linked page for the Web Content Accessibility Guidelines Overview. Which provides a range of useful documentation including a quick reference guide on how to meet WCAG 2

The homepage for the Web Content Accessibility Guidelines Overview
The homepage for the WCAG Overview (Large preview)
  • Make use the glossary of terms
    This just helps to understand the exact meaning of words and phrases in the context of the web standard . Let’s face it; there are so many terms out there with multiple meanings. Checking out the glossary also helps navigate some of the more academic terms.

The WCAG 2.1 Glossary section, which provides contextual definitions of words and phrases used within the standard.
The WCAG 2.1 Glossary section, which provides contextual definitions of words and phrases used within the standard. (Large preview)
  • ‘Find in page’ is your friend
    Once you have familiarized yourself with an overview and got an idea about the terms used within a web standard, you can start to search through the documentation for the information you require. The web standards are designed in such a way that you can consume them in a number of ways. If you seek to gain a comprehensive understanding then reading from start to finish is advised; however, you can also drop in and out of the sections as you require them. The good folks creating web standards have made efforts to ensure that referential content is linked to the source and any helpful resources are also included, which helps support the kind of “on demand” usage that is common. Take this example from WCAG 2.1:

WCAG 2.1 Guideline on Text Alternatives, in amongst the text are links to success criterions and other useful guidelines.
WCAG 2.1 Guideline on Text Alternatives, in amongst the text are links to success criterions and other useful guidelines. (Large preview)
  • If you’re not sure — ask!
    This community is put together from a bunch of people who care and have an investment in the future of web technologies. If you want to make sure you are adhering to Web Standards but maybe have got caught up in a language barrier, and you’re struggling to interpret what is meant by a phrase within a web standard, there are many folks out there that can help. You can raise issues through the W3C GitHub repositories for the W3C Web Standards or join the conversations about Web Standards through the suggested resources on the participate section of the W3C website.

How Do I Get Involved?

So, now that you know how to read up on your standards, what about getting involved? 

Well, here are a few places to start: 

  • GitHub repositories for standards
    The WC3, TC39, WhatWG and WICG all have organizations on GitHub that contain repositories for the work they are doing. Be sure to check in on the READme, contribution guidelines and code of conduct (if there is one) before you begin. Use the issues of a repository to look at what is currently being discussed in terms of future developments for the standard it relates to. 
  • The W3C website
    Here you can look at all the working groups, community groups, and forums. It is a great place to start; if you join the organization and become a member of a community group or working group you’ll be invited to the ongoing discussions, meetings, and events for that group.
  • The WhatWG website
    For all things WhatWG. Here there are guides on how to participate, FAQs, links to the GitHub repositories and a blog that is maintained by members of the WhatWG.
  • The WICG website
    Whilst the Web Incubator Community Group can be found from the W3C website, they are worth a separate shout-out here as they have their own web community page and Discourse instance. (For those of you not familiar with Discourse, it allows communities to create and maintain forums for discussion.)
  • The TC39 standard
    This is pretty comprehensive and includes links to the ways in which you can to contribute to the standard. 
  • Speak to Developer Advocates
    Many Web Developer Advocates are members of an SDO or known to be working on standards; teams like ours (the Samsung Internet Developer Advocates) are often involved in the work of Web Standards and happy to talk to developers that are interested in them. After all, standards have a huge impact on the future of the web and in turn the work that we do. So, depending on the web standard that interests you, you’ll be able to find folks like us (who are part of the work for those standards) through social media spaces like Twitter or Mastodon.

Thanks for reading! Remember that web standards impact everyone that builds or consumes websites, so the work of Web Standards is something we should all care about.

If you want to chat more about web standards, accessibility on the web, web audio or open-source adventures  —  you can find me on Twitter and I’m also on Mastodon. ✨

A huge thanks to Daniel Appelquist, who helped bring this article together.

Smashing Editorial
(ra, il)

Source: Smashing Magazine, Web Standards: The What, The Why, And The How

When And How To Use CSS Multi-Column Layout

dreamt up by webguru in Uncategorized | Comments Off on When And How To Use CSS Multi-Column Layout

When And How To Use CSS Multi-Column Layout

When And How To Use CSS Multi-Column Layout

Rachel Andrew



In all of the excitement about CSS Grid Layout and Flexbox, another layout method is often overlooked. In this article I’m going to take a look at Multi-column Layout — often referred to as multicol or sometimes “CSS Columns”. You’ll find out which tasks it is suited for, and some of the things to watch out for when making columns.

What Is Multicol?

The basic idea of multicol, is that you can take a chunk of content and flow it into multiple columns, as in a newspaper. You do this by using one of two properties. The column-count property specifies the number of columns that you would like the content to break into. The column-width property specifies the ideal width, leaving the browser to figure out how many columns will fit.

It doesn’t matter which elements are inside the content that you turn into a multicol container, everything remains in normal flow, but broken into columns. This makes multicol unlike other layout methods that we have in browsers today. Flexbox and Grid for example, take the child elements of the container and those items then participate in a flex or grid layout. With multicol, you still have normal flow, except inside a column.

In the below example I am using column-width, to display columns of at least 14em. Multicol assigns as many 14em columns as will fit and then shares out the remaining space between the columns. Columns will be at least 14em, unless we can only display one column in which case it may be smaller. Multicol was the first time that we saw this kind of behavior in CSS, columns being created which were essentialy responsive by default. You do not need to add Media Queries and change the number of columns for various breakpoints, instead we specify an optimal width and the browser will work it out.

See the Pen Smashing Multicol: column-width by Rachel Andrew (@rachelandrew) on CodePen.

Styling Columns

The column boxes created when you use one of the column properties can’t be targeted. You can’t address them with JavaScript, nor can you style an individual box to give it a background color or adjust the padding and margins. All of the column boxes will be the same size. The only thing you can do is add a rule between columns, using the column-rule property, which acts like border. You can also control the gap between columns using the column-gap property, which has a default value of 1em however you can change it to any valid length unit.

See the Pen Smashing Multicol: column styling by Rachel Andrew (@rachelandrew) on CodePen.

That is the basic functionality of multicol. You can take a chunk of content and split it into columns. Content will fill the columns in turn, creating columns in the inline direction. You can control the gaps between columns and add a rule, with the same possible values as border. So far so good, and all of the above is very well supported in browsers and has been for a long time, making this spec very safe to use in terms of backwards compatibility.

There are some further things you might want to consider with your columns, and some potential issues to be aware of when using columns on the web.

Spanning Columns

Sometimes you might like to break some content into columns, but then cause one element to span across the column boxes. Applying the column-span property to a descendent of the multicol container achieves this.

In the example below, I have caused a <blockquote> element to span across my columns. Note that when you do this, the content breaks into a set of boxes above the span, then starts a new set of column boxes below. The content doesn’t jump across the spanned element.

The column-span property is currently being implemented in Firefox and is behind a feature flag.

See the Pen Smashing Multicol: column-span by Rachel Andrew (@rachelandrew) on CodePen.

Be aware that in the current spec, the values for column-span are either all or none. You can’t span just some of the columns, but you can get the kind of layout you might see in a newspaper by combining multicol with other layout methods. In this next example, I have a grid container with two column tracks. The left-hand track is 2fr, the right-hand track 1fr. The article in the left-hand track I have turned into a multicol container with two tracks, it also has a spanning element.

On the right, we have an aside which goes into the second Grid column track. By playing around with the various layout methods available to us, we can figure out exactly which layout method suits the job at hand — don’t be afraid to mix and match!

See the Pen Smashing Multicol: mixing layout methods by Rachel Andrew (@rachelandrew) on CodePen.

Controlling Content Breaks

If you have content containing headings, then you probably want to avoid the situation where a heading ends up as the last thing in a column with the content going into the next column. If you have images with captions then the ideal situation would be for the image and caption to stay as one unit, not becoming split across columns. To deal with these problems CSS has properties to control where the content breaks.

When you split your content into columns, you perform what is known as fragmentation. The same is true if you split your content between pages, such as when you create a stylesheet for a print context. Therefore, multicol is closest to Paged Media than it is to other layout methods on the web. Because of this, for several years the way to control breaks in the content has been to use the page-break- properties which were part of CSS2.1.

  • page-break-before
  • page-break-after
  • page-break-inside

More recently the CSS Fragmentation specification has defined properties for fragmentation which are designed for any fragmented context, the spec includes details for Paged Media, multicol and the stalled Regions spec; Regions also fragments a continuous piece of content. By making these properties generic they can apply to any future fragmented context to, in the same way that the alignment properties from Flexbox were moved into the Box Alignment spec in order that they could be used in Grid and Block layout.

  • break-before
  • break-after
  • break-inside

As an example, I have used break-inside avoid on the <figure> element, to prevent the caption being detached from the image. A supporting browser should keep the figure together even if that causes the columns to look unbalanced.

See the Pen Smashing Multicol: break-inside by Rachel Andrew (@rachelandrew) on CodePen.

Unfortunately, support for these properties in multicol is pretty patchy. Even where supported they should be seen as a suggestion due to the fact that it would be possible to make so many requests while trying to control breaking, that essentially the browser can’t really break anywhere. The spec does define priorities in this case, however it is probably more useful for you to control only the most important cases.

The Problem Of Columns On the Web

One reason why we don’t see multicol used much on the web is the fact that it would be very easy to end up with a reading experience which made the reader scroll in the block dimension. That would mean scrolling up and down vertically for those of us using English or another vertical writing mode. This is not a good reading experience!

If you fix the height of the container, for example by using the viewport unit vh, and there is too much content, then overflow will happen in the inline direction and so you get a horizontal scrollbar instead.

See the Pen Smashing Multicol: overflow columns by Rachel Andrew (@rachelandrew) on CodePen.

Neither of these things are ideal, and making use of multicol on the web is something we need to think about very carefully in terms of the amount of content we might be aiming to flow into our columns.

Block Overflow Columns

For Level 2 of the specification, we are considering how to enable a method by which overflow columns, those which currently end up causing the horizontal scrollbar, could instead be created in the block direction. This would mean that you could have a multicol container with a height, and once the content had made columns which filled that container, a new set of columns would be created below. This would look a little like our spanning example above, however, instead of having a spanner causing the new column boxes to start, it would be the overflow caused by a container with a restriction in the block dimension.

This feature would make multicol far more useful for the web. While we are a little way off right now, you can keep an eye on the issue in the CSS Working Group repo. If you have additional use cases for this feature do post them, it can really help when designing the new feature.

What Is Multicol Useful For Today?

With the current specification, splitting all of your content into columns without consideration for the problems of scrolling isn’t advised. However, there are some cases where multicol is ideal on the web. There are enough uses cases to make it something you should consider when looking at design patterns.

Collapsing Small UI Or Text Elements

Multicol can be useful in any place where you have a small list of items that you want to take up less space. For example a simple listing of checkboxes, or a list of names. Often in these scenarios, the visitor is not reading down one column and then going back to the top of the next, but scanning the content for a checkbox to click or an item to select. Even if you do create a scrolled experience, it may not be an issue.

You can see an example of multicol used in this way by Sander de Jong on the DonarMuseum
website.


Names are arranged into multiple columns on the DonarMuseum website
On DonarMuseum, we can see multicol used to display lists of names. (Image source) (Large preview)

Known Small Amounts Of Content

There are times when we design a site where we know that some piece of content is relatively small, and will fit on the majority of screens without causing unwanted scrolling. I’ve used multicol on Notist presentation pages, for the introduction to a talk.

Andy Clarke designed a lovely example for the Equfund website.


A two-column layout including various content
On the Equfund website, you can see how different HTML elements remain in normal flow while displayed inside columns. (Image source) (Large preview)

To avoid the possibility of very small screens causing scrolling, remember that you can use media queries to check for height as well as width (or in a logical world, block as well as inline). If you only enable columns at a breakpoint which has a min-height large enough for their content, this can save users of very small devices having a poor scrolling experience.

Masonry-Like Display Of Content

Another place where Multiple-column Layout works beautifully is if you want to create a Masonry type of display of content. Multicol is the only layout method that will currently create this kind of layout with unequal height items. Grid would either leave a gap, or stretch the items to make a strict two-dimensional grid.

Veerle Pieters has a beautiful example of using multicol in this way on her inspiration page.


An arrangement of multiple boxes in columns designed by Veerle Pieters
In this design by Veerle Pieters, multicol is used to layout multiple boxes or cards as columns. (Large preview)

Grid And Flexbox Fallbacks

The column- properties can also be used as a fallback for Grid and Flex layout. If you specify one of the properties on a container, then turn that container into a Flex or Grid layout by using display: flex or display: grid any column behavior will be removed. If you have, for example, a cards layout that uses Grid Layout, and the layout would be readable if it ran in columns rather than across the page, you could use multicol as a simple fallback. Browsers that do not support Grid will get the multicol display, those which support Grid will get the Grid Layout.

Don’t Forget Multicol!

Fairly frequently I answer Grid and Flexbox questions where the answer is to not use Grid or Flexbox, but instead to look at Multicol. You probably won’t use it on every site, but when you come across a use case it can be really helpful. Over at MDN there are useful resources for multicol and the related fragmentation properties.

If you have used multicol on a project, perhaps drop a note in the comments, to share other ways in which we can use the feature.

Smashing Editorial
(il)

Source: Smashing Magazine, When And How To Use CSS Multi-Column Layout