Archive for the ‘Designing’ Category

A Perfect Table of Contents With HTML + CSS

May 25th, 2022 No comments
Misaligned numbers and dots in a table of contents.

To fix this problem, I set font-variant-numeric to tabular-nums so all numbers are treated with the same width. By also setting the minimum width to 2ch, I ensured that all numbers with one or two digits are perfectly aligned. (You may want to set this to 3ch if your project has more than 100 pages.) Here is the final CSS for the page number:

.toc-list li > a > .page {
  min-width: 2ch;
  font-variant-numeric: tabular-nums;
  text-align: right;
Aligned leader dots in a table of contents.

And with that, the table of contents is complete!

CodePen Embed Fallback


Creating a table of contents with nothing but HTML and CSS was more of a challenge than I expected, but I’m very happy with the result. Not only is this approach flexible enough to accommodate chapters and subsections, but it handles sub-subsections nicely without updating the CSS. The overall approach works on web pages where you want to link to the various locations of content, as well as PDFs where you want the table of contents to link to different pages. And of course, it also looks great in print if you’re ever inclined to use it in a brochure or book.

I’d like to thank Julie Blanc and Christoph Grabo for their excellent blog posts on creating a table of contents, as both of those were invaluable when I was getting started. I’d also like to thank Sara Soueidan for her accessibility feedback as I worked on this project.

Earlier this year, I self-published an ebook called Understanding JavaScript Promises (free for download). Even though I didn’t have any intention of turning it into a print book, enough people reached out inquiring about a print version that I decided to self-publish that as well .I thought it would be an easy exercise using HTML and CSS to generate a PDF and then send it off to the printer. What I didn’t realize was that I didn’t have an answer to an important part of a print book: the table of contents.

The makeup of a table of contents

At its core, a table of contents is fairly simple. Each line represents a part of a book or webpage and indicates where you can find that content. Typically, the lines contain three parts:

  1. The title of the chapter or section
  2. Leaders (i.e. those dots, dashes, or lines) that visually connect the title to the page number
  3. The page number

A table of contents is easy to generate inside of word processing tools like Microsoft Word or Google Docs, but because my content was in Markdown and then transformed into HTML, that wasn’t a good option for me. I wanted something automated that would work with HTML to generate the table of contents in a format that was suitable for print. I also wanted each line to be a link so it could be used in webpages and PDFs to navigate around the document. I also wanted dot leaders between the title and page number.

And so I began researching.

I came across two excellent blog posts on creating a table of contents with HTML and CSS. The first was “Build a Table of Contents from your HTML” by Julie Blanc. Julie worked on PagedJS, a polyfill for missing paged media features in web browsers that properly formats documents for print. I started with Julie’s example, but found that it didn’t quite work for me. Next, I found Christoph Grabo’s “Responsive TOC leader lines with CSS” post, which introduced the concept of using CSS Grid (as opposed to Julie’s float-based approach) to make alignment easier. Once again, though, his approach wasn’t quite right for my purposes.

After reading these two posts, though, I felt I had a good enough understanding of the layout issues to embark on my own. I used pieces from both blog posts as well as adding some new HTML and CSS concepts into the approach to come up with a result I’m happy with.

Choosing the correct markup

When deciding on the correct markup for a table of contents, I thought primarily about the correct semantics. Fundamentally, a table of contents is about a title (chapter or subsection) being tied to a page number, almost like a key-value pair. That led me to two options:

  • One option is to use a table (
    ) with one column for the title and one column for the page.
  • Then there’s the often unused and forgotten definition list (
    ) element. It also acts as a key-value map. So, once again, the relationship between the title and the page number would be obvious.
  • Either of these seemed like good options until I realized that they really only work for single-level tables of contents, namely, only if I wanted to have a table of contents with just chapter names. If I wanted to show subsections in the table of contents, though, I didn’t have any good options. Table elements aren’t great for hierarchical data, and while definition lists can technically be nested, the semantics didn’t seem correct. So, I went back to the drawing board.

    I decided to build off of Julie’s approach and use a list; however, I opted for an ordered list (

      ) instead of an unordered list (

        ). I think an ordered list is more appropriate in this case. A table of contents represents a list of chapters and subheadings in the order in which they appear in the content. The order matters and shouldn’t get lost in the markup.

        Unfortunately, using an ordered list means losing the semantic relationship between the title and the page number, so my next step was to re-establish that relationship within each list item. The easiest way to solve this is to simply insert the word “page” before the page number. That way, the relationship of the number relative to the text is clear, even without any other visual distinction.

        Here’s a simple HTML skeleton that formed the basis of my markup:

        <ol class="toc-list">
            <a href="#link_to_heading">
              <span class="title">Chapter or subsection title</span>
              <span class="page">Page 1</span>
              <!-- subsection items -->

        Applying styles to the table of contents

        Once I had established the markup I planned to use, the next step was to apply some styles.

        First, I removed the autogenerated numbers. You can choose to keep the autogenerated numbers in your own project if you’d like, but it’s common for books to have unnumbered forewords and afterwords included in the list of chapters, which makes the autogenerated numbers incorrect.

        For my purpose, I would fill in the chapter numbers manually then adjust the layout so the top-level list doesn’t have any padding (thus aligning it with paragraphs) and each embedded list is indented by two spaces. I chose to use a 2ch padding value because I still wasn’t quite sure which font I would use. The ch length unit allows the padding to be relative to the width of a character — no matter what font is used — rather than an absolute pixel size that could wind up looking inconsistent.

        Here’s the CSS I ended up with:

        .toc-list, .toc-list ol {
          list-style-type: none;
        .toc-list {
          padding: 0;
        .toc-list ol {
          padding-inline-start: 2ch;

        Sara Soueidan pointed out to me that WebKit browsers remove list semantics when list-style-type is none, so I needed to add role="list" into the HTML to preserve it:

        <ol class="toc-list" role="list">
            <a href="#link_to_heading">
              <span class="title">Chapter or subsection title</span>
              <span class="page">Page 1</span>
            <ol role="list">
              <!-- subsection items -->
        CodePen Embed Fallback

        Styling the title and page number

        With the list styled to my liking, it was time to move on to styling an individual list item. For each item in the table of contents, the title and page number must be on the same line, with the title to the left and the page number aligned to the right.

        You might be thinking, “No problem, that’s what flexbox is for!” You aren’t wrong! Flexbox can indeed achieve the correct title-page alignment. But there are some tricky alignment issues when the leaders are added, so I instead opted to go with Christoph’s approach using a grid, which as a bonus as it also helps with multiline titles. Here is the CSS for an individual item:

        .toc-list li > a {
          text-decoration: none;
          display: grid;
          grid-template-columns: auto max-content;
          align-items: end;
        .toc-list li > a > .page {
          text-align: right;

        The grid has two columns, the first of which is auto-sized to fill up the entire width of the container, minus the second column, which is sized to max-content. The page number is aligned to the right, as is traditional in a table of contents.

        The only other change I made at this point was to hide the “Page” text. This is helpful for screen readers but unnecessary visually, so I used a traditional visually-hidden class to hide it from view:

        .visually-hidden {
          clip: rect(0 0 0 0);
          clip-path: inset(100%);
          height: 1px;
          overflow: hidden;
          position: absolute;
          width: 1px;
          white-space: nowrap;

        And, of course, the HTML needs to be updated to use that class:

        <ol class="toc-list" role="list">
            <a href="#link_to_heading">
              <span class="title">Chapter or subsection title</span>
              <span class="page"><span class="visually-hidden">Page</span> 1</span>
            <ol role="list">
              <!-- subsection items -->

        With this foundation in place, I moved on to address the leaders between the title and the page.

        CodePen Embed Fallback

        Creating dot leaders

        Leaders are so common in print media that you might be wondering, why doesn’t CSS already support that? The answer is: it does. Well, kind of.

        There is actually a leader() function defined in the CSS Generated Content for Paged Media specification. However, as with much of the paged media specifications, this function isn’t implemented in any browsers, therefore excluding it as an option (at least at the time I’m writing this). It’s not even listed on, presumably because no one has implemented it and there are no plans or signals that they will.

        Fortunately, both Julie and Christoph already addressed this problem in their respective posts. To insert the dot leaders, they both used a ::after pseudo-element with its content property set to a very long string of dots, like this:

        .toc-list li > a > .title {
          position: relative;
          overflow: hidden;
        .toc-list li > a .title::after {
          position: absolute;
          padding-left: .25ch;
          content: " . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . ";
          text-align: right;

        The ::after pseudo-element is set to an absolute position to take it out of the flow of the page and avoid wrapping to other lines. The text is aligned to the right because we want the last dots of each line flush to the number at the end of the line. (More on the complexities of this later.) The .title element is set to have a relative position so the ::after pseudo-element doesn’t break out of its box. Meanwhile, the overflow is hidden so all those extra dots invisible. The result is a pretty table of contents with dot leaders.

        However, there’s something else that needs consideration.

        Sara also pointed out to me that all of those dots count as text to screen readers. So what do you hear? “Introduction dot dot dot dot…” until all of the dots are announced. That’s an awful experience for screen reader users.

        The solution is to insert an additional element with aria-hidden set to true and then use that element to insert the dots. So the HTML becomes:

        <ol class="toc-list" role="list">
            <a href="#link_to_heading">
              <span class="title">Chapter or subsection title<span class="leaders" area-hidden="true"></span></span>
              <span class="page"><span class="visually-hidden">Page</span> 1</span>
            <ol role="list">
              <!-- subsection items -->

        And the CSS becomes:

        .toc-list li > a > .title {
          position: relative;
          overflow: hidden;
        .toc-list li > a .leaders::after {
          position: absolute;
          padding-left: .25ch;
          content: " . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . "
              ". . . . . . . . . . . . . . . . . . . . . . . ";
          text-align: right;

        Now screen readers will ignore the dots and spare users the frustration of listening to multiple dots being announced.

        CodePen Embed Fallback

        Finishing touches

        At this point, the table of contents component looks pretty good, but it could use some minor detail work. To start, most books visually offset chapter titles from subsection titles, so I made the top-level items bold and introduced a margin to separate subsections from the chapters that followed:

        .toc-list > li > a {
          font-weight: bold;
          margin-block-start: 1em;

        Next, I wanted to clean up the alignment of the page numbers. Everything looked okay when I was using a fixed-width font, but for variable-width fonts, the leader dots could end up forming a zigzag pattern as they adjust to the width of a page number. For instance, any page number with a 1 would be narrower than others, resulting in leader dots that are misaligned with the dots on previous or following lines.

        To fix this problem, I set font-variant-numeric to tabular-nums so all numbers are treated with the same width. By also setting the minimum width to 2ch, I ensured that all numbers with one or two digits are perfectly aligned. (You may want to set this to 3ch if your project has more than 100 pages.) Here is the final CSS for the page number:

        .toc-list li > a > .page {
          min-width: 2ch;
          font-variant-numeric: tabular-nums;
          text-align: right;
        Aligned leader dots in a table of contents.

        And with that, the table of contents is complete!

        CodePen Embed Fallback


        Creating a table of contents with nothing but HTML and CSS was more of a challenge than I expected, but I’m very happy with the result. Not only is this approach flexible enough to accommodate chapters and subsections, but it handles sub-subsections nicely without updating the CSS. The overall approach works on web pages where you want to link to the various locations of content, as well as PDFs where you want the table of contents to link to different pages. And of course, it also looks great in print if you’re ever inclined to use it in a brochure or book.

        I’d like to thank Julie Blanc and Christoph Grabo for their excellent blog posts on creating a table of contents, as both of those were invaluable when I was getting started. I’d also like to thank Sara Soueidan for her accessibility feedback as I worked on this project.

        A Perfect Table of Contents With HTML + CSS originally published on CSS-Tricks. You should get the newsletter.

        Categories: Designing, Others Tags:

        10 Terrific WordPress Plugins You Should Be Using in 2022

        May 24th, 2022 No comments

        Having the right WordPress plugins on hand can do wonders for your business or online presence. WordPress offers a vast collection to choose from.

        There are so many of them. However, finding those that get the best reviews and can do the most for you can be a challenge.

        A plugin can give you additional functionality. It could otherwise be difficult or overly expensive to realize with your website by itself. A glance at the 10 top WordPress plugins described below can provide a powerful case in point.

        Your website’s purpose or niche will usually dictate the types of essential WordPress plugins you would do well to invest in. The right ones can make your website a genuine powerhouse and, by extension, your business as well.

        1. Amelia

        Amelia is an excellent choice for beauty, healthcare, fitness, consulting, and businesses that might be saddled down with a manual or semi-manual booking system by saving them and their clients time while eliminating booking mistakes that often occur in those manual systems.

        • Clients can book appointments online 24/7, change or cancel their appointments, and receive reminders of upcoming appointments and other notifications via SMS or email.
        • Amelia enables business owners or department managers to track and manage employee schedules and time off.
        • Amelia can manage bookings for appointments, book tickets for events, and manage group bookings, all at multiple locations. There are no limits on the number of appointments that can be managed.
        • Booking forms can be customized to best serve a business’s needs and match its brand.

        Amelia fully supports WooCommerce with PayPal, Stripe, Mollie, and RazorPay payments. Click on the banner to learn more about this time and money-saving plugin.

        2. wpDataTables

        wpDataTables is a premier WordPress table and chart building plugin that features virtually everything you are apt to need to build any table or chart you want.

        Creating a table that is by any definition complex often requires tools that may not necessarily be easy to come by. wpDataTables uses four chart-building engines, one or more of which should suit you perfectly.

        They are:

        • Google Charts
        • Highcharts
        • Charts.js
        • Apex Charts

        For both table and chart building, wpDataTables can connect you to multiple database sources, including –

        • MySQL
        • MS SQL
        • PostgreSQL

        wpDataTables can process data that exists in the commonly used formats and features various sorting and filtering options that allow you to create a host of different table types.

        Both tables and charts are editable and responsive and, thanks to the wpDataTables conditional formatting feature, can highlight and color-code critical information.

        Click to learn more.

        3. Site Kit by Google

        While your website’s performance might exceed your wildest dreams, it is more likely that there are areas that need improvement before your wishes can be met. 

        Determining those areas can be a challenge, but Site Kit offers a one-stop solution to deploy, manage, and get insights from critical Google tools to make your site a success by making those critical tools available to WordPress.

        They provide:

        • stats displayed on your WordPress dashboard from multiple Google tools
        • quick Google tool setup without your having to edit your site’s source code  
        • key metrics and insights for your entire site and individual posts, and
        • easy-to-manage, granular permissions across WordPress and different Google products

        Site Kit shows you how many people have found your site, how users navigate it, etc.

        Click on the banner to learn more about what Site Kit could do for you.

        4. Tablesome –  WordPress Table Plugin With Form Automation

        Tablesome is a WordPress form database and form automation plugin that you can use to store entries from WordPress forms to a database. It can be integrated with popular forms – Contact Form 7 DB, WPForms entries, Forminator database, Elementor Form submissions, etc.

        After saving, you can:

        • Edit, auto-delete, and export entries to tools such as MailChimp, Google Sheets, Salesforce, etc.,
        • Display WordPress form entries on frontend pages
        • Automatically export contact data using the Mailchimp WordPress Integration

        5. TheDock

        TheDock eliminates the need to search for just the right WordPress theme by enabling you to create your own – which can be more fun anyway.

        Among TheDock’s many features, a few key ones include –

        • A comprehensive, option-rich Design System
        • A responsive design system that ensures your site looks great on all screens.
        • Designer, developer, and editing collaboration support. 
        • Clean, readable code.

        6. Slider Revolution

        Beginners and mid-level designers can sometimes have difficulty finding ways to WOW their clients with professional-level visuals.

        Slider Revolution changes all that by bridging the gap between what clients want and what you can provide with its –

        • 200 designed-to-impress website and slider templates
        • 25+ powerful addons and brand new WebGL slide animations
        • ability to import dynamic content from WooCommerce and social media outlets.

        7. LayerSlider

        More than a simple slider-builder, LayerSlider is an animation and website-building tool you can use to improve any website’s look and feel through eye-catching animations, contemporary graphics, and interactive features.

        This is made possible in part through the use of –

        • 160+ website, slider, and popup templates
        • LayerSlider’s modern and intuitive editing interface

        Plus, you can count on professional one-on-one customer support.

        8. Download Monitor

        The Download Monitor plugin helps you sell your digital products by offering a ready solution for tracking file downloads, gating content to generate leads, build your audience, and ask users for personal information in exchange for valuable content.

        Download Monitor lets you –

        • add any type of file you need to your website
        • link a page to all your channels and promote your social media networks
        • place ads – and more.

        9. Ads Pro – Multi-Purpose WordPress Ad Manager

        The biggest ad manager for WordPress, Ads Pro gives you everything necessary to manage and sell ads.

        Ads Pro’s admin panel makes managing ads straightforward for you and your users.

        • Key ad features include 25+ ad templates and 20+ ad display options.
        • CPC, CPM, CPD billing and PayPal, Stripe, and bank transfer payment methods are built-in.
        • Geo-Targeting lets you show/hide ad spaces based on countries, provinces, cities, and Zip Codes.

        10. Ultimate Membership Pro

        If selling content is your objective, Ultimate Membership Pro is the tool you’ll want to take your website and convert it into a powerful content selling platform.

        The Ultimate Membership Pro plugin enables you to –

        • Create unlimited subscription levels, including free, trial, and paid member subscriptions
        • Control customer access to content based on their subscriptions
        • Send emails to welcome new members and send notifications and reminders to regular subscribers.

        The WordPress plugin directory is already stuffed with almost 60,000 plugins. This guide has been published to narrow things down to 10 top WordPress plugins for your use.

        We consulted with experts to create this list of excellent plugins for WordPress. It can help you with content strategy, SEO, site security, and even social media marketing.

        Installing plugins and getting the functionality they provide can add immense value to your use of WordPress.


        [- This is a sponsored post on behalf of BAW Media -]


        The post 10 Terrific WordPress Plugins You Should Be Using in 2022 first appeared on Webdesigner Depot.

        Categories: Designing, Others Tags:

        First Look At The CSS object-view-box Property

        May 23rd, 2022 No comments

        Ahmad Shadeed — doing what he always does so well — provides an early look at the object-view-box property, something he describes as a native way to crop an image in the browser with CSS.

        The use case? Well, Ahmad wastes no time showing how to use the property to accomplish what used to require either (1) a wrapping element with hidden overflow around an image that’s sized and positioned inside that element or (2) the background-image route.

        But with object-view-box we can essentially draw the image boundaries as we can with an SVG’s viewbox. So, take a plain ol’ and call on object-view-box to trim the edges using an inset function. I’ll simply drop Ahmad’s pen in here:

        CodePen Embed Fallback

        Only supported in Chrome Canary for now, I’m afraid. But it’s (currently) planned to release in Chrome 104. Elsewhere:

        To Shared LinkPermalink on CSS-Tricks

        First Look At The CSS object-view-box Property originally published on CSS-Tricks. You should get the newsletter.

        Categories: Designing, Others Tags:

        20 Best New Sites, June 2022

        May 23rd, 2022 No comments

        This month’s collection of the best new sites is a mixed bag. Positivity remains from last month’s edition, and what we’re seeing is designers being far more ambitious for the experiences they create.

        We have a couple of sites helping to alleviate the damage of war, some unusual approaches to topics that are normally very dour, and some excellent portfolios to be jealous of. Enjoy!

        Sarah Fatmi

        Characterful illustration and desktop sideways scrolling make this portfolio site for illustrator Sarah Fatmi stand out.

        Vestiaire Impact Report

        Green is the new black, and fashion resale platform Vestiaire presents its green credentials in an informative and engaging way.


        Houseplant is a collection of cannabis-related products designed by Seth Rogen and Evan Goldberg; this site is a lot classier than the average headshop.

        FreshCut BarberShop

        The site for FreshCut BarberShop is modern, bold, and gets its message across clearly, even if the user doesn’t read French.

        Feed The 300

        Feed the 300 is an appeal in aid of the animals in Ukraine’s zoos. It is very simple in concept and design, but endearing animated line drawings give it character.

        Honeymoon Chicken

        Luscious photography combined with surprisingly delicate illustrations makes Honeymoon Chicken very inviting.

        Patachou Inc

        Patachou Inc operates a group of eateries and the site does a good job of conveying both the very different individual brand identities of each establishment, and the common ethic behind all of them.

        Living With OCD

        Many design studios do showcase projects, and Living With OCD by designedbyla is one of the more publicly beneficial, and well-executed, examples around.


        Aro is a product with a very simple concept — basically, a box to put away a phone, that also charges it — but this website does a great job of increasing the product’s desirability.

        Kim Kniepp

        The navigation on this site for Kim Kniepp’s design studio feels very interconnected, an effect heightened by the overlapping masonry grid.


        There is a calming, reassuring quality to the color used here for Pan-Baltic law firm Triniti. The perpetual motion style hero video adds a confident, soothing touch too.


        Creative agency Herezie uses saturation and gradual color changes to pleasing effect in this confident, assured website.


        The color choices in this site for MetalColor, and how they are used, succeed in evoking what results the company could achieve without focusing on the less glamorous parts of the process.


        Architecture and design studio Gras goes for a clean feel with an irregular grid layout and carefully curated images. The blog sidebar works well too.

        Vendredi Society

        Dark green and bright yellow make a strong statement in this portfolio site for brand strategists Vendredi Society.


        HUB describes itself as a progressive property developer and this site does a great job of leaving behind the corporate image usually associated with property developers.

        Nowhere Bakery

        Nowhere Bakery makes vegan, paleo, gluten-free cookies, which don’t sound all that appealing on paper. This site manages to make them seem both really tasty and healthy.

        Apotheke zur Triumphpforte

        The botanical illustration style images on Apotheke zur Triumphpforte’s site help create an approachable brand identity while adding visual interest.


        A good balance of images, animation, and illustration combine to create an impactful presence for B!pod’s first product, a food vacuum storage system.

        The New Exhibition

        The New Exhibition is a showcase platform for Ukrainian creatives — type designers, illustrators, graphic designers, photographers, and others — whose ability to get work has been affected by war.


        The post 20 Best New Sites, June 2022 first appeared on Webdesigner Depot.

        Categories: Designing, Others Tags:

        Popular Design News of the Week: May 16, 2022 – May 22, 2022

        May 22nd, 2022 No comments

        Every day design fans submit incredible industry stories to our sister-site, Webdesigner News. Our colleagues sift through it, selecting the very best stories from the design, UX, tech, and development worlds and posting them live on the site.
        The best way to keep up with the most important stories for web professionals is to subscribe to Webdesigner News or check out the site regularly. However, in case you missed a day this week, here’s a handy compilation of the top curated stories from the last seven days. Enjoy!”

        Exciting New Tools for Designers, May 2022

        HTMLrev – 50 Beautiful HTML Landing Page Templates Library

        Cool Hover Effects that Use CSS Text Shadow

        Designers’ Pick: Top Color Trends for 2022

        :Where() :Is() :Has()? New CSS Selectors that Make your Life Easier

        The Era of Rebellious Web Design is Here

        Bootstrap 5.2.0 Beta

        OptimizeImages Free Bulk Image Optimizer

        2022 Craft Beer Branding and Package Design Trends

        3D Avatar Library – Hundreds of 3D Avatars for your Designs – Shrink the Size of your Images for Free

        The WHY of Accessibility


        The post Popular Design News of the Week: May 16, 2022 – May 22, 2022 first appeared on Webdesigner Depot.

        Categories: Designing, Others Tags:


        May 20th, 2022 No comments


        You may not know his name, but he played a huge part in creating the web you take for granted today. And he’s back—kind of.

        That would be Glenn Davis and the Verevolf site Zeldman’s talking about. The site is a growing archive of Davis’s personal (and unvarnished) recollections pioneering the early web, like the one where he recounts the origin story of his uber-famous Cool Site of the Day.

        Credit: Web Design Museum

        Or the how an email he wrote out of frustration snowballed into the Web Standards Project.

        Personal retellings of history can be fraught with emotion and Davis’s posts are no exception. What’s super cool is how his experiences augment other retellings, including Chapter 7 of our own Web History series where Jay Hoffman documents the evolution of web standards.

        To Shared LinkPermalink on CSS-Tricks

        Verevolf originally published on CSS-Tricks. You should get the newsletter.

        Categories: Designing, Others Tags:

        9 Ways To Drive Traffic To Your WordPress Blog

        May 20th, 2022 No comments

        WordPress has made it easy for everyone to launch a blog, but even though launching a blog isn’t a difficult task any longer, driving traffic to your blog certainly is!

        In this article, I’ll share some tried and tested strategies that have worked well for my clients’ blogs. You do not have to be an expert or a marketing guru to get traffic to your WordPress website. Follow the helpful tips I share in this article and watch the visitors start pouring in.

        Tip 1: Use Powerful Headlines

        The first thing related to your blog that a user reads in the search engine results is your article headlines. Of course, nobody wants to click on a boring article title. But a powerful headline stands out from the rest and gets you more clicks. 

        In most themes, your article headlines are translated into meta titles for the pages. Meta titles indicate the topic of your articles to Google and other search engines. 

        Tip 2: Build an Email List

        Consider offering your visitors a newsletter signup form through which they can subscribe and get notified about new posts on your blog. You can offer them an incentive for free to persuade them to subscribe to your blog. It can be anything from an e-book, membership, useful templates, or an e-course. 

        Building an email list gives access to the inboxes of your visitors. You can share your blog content with this prospective audience every time you post a new article. This will help you get consistent traffic to your WordPress blog.

        Tip 3: Use Free Giveaways and Contests

        Free giveaways work as an incentive for your WordPress blog visitors. To offer an entry to your blog’s free giveaway, you can ask your visitors for an email subscription, comment on your blog posts, share it on their social media channels, and ask for other such things. 

        The trick is to think about the actions of your visitors that will increase traffic to your blog and provide them with one or multiple giveaway entries for such actions. 

        Tip 4: Optimize For Keywords

        All successful bloggers optimize their content for keywords. You need to perform proper keyword research to find sentences and words that your target audience is typing in Google and other top search engines. 

        Instead of guessing the keywords for your articles, consider using some helpful tools like SEMrush’s Keyword Magic Tool and Google Ads Keyword Planner. This way, you can find the terms people are genuinely interested in and the keywords that do not have too much competition.

        You must ensure to choose the keywords that have some excellent traffic volume but, at the same time, have less competition. Such keywords will help in the better ranking of each of your articles.

        Tip 5: Optimize WordPress Site Speed

        It has been proven that loading time is a ranking factor for SEO, as Google tends to assume that fast sites are high-quality sites.

        Signing up for a hosting provider specializing in WordPress guarantees you get the best optimization features for your WordPress site. However, that alone is not enough because you need a hosting provider that can also handle a high volume of visitors.

        Optimizing your WordPress website will help in the faster loading of your blog pages. Images are generally the biggest culprit in slowing down your website. So you must first optimize them through an image optimization plugin like Smush, Imagify, or Optimus. 

        Enabling caching on your WordPress blog will considerably improve its speed. You can store your website data locally with caching, thereby reducing your server load to a large extent. Your website will, therefore, load faster on your visitors’ end, especially when they are repeat visitors.

        Tip 6: Take Advantage of Social Media

        Try building your presence on some of the top platforms like Facebook, Instagram, Twitter, LinkedIn, and Pinterest. Post multiple times a day on these websites and share your blog articles.

        You must also include social sharing buttons with your blog posts to make sharing easier for your audience. It will allow your blog visitors to share your post on different social platforms. This dramatically increases the chances of your blog post going viral.

        Tip 7: Internal Linking Strategy

        The only key here is to link articles that are closely related to each other. Your visitors might be interested in such related content and read more of your blog posts, thereby increasing your page views. It also increases the chances of visitors sharing your blog content since they find it valuable.

        Tip 8: Be a Guest Blogger

        Guest blogging involves creating content for other websites for mutual benefits. It helps you establish your authority in the blogging world while attracting more visitors to your WordPress website. 

        Becoming a guest blogger allows you to spread the word about your blog to a new set of audiences and bring in organic traffic. It expands your work portfolio and helps build or enhance your online reputation.

        Tip 9: Pay for Traffic

        Consider using Google Ads, Facebook Ads, Microsoft advertising, and other top advertising platforms when paying to bring traffic to your blog. Be aware of your blog audience and use the most suitable criteria to target it. 

        I’d recommend setting a weekly budget for paid ads and tracking the ad performance at the end of the week.

        If you are satisfied with the traffic results, use the same criteria for the next week. On the other hand, if the ad performance is not as per your expectations, try different criteria to reach your target audience.


        Getting traffic to your WordPress blog is an incentive for all the hard work that you do in creating content and managing your website. It builds a name for your blog and improves its search engine ranking. All this leads to better user engagement and revenue.


        Featured image via Pexels.


        The post 9 Ways To Drive Traffic To Your WordPress Blog first appeared on Webdesigner Depot.

        Categories: Designing, Others Tags:

        Inline Image Previews with Sharp, BlurHash, and Lambda Functions

        May 19th, 2022 No comments

        Don’t you hate it when you load a website or web app, some content displays and then some images load — causing content to shift around? That’s called content reflow and can lead to an incredibly annoying user experience for visitors.

        I’ve previously written about solving this with React’s Suspense, which prevents the UI from loading until the images come in. This solves the content reflow problem but at the expense of performance. The user is blocked from seeing any content until the images come in.

        Wouldn’t it be nice if we could have the best of both worlds: prevent content reflow while also not making the user wait for the images? This post will walk through generating blurry image previews and displaying them immediately, with the real images rendering over the preview whenever they happen to come in.

        So you mean progressive JPEGs?

        You might be wondering if I’m about to talk about progressive JPEGs, which are an alternate encoding that causes images to initially render — full size and blurry — and then gradually refine as the data come in until everything renders correctly.

        This seems like a great solution until you get into some of the details. Re-encoding your images as progressive JPEGs is reasonably straightforward; there are plugins for Sharp that will handle that for you. Unfortunately, you still need to wait for some of your images’ bytes to come over the wire until even a blurry preview of your image displays, at which point your content will reflow, adjusting to the size of the image’s preview.

        You might look for some sort of event to indicate that an initial preview of the image has loaded, but none currently exists, and the workarounds are … not ideal.

        Let’s look at two alternatives for this.

        The libraries we’ll be using

        Before we start, I’d like to call out the versions of the libraries I’ll be using for this post:

        Making our own previews

        Most of us are used to using  tags by providing a src attribute that’s a URL to some place on the internet where our image exists. But we can also provide a Base64 encoding of an image and just set that inline. We wouldn’t usually want to do that since those Base64 strings can get huge for images and embedding them in our JavaScript bundles can cause some serious bloat.

        But what if, when we’re processing our images (to resize, adjust the quality, etc.), we also make a low quality, blurry version of our image and take the Base64 encoding of that? The size of that Base64 image preview will be significantly smaller. We could save that preview string, put it in our JavaScript bundle, and display that inline until our real image is done loading. This will cause a blurry preview of our image to show immediately while the image loads. When the real image is done loading, we can hide the preview and show the real image.

        Let’s see how.

        Generating our preview

        For now, let’s look at Jimp, which has no dependencies on things like node-gyp and can be installed and used in a Lambda.

        Here’s a function (stripped of error handling and logging) that uses Jimp to process an image, resize it, and then creates a blurry preview of the image:

        function resizeImage(src, maxWidth, quality) {
          return new Promise<ResizeImageResult>(res => {
  , async function (err, image) {
              if (image.bitmap.width > maxWidth) {
                image.resize(maxWidth, Jimp.AUTO);
              const previewImage = image.clone();
              const preview = await previewImage.getBase64Async(previewImage.getMIME());
              res({ STATUS: "success", image, preview });

        For this post, I’ll be using this image provided by Flickr Commons:

        Photo of the Big Boy statue holding a burger.

        And here’s what the preview looks like:

        Blurry version of the Big Boy statue.

        If you’d like to take a closer look, here’s the same preview in a CodeSandbox.

        Obviously, this preview encoding isn’t small, but then again, neither is our image; smaller images will produce smaller previews. Measure and profile for your own use case to see how viable this solution is.

        Now we can send that image preview down from our data layer, along with the actual image URL, and any other related data. We can immediately display the image preview, and when the actual image loads, swap it out. Here’s some (simplified) React code to do that:

        const Landmark = ({ url, preview = "" }) => {
            const [loaded, setLoaded] = useState(false);
            const imgRef = useRef<HTMLImageElement>(null);
            useEffect(() => {
              // make sure the image src is added after the onload handler
              if (imgRef.current) {
                imgRef.current.src = url;
            }, [url, imgRef, preview]);
            return (
                <Preview loaded={loaded} preview={preview} />
                  onLoad={() => setTimeout(() => setLoaded(true), 3000)}
                  style={{ display: loaded ? "block" : "none" }}
          const Preview: FunctionComponent<LandmarkPreviewProps> = ({ preview, loaded }) => {
            if (loaded) {
              return null;
            } else if (typeof preview === "string") {
              return <img key="landmark-preview" alt="Landmark preview" src={preview} style={{ display: "block" }} />;
            } else {
              return <PreviewCanvas preview={preview} loaded={loaded} />;

        Don’t worry about the PreviewCanvas component yet. And don’t worry about the fact that things like a changing URL aren’t accounted for.

        Note that we set the image component’s src after the onLoad handler to ensure it fires. We show the preview, and when the real image loads, we swap it in.

        Improving things with BlurHash

        The image preview we saw before might not be small enough to send down with our JavaScript bundle. And these Base64 strings will not gzip well. Depending on how many of these images you have, this may or may not be good enough. But if you’d like to compress things even smaller and you’re willing to do a bit more work, there’s a wonderful library called BlurHash.

        BlurHash generates incredibly small previews using Base83 encoding. Base83 encoding allows it to squeeze more information into fewer bytes, which is part of how it keeps the previews so small. 83 might seem like an arbitrary number, but the README sheds some light on this:

        First, 83 seems to be about how many low-ASCII characters you can find that are safe for use in all of JSON, HTML and shells.

        Secondly, 83 * 83 is very close to, and a little more than, 19 * 19 * 19, making it ideal for encoding three AC components in two characters.

        The README also states how Signal and Mastodon use BlurHash.

        Let’s see it in action.

        Generating blurhash previews

        For this, we’ll need to use the Sharp library.


        To generate your blurhash previews, you’ll likely want to run some sort of serverless function to process your images and generate the previews. I’ll be using AWS Lambda, but any alternative should work.

        Just be careful about maximum size limitations. The binaries Sharp installs add about 9 MB to the serverless function’s size.

        To run this code in an AWS Lambda, you’ll need to install the library like this:

        "install-deps": "npm i && SHARP_IGNORE_GLOBAL_LIBVIPS=1 npm i --arch=x64 --platform=linux sharp"

        And make sure you’re not doing any sort of bundling to ensure all of the binaries are sent to your Lambda. This will affect the size of the Lambda deploy. Sharp alone will wind up being about 9 MB, which won’t be great for cold start times. The code you’ll see below is in a Lambda that just runs periodically (without any UI waiting on it), generating blurhash previews.

        This code will look at the size of the image and create a blurhash preview:

        import { encode, isBlurhashValid } from "blurhash";
        const sharp = require("sharp");
        export async function getBlurhashPreview(src) {
          const image = sharp(src);
          const dimensions = await image.metadata();
          return new Promise(res => {
            const { width, height } = dimensions;
              .toBuffer((err, buffer) => {
                const blurhash = encode(new Uint8ClampedArray(buffer), width, height, 4, 4);
                if (isBlurhashValid(blurhash)) {
                  return res({ blurhash, w: width, h: height });
                } else {
                  return res(null);

        Again, I’ve removed all error handling and logging for clarity. Worth noting is the call to ensureAlpha. This ensures that each pixel has 4 bytes, one each for RGB and Alpha.

        Jimp lacks this method, which is why we’re using Sharp; if anyone knows otherwise, please drop a comment.

        Also, note that we’re saving not only the preview string but also the dimensions of the image, which will make sense in a bit.

        The real work happens here:

        const blurhash = encode(new Uint8ClampedArray(buffer), width, height, 4, 4);

        We’re calling blurhash‘s encode method, passing it our image and the image’s dimensions. The last two arguments are componentX and componentY, which from my understanding of the documentation, seem to control how many passes blurhash does on our image, adding more and more detail. The acceptable values are 1 to 9 (inclusive). From my own testing, 4 is a sweet spot that produces the best results.

        Let’s see what this produces for that same image:

          "blurhash" : "UAA]{ox^0eRiO_bJjdn~9#M_=|oLIUnzxtNG",
          "w" : 276,
          "h" : 400

        That’s incredibly small! The tradeoff is that using this preview is a bit more involved.

        Basically, we need to call blurhash‘s decode method and render our image preview in a canvas tag. This is what the PreviewCanvas component was doing before and why we were rendering it if the type of our preview was not a string: our blurhash previews use an entire object — containing not only the preview string but also the image dimensions.

        Let’s look at our PreviewCanvas component:

        const PreviewCanvas: FunctionComponent<CanvasPreviewProps> = ({ preview }) => {
            const canvasRef = useRef<HTMLCanvasElement>(null);
            useLayoutEffect(() => {
              const pixels = decode(preview.blurhash, preview.w, preview.h);
              const ctx = canvasRef.current.getContext("2d");
              const imageData = ctx.createImageData(preview.w, preview.h);
              ctx.putImageData(imageData, 0, 0);
            }, [preview]);
            return <canvas ref={canvasRef} width={preview.w} height={preview.h} />;

        Not too terribly much going on here. We’re decoding our preview and then calling some fairly specific Canvas APIs.

        Let’s see what the image previews look like:

        In a sense, it’s less detailed than our previous previews. But I’ve also found them to be a bit smoother and less pixelated. And they take up a tiny fraction of the size.

        Test and use what works best for you.

        Wrapping up

        There are many ways to prevent content reflow as your images load on the web. One approach is to prevent your UI from rendering until the images come in. The downside is that your user winds up waiting longer for content.

        A good middle-ground is to immediately show a preview of the image and swap the real thing in when it’s loaded. This post walked you through two ways of accomplishing that: generating degraded, blurry versions of an image using a tool like Sharp and using BlurHash to generate an extremely small, Base83 encoded preview.

        Happy coding!

        Inline Image Previews with Sharp, BlurHash, and Lambda Functions originally published on CSS-Tricks. You should get the newsletter.

        Categories: Designing, Others Tags:

        What Even Is Web Design in 2022?

        May 18th, 2022 No comments

        The term “web design” refers to the process of planning, organizing, and editing content online. On the surface, it seems like a simple enough concept. However, the reality is what we consider “web design” can change over time, influenced by our perception of the “web.” 

        In 2022, a professional web designer might create custom websites from scratch, but they may also be responsible for: 

        • UX Design: Creating elements focused on user experience
        • App design: Building digital components of a website or online experience.
        • Theme design: Creating visual tools for supplementing web design. 

        Web design isn’t just about making a site look attractive anymore. The definition goes beyond the aesthetic to include a complete consideration of the functionality, performance, and abilities of countless assets we engage within the digital world.

        What is Web Design? The Definition Today

        Web design is the practice responsible for creating a website’s overall look and feel or web asset (such as web and mobile apps). It involves the process of planning and building elements of your project, from structure and layout choices to graphics and presentation. 

        Web design has various components that work together to create the final “experience” of a website, including graphic design, interface design, user experience design, search engine optimization, content creation, etc. These elements determine how a web asset looks, feels and performs on various devices. 

        Though the definition of web design in 2022 has evolved, it’s still different from web development, which refers to the actual coding which makes a website work. When you’re building a website, you’ll need web design and web development. 

        Elements of Web Design in 2022 

        When designing a website, modern designers need to consider two overlapping concepts: the overall appearance of the website and its functionality. The proper connection between these elements will maximize the site’s overall performance and usability, and make a design more memorable (for all of the right reasons). 

        Let’s break down the elements of web design into its visual and functional components.

        Visual Elements of Web Design

        Visual elements of web design influence how a design looks. The various visual components of a design should still follow the basic principles of graphic design. In other words, designers should be thinking about contrast, balance, unity, and alignment simultaneously. The visual elements of web design include: 

        • Written copy and fonts: A website’s appearance and the text on the site often go hand in hand. Designers need to work together with content writers to ensure written copy makes sense structurally and uses the correct fonts for legibility. 
        • Colors: Colors for web design are usually chosen based on factors like color psychology, which demonstrates a color’s ability to affect how someone feels, and branding. Most brands have specific colors they use consistently throughout their visual assets; this helps create a sense of cohesion and unity in designs.
        • Layout and spacing: Layout and spacing influence how content is arranged in an app, website, or another visual asset. The right layout helps to create a visual hierarchy, guiding a viewer through a page and drawing their attention to the correct information in order. Spacing helps to separate components on a page and create legibility. 
        • Images, icons, and shapes: Images, icons, and shapes help convey significant amounts of information. The right ideas and icons can strengthen a brand message, direct a customer’s attention using a web app, and bring context to a design. 
        • Videos and animations: Videos and animations are becoming increasingly common in today’s web design strategies. Videos can include 360-degree videos, which help immerse someone in a space, video streams, and short content clips.

        Functional Elements of Web Design

        Functional elements in web design are the practical components designers need to consider to ensure websites and assets work as they’re supposed to. A website, app, or any other web asset needs to function correctly to be accessible to users.

        Functional elements of web design may include:

        • Navigation: The navigation elements of a website or app are among the main components determining whether a site is functioning properly and ensuring a good user experience. Audiences need to be able to move around the app or website quickly. 
        • User interactions: Your site visitors may have multiple ways of communicating with your web app or website, depending on their device. You’ll need to make sure people can scroll and swipe on smartphones and tablets and click on desktops. If your website has VR or AR elements, you’ll also need to consider these immersive components in your design.
        • Speed and performance: While web development elements can also influence a web design’s speed or performance, it’s also essential for a designer to show elements of the composition don’t weigh down the functionality. Designs need to load quickly and correspond with the demands of browsers on various devices.
        • Structure: A website’s structure plays a critical role in user experience and SEO requirements. Users need to easily navigate through a website without encountering any issues like getting lost or ending up on broken pages.
        • Compatibility: A good design should look perfect on all devices, from a wide range of browsers to the various devices users might leverage today. 

        What Does Good Web Design Look Like in 2022?

        More than ever, achieving high-quality web design is crucial to success in any industry or landscape. More than half of the world’s population is active online. If you’re not appealing to this audience correctly, you’re missing out on endless opportunities.

        Notably, while elements of good web design can be subjective, such as which themes or colors someone might prefer for their website, the underlying foundations of strong web design are the same for everyone in 2022.  

        Good web design is any design that looks good, performs as it should, and delivers the best possible experience to your target audience. Effective web design should include components like:

        • Effective use of white space for organization and structure.
        • Clearly presented choices and navigation options for the user.
        • Clear calls to action to drive user activities from one page to another.
        • Limited distractions and a straightforward user journey. 
        • No clutter or unnecessary components irrelevant to the needs of the user. 
        • Responsive, flexible design accessible on any browser or device.
        • High-quality content and images are designed to hook a reader’s attention.
        • Appropriately sized fonts and legible typography.
        • A good balance between images and text on a page. 

        Other elements like eye-catching imagery and professional photography can help your web design stand out. Using the right building blocks, like a strong color palette and the right shapes or icons in your design is helpful. 

        Of course, there is some scope for variation in good web design. A web designer in 2022 needs to be able to adapt their use of the various essential elements of design to suit a specific target audience or the unique identity of a brand.

        What Doesn’t Work for Web Design in 2022?

        Just as web design elements seem to appear consistently in all excellent examples, there are also parts of web design we’ve left behind over the years. Simpler, more straightforward designs have replaced cluttered spaces, flashing images, and endless animations. 

        The focus in 2022 is on creating an experience that’s simple, engaging, and intuitive, capable of speaking to the right audience without confusion or being visually overwhelming. In most cases, some of the top components to avoid include:

        • Clunky performance: Non-responsive website design, slow pages, and other examples of clunky functionality are a no-go in 2022. Websites need to be quick and responsive.
        • Distracting content: Flashing images, animations, and complex backgrounds are a thing of the past for a good reason. Websites today need to be clean, simple, and clear. Any elements which don’t add to the value of the design should be removed.
        • Generic content: Filler text, irrelevant stock photos, unclear buttons, and links can be removed from today’s website designs. A web design should be specific to the audience’s needs and the brand’s identity. Generic components don’t work.

        Creating Web Designs in 2022

        Today, the underlying definition of web design has a lot of similarities to the definition we’ve known for several years already. Creating a great website or web asset still requires focusing on user experience, aesthetic appeal, and functionality. However, today’s web designers generally have more components and different devices. 

        Web design in 2022 is about creating high-quality experiences for customers that can support various environments and devices. The best web designs are aesthetically appealing, functionally reliable, and capable of adhering to the latest trends in web creation, like augmented reality, 360-degree video, and ultra-high resolution. 


        Featured image via Pexels.


        The post What Even Is Web Design in 2022? first appeared on Webdesigner Depot.

        Categories: Designing, Others Tags:

        Improving Icons for UI Elements with Typographic Alignment and Scale

        May 17th, 2022 No comments
        Screenshot of the site messaging element. It is overlayed with a red-dashed line indicating the icon's top edge and a blue-dashed line indicating the text's topmost point. The red-dashed line is slightly higher than the blue-dashed line.

        Utilizing icons in user interface elements is helpful. In addition to element labeling, icons can help reinforce a user element’s intention to users. But I have to say, I notice a bit of icon misalignment while browsing the web. Even if the icon’s alignment is correct, icons often do not respond well when typographic styles for the element change.

        I took note of a couple real-world examples and I’d like to share my thoughts on how I improved them. It’s my hope these techniques can help others build user interface elements that better accommodate typographic changes and while upholding the original goals of the design.

        Example 1 — Site messaging

        I found this messaging example on a popular media website. The icon’s position doesn’t look so bad. But when changing some of the element’s style properties like font-size and line-height, it begins to unravel.

        CodePen Embed Fallback

        Identified issues

        • the icon is absolutely positioned from the left edge using a relative unit (rem)
        • because the icon is taken out of the flow, the parent is given a larger padding-left value to help with overall spacing – ideally, our padding-x is uniform, and everything looks good whether or not an icon is present
        • the icon (it’s an SVG) is also sized in rems – this doesn’t allow for respective resizing if its parent’s font-size changes


        Indicating the issues with aligning the icon and typography.

        We want our icon’s top edge to be at the blue dashed line, but we often find our icon’s top edge at the red dashed line.

        Have you ever inserted an icon next to some text and it just won’t align to the top of the text? You may move the icon into place with something like position: relative; top: 0.2em. This works well enough, but if typographic styles change in the future, your icon could look misaligned.

        We can position our icon more reliably. Let’s use the element’s baseline distance (the distance from one line’s baseline to the next line’s baseline) to help solve this.

        Screenshot of the site messaging element. It is overlayed with arrows indicating the baseline distance from the baseline of one line to the next line's baseline.
        Calculating the baseline distance.

        Baseline distance is font-size * line-height.

        We’ll store that in a CSS custom property:

        --baselineDistance: calc(var(--fontSize) * var(--lineHeight));

        We can then move our icon down using the result of (baseline distance – font size) / 2.

        --iconOffset: calc((var(--baselineDistance) - var(--fontSize)) / 2);

        With a font-size of 1rem (16px) and line-height of 1.5, our icon will be moved 4 pixels.

        • baseline distance = 16px * 1.5 = 24px
        • icon offset = (24px16px) / 2 = 4px

        Demo: before and after

        CodePen Embed Fallback

        Example 2 – unordered lists

        The second example I found is an unordered list. It uses a web font (Font Awesome) for its icon via a ::before pseudo-element. There have been plenty of great articles on styling both ordered and unordered lists, so I won’t go into details about the relatively new ::marker pseudo-element and such. Web fonts can generally work pretty well with icon alignment depending on the icon used.

        CodePen Embed Fallback

        Identified issues

        • no absolute positioning used – when using pseudo-elements, we don’t often use flexbox like our first example and absolute positioning shines here
        • the list item uses a combination of padding and negative text-indent to help with layout – I am never able to get this to work well when accounting for multi-line text and icon scalability


        Because we’ll also use a pseudo-element in our solution, we’ll leverage absolute positioning. This example’s icon size was a bit larger than its adjacent copy (about 2x). Because of this, we will alter how we calculate the icon’s top position. The center of our icon should align vertically with the center of the first line.

        Start with the baseline distance calculation:

        --baselineDistance: calc(var(--fontSize) * var(--lineHeight));

        Move the icon down using the result of (baseline distance – icon size) / 2.

        --iconOffset: calc((var(--baselineDistance) - var(--iconSize)) / 2);

        So with a font-size of 1rem (16px), a line-height of 1.6, and an icon sized 2x the copy (32px), our icon will get get a top value of -3.2 pixels.

        • baseline distance = 16px * 1.6 = 25.6px
        • icon offset = (25.6px32px) / 2 = -3.2px

        With a larger font-size of 2rem (32px), line-height of 1.2, and 64px icon, our icon will get get a top value of -12.8 pixels.

        • baseline distance = 32px * 1.2 = 38.4px
        • icon offset = (38.4px64px) / 2 = -12.8px

        Demo: before and after

        CodePen Embed Fallback


        For user interface icons, we have a lot of options and techniques. We have SVGs, web fonts, static images, ::marker, and list-style-type. One could even use background-colors and clip-paths to achieve some interesting icon results. Performing some simple calculations can help align and scale icons in a more graceful manner, resulting in implementations that are a bit more bulletproof.

        See also: Previous discussion on aligning icon to text.

        Improving Icons for UI Elements with Typographic Alignment and Scale originally published on CSS-Tricks. You should get the newsletter.

        Categories: Designing, Others Tags: