Line length revisited: following the research

Typography Definitions Cover

Mary Dyson produces nitty gritty research on the long-accepted notion that shorter line lengths are more legible than longer ones. The study finds that shorter lines do not necessarily lead to faster reading. If you’re looking for a definitive answer to use in your next design review debate, though, no dice. The big finding is that long lines don’t slow things down as much as previously thought, not that they’re better or worse.

But there’s so much more meat in here that I found much more interesting, mostly because I’m largely ignorant on the topic and gained a dollop of context on writing, legibility, and behavior.

Things like…

There’s a term for transitioning between lines of text

It’s return sweeps. You know, like your eye hits the Return key at the end of the line and sweeps to the start of the next line. Then, there are undershoots. The idea is that eyes may not sweep to the exact start of the next line, instead stopping a bit short.

Showing four muted lines of test with jump arrows across each line taking the eye to the end of the line, followed by dashed arrow leading to the next line. Red arrows highlight where the eye could undershoot a new line and miss content.

Those little rapid eye movements between words and phrases? Those are called saccades. I had to look that up.

The impact of undershoots is what’s being challenged

The previous research we’ve relied on for years comes from 1940(!), a time when we obviously were more concerned with paper pages than bright digital displays. Longer lines, it said, increased the likelihood that eyes undershoot during a return sweep, and undershooting results in a regression that results in a 130ms to 250ms delay where the brain needs to get its bearings. The report refers to that as undersweep-fixation.

We can still process words during undersweep-fixation

This report cites a 2019 study that tried to correct undershoots by bolding the first word at the start of each new line, sort of like an anchor that naturally draws the eye closer to the left margin.

The 2019 study did find that the bolded words did decrease undershot return sweeps But despite that, reading speed did not improve. That’s the impetus for challenging the long-held assumption that shorter is better.

Mary explains further:

In seeking to reconcile why longer line lengths may not slow down reading on screen but do so when reading print, I outlined some differences, e.g. visual angle, time spent scrolling. But although physical differences between reading from screen and reading print still exist, we now have direct evidence to explain why longer lines were read at least as fast as shorter lines. Readers can process words during the brief fixation when undershooting the start of the new line. This saves time in subsequent processing. Now we might also acknowledge that there is greater consistency between the range of optimal line lengths for print and screen.

Where does this leave us today?

Well, nowhere closer to a clear answer we can use in our day-to-day work. But it’s good to dust off our collection of design and copywriting best practices and know that line length is less of a constraint than perhaps it has been.

Again, none of this tells us whether long or short lines are better. Mary ends her report by saying she cannot definitely recommend using longer lines of text because there are clear because there are still some factors at play, including:

  • Shorter lines are more effective for people with dyslexia.
  • More questions about return sweeps and undershooting need to be answered.
  • Several other studies indicate that users prefer shorter lines and judge longer lines as more difficult to read.

To Shared LinkPermalink on CSS-Tricks


The post Line length revisited: following the research appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

Other Looks at the Conditional Border Radius Trick

Category Image 052

Remember when Ahmad Shadeed wrote about that border-radius “toggle” he found in Facebook’s CSS? It was interesting! I covered it. A few weeks after that surge of linkage, a couple of articles came out digging into it a little deeper.

In “Evaluating Clever CSS Solutions,” Michelle Barker wonders how clever is too clever?

While undoubtedly clever, and super interesting to read about, I side with Robin Rendle in the CSS-Tricks newsletter when he says:

I can’t help but feel that it’s a little too smart.

I have to agree here. Tricks like this have their place, and Facebook (which can clearly afford to hire the best of the best CSS developers) might be one of them. But speaking personally, when forced to pick between a trick like this and an ever-so-slightly less optimal but far more readable solution (say, a media query), in 99% of cases I’d plump for the latter.

Michelle is aware that a media query isn’t the same solution here. A non-clever solution would be a container query. I agree as well. I almost never opt for tricky solutions in production, as even if they seem to work, I worry about the long term maintenance and sometimes even the fragility of the solution.

Stefan Judis looked at how we might pull of the same “conditional border-radius” idea only using the upcoming container queries syntax.

/* If the container's width is equal to or greater than 
   the viewport width, remove the border-radius */
@container (width >= 100vw) {
  .conditional-border-radius {
    border-radius: 0;
  }
}

That’s pretty darn clear to me. Stefan also mentions that if we could use the theoretically upcoming @when feature, it could be even clearer:

@when container(width >= 100vw) {
  .conditional-border-radius {
    border-radius: 0;
  }
}
@else {
  .conditional-border-radius {
    border-radius: 1em;
  }
}

That is a big maybe, as there is no evidence these brand new specs will overlap like this. I hope they do though. CSS has gotten much more logical and readable over the years and this would keep that train moving.


Oh, and I mentioned this in the last article

The 9999 multiplication means that you’ll never get low-positive numbers. It’s a toggle. You’ll either get 8px or 0px and nothing in between. Try removing that part, resizing the screen, and seeing it sorta morph as the viewport becomes close to the component size

But I regretted not putting a video in there to make the concept clearer, so I’ll rectify that here.


The post Other Looks at the Conditional Border Radius Trick appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

Semantic menu context

Category Image 052

Scott digs into the history of the <menu> element. He traced it as far back as HTML 2 (!) in a 1994 changelog. The vibe then, it seems, was to mark up a list. I would suspect the intention is much like <nav> is today, but I really don’t know.

Short story: HTML 4 deprecated it, HTML 5 revived it—this time as a “group of commands”—and then HTML 5.2 deprecated it again. Kind of a bummer since it has some clear use cases.

So, it’s been quite the roller coaster for ol’ <menu>! There never seems to be any easy wins for HTML evolution. As of now, it’s in “don’t bother” territory:

I really wrote this post as a sort of counter point to the often uttered phrase “use semantic HTML and you get accessibility for free!” That statement, on its surface, is largely true. And you should use semantic HTML wherever its use is appropriate. <menu>, unfortunately, doesn’t really give us all that much, even though it has clearly defined semantics. Its intended semantics and what we actually need in reality are better served by either just using the more robust <ul> element, or creating your own role=toolbarmenubar, etc.. Using this semantic element, for semantics sake, is just that.

To Shared LinkPermalink on CSS-Tricks


The post Semantic menu context appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

How to Remove Render-Blocking JS & CSS for Site Speed

Category Image 052

How to Improve Speed by Removing Render-blocking JS & CSSWhile the aesthetics of a website are important, its content and loading speeds keep people coming back. WordPress supplies users with a sophisticated toolbox of plugins and themes to create their very own custom websites quickly. However, these themes and plugins require JavaScript (JS) and Cascading Style Sheets (CSS) to work. WordPress creates them automatically […]

The post How to Remove Render-Blocking JS & CSS for Site Speed appeared first on WPExplorer.

How CSS Subgrids Make Vertical Alignment Easy

Category Image 052

Do you know that both the grids and alignment CSS properties are always talked about together? Why? Because of the nature of their existence and the mess that alignment creates on different screen devices. How easy and convenient would web developers’ lives become if all the devices in this world existed with the same screen size. That would be a dream! But coming back to reality, we have to deal with hundreds of devices with varying screen sizes, and the problems they create for the developers with alignment is an add-on. CSS grids and CSS subgrids were introduced to tackle the alignment problem with multiple elements existing side by side.

Grids were responsive, and instead of the “hit and try” of pixel and margin values, setting display: grid worked like a charm. As time stands witness to the issues tackled by web developers, if they do not have one, they invent one themselves. Now the developers have started to create complex web designs with one grid nested with other grids. That was a makeshift arrangement, and making it work was an endeavor in itself.

A Deep Dive Into object-fit And background-size In CSS

Category Image 052

We’re not always able to load different-sized images for an HTML element. If we use a width and height that isn’t proportional to the image’s Aspect ratio, the image might either be compressed or stretched. That isn’t good, and it can be solved either with object-fit for an img element or by using background-size.

First, let’s define the problem. Consider the following figure:

Why is this happening?

An image will have an Aspect ratio, and the browser will fill the containing box with that image. If the image’s Aspect ratio is different than the width and height specified for it, then the result will be either a squeezed or stretched image.

We see this in the following figure:

The Solution

We don’t always need to add a different-sized image when the Aspect ratio of the image doesn’t align with the containing element’s width and height. Before diving into CSS solutions, I want to show you how we used to do this in photo-editing apps:

Now that we understand how that works, let’s get into how this works in the browser. (Spoiler alert: It’s easier!)

CSS object-fit

The object-fit property defines how the content of a replaced element such as img or video should be resized to fit its container. The default value for object-fit is fill, which can result in an image being squeezed or stretched.

Let’s go over the possible values.

Possible Values for object-fit

object-fit: contain

In this case, the image will be resized to fit the Aspect ratio of its container. If the image’s Aspect ratio doesn’t match the container’s, it will be letterboxed.

object-fit: cover

Here, the image will also be resized to fit the Aspect ratio of its container, and if the image’s Aspect ratio doesn’t match the container’s, then it will be clipped to fit.

object-fit: fill

With this, the image will be resized to fit the Aspect ratio of its container, and if the image’s Aspect ratio doesn’t match the container’s, it will be either squeezed or stretched. We don’t want that.

object-fit: none

In this case, the image won’t be resized at all, neither stretched nor squeezed. It works like the cover value, but it doesn’t respect its container’s Aspect ratio.

Aside from object-fit, we also have the object-position property, which is responsible for positioning an image within its container.

Possible Values For object-position

The object-position property works similar to CSS’ background-position property:

The top and bottom keywords also work when the Aspect ratio of the containing box is vertically larger:

CSS background-size

With background-size, the first difference is that we’re dealing with the background, not an HTML (img) element.

Possible Values for background-size

The possible values for background-size are auto, contain, and cover.

background-size: auto

With auto, the image will stay at its default size:

background-size: cover

Here, the image will be resized to fit in the container. If the Aspect ratios are not the same, then the image will be masked to fit.

background-size: contain

In this case, the image will be resized to fit in the container. If the Aspect ratios are off, then the image will be letterboxed as shown in the next example:

As for background-position, it’s similar to how object-position works. The only difference is that the default position of object-position is different than that of background-position.

When Not to Use object-fit or background-size

If the element or the image is given a fixed height and has either background-size: cover or object-fit: cover applied to it, there will be a point where the image will be too wide, thus losing important detail that might affect how the user perceives the image.

Consider the following example in which the image is given a fixed height:

.card__thumb {
    height: 220px;
}

If the card’s container is too wide, it will result in what we see on the right (an image that is too wide). That is because we are not specifying an Aspect ratio.

There is only one of two fixes for this. The first is to use the padding hack to create an intrinsic ratio.

.card__thumb {
    position: relative;
    padding-bottom: 75%;
    height: 0;
}

.card__thumb img {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

The second fix is to use the new aspect-ratio CSS property. Using it, we can do the following:

.card__thumb img {
    aspect-ratio: 4 / 3;
}

Note: I’ve already written about the aspect-ratio property in detail in case you want to learn about it: “Let’s Learn About Aspect Ratio In CSS”.

Use Cases And Examples

User Avatars

A perfect use case for object-fit: cover is user avatars. The Aspect ratio allowed for an avatar is often square. Placing an image in a square container could distort the image.

.c-avatar {
    object-fit: cover;
}

Logos List

Listing the clients of a business is important. We will often use logos for this purpose. Because the logos will have different sizes, we need a way to resize them without distorting them.

Thankfully, object-fit: contain is a good solution for that.

.logo__img {
    width: 150px;
    height: 80px;
    object-fit: contain;
}

Article Thumbnail

This is a very common use case. The container for an article thumbnail might not always have an image with the same Aspect ratio. This issue should be fixed by the content management system (CMS) in the first place, but it isn’t always.

.article__thumb {
    object-fit: cover;
}

Hero Background

In this use case, the decision of whether to use an img element or a CSS background will depend on the following:

  • Is the image important? If CSS is disabled for some reason, would we want the user to see the image?
  • Or is the image’s purpose merely decorative?

Based on our answer, we can decide which feature to use. If the image is important:

<section class="hero">
    <img class="hero__thumb" src="thumb.jpg" alt="" />
</section>
.hero {
    position: relative;
}

.hero__thumb {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;    
}

If the image is decorative, we can go with background-image:

.hero {
    position: relative;
    background-image: linear-gradient(to top, #a34242, rgba(0,0,0,0), url("thumb.jpg");
    background-repeat: no-repeat;
    background-size: cover;
}

The CSS is shorter in this case. Make sure that any text placed over the image is readable and accessible.

Adding a Background to an Image With object-fit: contain

Did you know that you can add a background color to img? We would benefit from that when also using object-fit: contain.

In the example below, we have a grid of images. When the Aspect ratios of the image and the container are different, the background color will appear.

img {
    object-fit: contain;
    background-color: #def4fd;
}

Video Element

Have you ever needed a video as a background? If so, then you probably wanted it to take up the full width and height of its parent.

.hero {
    position: relative;
    background-color: #def4fd;
}

.hero__video {
    position: aboslute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}

To make it fully cover the width and height of its parent, we need to override the default object-fit value:

.hero__video {
    /* other styles */
    object-fit: cover;
}

Conclusion

As we’ve seen, both object-fit and background-size are very useful for handling different image Aspect ratios. We won’t always have control over setting the perfect dimensions for each image, and that’s where these two CSS features shine.

A friendly reminder on the accessibility implications of choosing between an img element and a CSS background: If the image is purely decorative, then go for a CSS background. Otherwise, an img is more suitable.

I hope you’ve found this article useful. Thank you for reading.

Container Units Should Be Pretty Handy

Category Image 052

Container queries are going to solve this long-standing issue in web design where we want to make design choices based on the size of an element (the container) rather than the size of the entire page. So, if a container is 600px wide, perhaps it has a row-like design, but any narrower than that it has a column-like design, and we’ll have that kind of control. That’s much different than transitioning between layouts based on screen size.

We can already size some things based on the size of an element, thanks to the % unit. For example, all these containers are 50% as wide as their parent container.

The % here is 1-to-1 with the property in use, so width is a % of width. Likewise, I could use % for font-size, but it will be a % of the parent container’s font-size. There is nothing that lets me cross properties and set the font-size as a % of a container’s width.

That is, unless we get container units! Here’s the table of units per the draft spec:

unitrelative to
qw1% of a query container’s width
qh1% of a query container’s height
qi1% of a query container’s inline size
qb1% of a query container’s block size
qminThe smaller value of qi or qb
qmaxThe larger value of qi or qb

With these, I could easily set the font-size to a percentage of the parent container’s width. Or line-height! Or gap! Or margin! Or whatever!

Miriam notes that we can actually play with these units right now in Chrome Canary, as long as the container queries flag is on.

I had a quick play too. I’ll just put a video here as that’ll be easier to see in these super early days.

And some great exploratory work from Scott here as well:

Ahmad Shadeed is also all over this!

Query units can save us effort and time when dealing with things like font-sizepadding, and margin within a component. Instead of manually increasing the font size, we can use query units instead.

Ahmad Shadeed, “CSS Container Query Units”

Maybe container queries and container units will drop for real at the same time. 🤷


The post Container Units Should Be Pretty Handy appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

Automattic Acquires Social Image Generator Plugin, Plans to Integrate with Jetpack

Category Image 052
Social Image Generator plugin

Automattic has acquired the Social Image Generator plugin, a commercial product that automatically creates social share images for WordPress content from a set of fully customizable templates. The plugin launched in February 2021, with a starting price of $39/year but is now closed to new sales. Daniel Post, the plugin’s creator, is joining Automattic to continue developing it as a new addition to Jetpack’s social media tools.

Automattic is always on the prowl for companies that are doing something interesting in the WordPress ecosystem. The Social Image Generator plugin expertly captured a new niche with an interface that feels like a natural part of WordPress and impressed our chief plugin critic, Justin Tadlock, in a recent review.

“Automattic approached me and let me know they were fans of my plugin,” Post said. “And then we started talking to see what it would be like to work together. We were actually introduced by Chris Coyier from CSS-Tricks, who uses both our products.”

The Social Image Generator plugin has always been a commercial-only product, which tends to limit a plugin’s reach within a market that has been so heavily trained on the freemium model. Its acquisition will undoubtedly get it into the hands of more WordPress users.

“I briefly considered building a freemium plugin but I decided to focus on paid licenses to make sure I could provide great support to all users and, frankly, to see how well it would be received compared to a freemium plugin,” Post said.

Current customers will be able to continue using the plugin “without any changes in the near term,” according to the announcement on the Jetpack blog. Those who have strong opinions about the long-term future of the plugin are encouraged to schedule a session with Jetpack Customer Research to open a dialogue.

“I look forward to the future functionality and user experience improvements that will come out of this acquisition,” Jetpack General Manager James Grierson said. “The goal of our social product is to help content creators expand their audience through increased distribution and engagement. Social Image Generator will be a key component of helping us deliver this to our customers.“

I would not be surprised to see this plugin available on one of Jetpack’s paid tiers in the near future, alongside the Publicize module’s other paid features (scheduling social media posts, tracking and viewing sharing history, and re-sharing existing content). Social Image Generator makes WordPress content more engaging on social media, has built-in support for WooCommerce, and can be extended for use with other plugins. It’s a strategic acquisition where Automattic gains an engineer as well as a new way to make Jetpack subscriptions more compelling.

“We are still figuring out our exact approach, but the initial plans are to integrate the Social Image Generator features with the existing Jetpack social tools like Publicize,” Post said. “The ability to see exactly what your social media post will look like before publishing it right from your WordPress site is incredible, and a big reason why I’m so excited about this acquisition.”

How to Change the Admin Color Scheme in WordPress (Quick & Easy)

Featured Imgs 19

Do you want to change the admin color scheme in WordPress?

Changing the color scheme of the WordPress admin lets you create a custom dashboard for you and your team. The color scheme can match the design of your brand, or just feature your favorite colors.

In this article, we’ll show you how to change the admin color scheme in WordPress easily.

How to change the admin color scheme in WordPress

Why Change the Admin Color Scheme in WordPress?

If you’re not a fan of the default admin color scheme in WordPress, then you can easily change the color scheme to something you like.

You can also change the color scheme to match the design of your WordPress theme, or even add a dark mode feature.

This can be useful if you have a membership site or online store where users can log in to your site, and want your website and admin dashboard to offer a similar experience.

You could also use a different admin color scheme for your staging site to more easily tell it apart from your live site.

That being said, let’s show you a few different ways you can change the admin color scheme in WordPress. You can use the quick links below to jump straight to the method you want to use.

How to Change the Admin Color Scheme with WordPress Default Settings

WordPress has a built in feature that lets you choose from a few predetermined color palettes for your WordPress admin dashboard.

To change the admin color scheme, simply login to your WordPress admin dashboard, and then navigate to Users » Profile.

After that, select the new color scheme in the ‘Admin Color Scheme’ section by clicking the radio button.

Select new admin color scheme

There are 9 different color schemes to choose from.

As you click different options, the color scheme will automatically change.

Admin color scheme change example

Once you’ve selected a color scheme you like, you need to scroll down to the bottom of the page and click the ‘Update Profile’ button.

Save new admin color scheme

You can also control the admin color scheme for other registered users on your WordPress website.

To do this, go to Users » All Users, and then hover over the user and click the ‘Edit’ button.

Edit user color scheme

Then, simply follow the same process as above to change the admin color scheme for that user.

Once you’re finished, make sure to click the ‘Update Profile’ button at the bottom of the page.

How to Create Custom Admin Color Schemes in WordPress

If you want even more color choices for your admin dashboard, then you can create custom color schemes and upload them to your WordPress blog.

To do this, go to the free WordPress Admin Colors website and click the ’Start Creating’ button.

Click start creating button

Then, enter a name into the ‘Color Scheme Name’ box.

This name will show up in your WordPress admin panel as a new color option.

Enter color scheme name

After that, you can fully customize your color scheme by clicking the color options in the ‘Choose your colors’ section.

To change one of the existing colors, click the color and choose your new color from the popup. You can click anywhere on the color picker, or enter a hex code for a specific color.

Click to customize colors

Once you’re finished customizing your color scheme, click the ‘Generate Color Scheme’ button at the bottom of the page.

This will create the color scheme code that you need to add to WordPress.

Click to generate color scheme

On the next page there will be two different code files.

You need to download the CSS file and copy the code snippet and paste it into your favorite text editor. We will be adding these to your WordPress files.

Download CSS and copy PHP code

If you haven’t done this before, then check out our guide on how to copy and paste code in WordPress.

You can add the code snippet to your functions.php file, in a site-specific plugin, or by using a code snippets plugin.

For this tutorial, we’ll use a code snippets plugin. It’s the easiest and most beginner-friendly method of adding code snippets to your WordPress site.

First, you need to install the Code Snippets plugin. For more details, see our beginner’s guide on how to install a WordPress plugin.

Upon activation, you’ll have a new menu item labeled ‘Snippets’ in your WordPress admin bar. Go ahead and navigate to Snippets » Add New.

Then, give your code snippet a name. This can be anything to help you remember your code.

After that, you can paste the snippet you copied above into the ‘Code’ box.

Name and add new code snippet

Next, click the ‘Save Changes and Activate’ button at the bottom of the screen.

This will save the code and activate the new admin color scheme.

Save and activate code snippet

Now, you need to upload the CSS stylesheet you downloaded earlier to your theme directory in your WordPress hosting account.

To do this, you can use an FTP client, or the file manager option in your WordPress hosting control panel.

If you haven’t used FTP before, then you might want to check out our guide on how to use FTP to upload files to WordPress.

First, you need to connect to your website using an FTP client, or the file manager in cPanel. Once you’re connected, you need to navigate to the /wp-content folder.

Select wp-content folder FTP

Inside the wp-content folder, you will see a folder called themes. This is where WordPress stores all the themes your website uses or has used in the past.

You need to click on the themes folder, and then open up the folder for the theme you’re using.

Open themes folder and select theme

Then, upload the display.css file that you downloaded.

Your CSS file will have the name that you chose earlier.

Upload new CSS file

Note: If you change WordPress themes, then you will need to upload the CSS file to your new theme folder.

After that, navigate to Users » Your Profile.

Then, you can select the new color scheme you just created.

Select custom color scheme

If you want to use this color scheme, then make sure to click the ‘Update Profile’ button at the bottom of the page.

How to Control the Default Admin Color Scheme for New Users

When a new user creates an account, they’ll have the option to customize their color scheme. But, you may want to control the default admin color scheme or prevent users from changing the color scheme altogether.

The easiest way to do this is by using the free plugin Force Admin Color Scheme.

First, you need to install and activate the plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, navigate to Users » Profile and then select your admin color and click the ‘Force this admin color scheme on all users’ checkbox.

Check force admin color scheme checkbox

After that, click the ‘Update Profile’ button at the bottom of the page.

Now the default admin color scheme will be the same for all new and existing users on your site.

The plugin also disables the admin color scheme selector for all of your users. The only users who can change this color are those with admin access.

We hope this article helped you learn how to change the admin color scheme in WordPress. You may also want to see our expert picks on the best WordPress landing page plugins and our guide on how to choose the best domain name registrar.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Change the Admin Color Scheme in WordPress (Quick & Easy) appeared first on WPBeginner.

What I Wish I Knew About CSS When Starting Out As A Front-Ender

Category Image 052

Nathan Hardy shares when things “clicked”:

Reflecting back on this time, I think there are a few key concepts that were vital to things finally all making sense and fitting together. These were:

• The Box Model (e.g. box-sizing, height, width, margin, padding)
• Layout (e.g. display)
• Document Flow and Positioning (e.g. position, top, left, etc.)

I called this my ah-ha moment a few years back:

For me, it was a couple of concepts that felt like an unlocking of real power. It was a combination of these concepts that were my “Ah-ha!” moment.

• Every page element is a box.
• I can control the size and position of those boxes.
• I can give those boxes background images.

People shared their own as well. And again.

It’s really the deal.

Direct Link to ArticlePermalink


The post What I Wish I Knew About CSS When Starting Out As A Front-Ender appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

How to Easily Optimize WordPress CSS Delivery (2 Methods)

Category Image 052

Would you like to optimize your WordPress CSS delivery?

CSS files control the visual formatting and style of your WordPress website. But if your CSS code isn’t delivered in an optimal way, then it could be slowing down your website.

In this article, we’ll show you two easy methods to optimize your WordPress CSS delivery.

How to Easily Optimize CSS Delivery in WordPress

How WordPress CSS Delivery Affects WordPress Performance

CSS files are used to define the visual appearance of your WordPress site. Your WordPress theme contains a CSS stylesheet file, and some of your plugins may also use CSS stylesheets.

CSS is necessary for modern websites, but it’s possible for CSS files to slow down your site’s speed and performance depending on how they’re set up.

Even a small delay in site speed creates a bad user experience and may affect your search rankings and conversions, resulting in less traffic and sales.

StrangeLoop study

One way that CSS files can slow your website is if they need to be loaded before the page can be displayed. That means your visitors will see a blank page until the CSS file has loaded. This is known as render-blocking CSS.

Another common reason CSS files can slow your website is when they contain more code than is needed to display the visible part of the current page. That extra code means that they will take longer to load.

The good news is, you can improve your WordPress site’s performance by optimizing the way the CSS code is delivered.

That’s done by identifying the minimum CSS code needed to display the first part of the current web page. This is known as critical CSS.

This critical code is then added inline to the page’s HTML, instead of in separate stylesheets, so that the code can be rendered without needing to load the CSS file first.

The rest of the CSS can then be loaded after your visitors can see the contents of the page. This is known as ‘deferred loading’.

In this tutorial, we’ll show you two methods to optimize WordPress CSS delivery, and you can choose the one that works best for you.

Method 1: Optimizing WordPress CSS Delivery with WP Rocket

WP Rocket is the best WordPress caching plugin in the market. It offers the simplest way to optimize your WordPress CSS delivery. In fact, it’s as easy as checking a box.

WP Rocket is a premium plugin, but the best part is that all features are included in their lowest plan.

The first thing you need to do is install and activate the WP Rocket plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Once activated, you need to navigate to the Settings » WP Rocket page and switch to the ‘File Optimization’ tab.

Switch to the File Optimization Tab

Next, you need to scroll down to the CSS files section. Once there, you need to check the box next to the ‘Optimize CSS delivery’ option.

Check Optimize CSS Delivery

This feature will intelligently identify the critical CSS needed to format the part of the web page your visitors see first. Your pages will load more quickly, and the rest of the CSS will be loaded after your visitors can see its contents.

All you need to do now is click the Save Changes button and wait for WP Rocket to generate the necessary CSS file for all your posts and pages.

It will also automatically clear the cache for your website, so that your visitors will see the new optimized version of your site instead of the any unoptimized versions stored in cache.

There are plenty of other ways that WP Rocket can help you improve your website’s performance. To learn more, see our guide on how to properly install and setup WP Rocket in WordPress.

Method 2: Optimizing WordPress CSS Delivery with Autoptimize

Autoptimize is a free plugin designed to improve the delivery of your website’s CSS and JS files.

While Autoptimize is a free plugin, it doesn’t have as many features as WP Rocket and takes more time to set up.

For example, it’s not able to automatically identify critical CSS like WP Rocket can. Instead, Autoptimize requires the help of a premium third-party service which is an additional cost and requires extra time to configure.

However, it could be a good option if you’re on a tight budget and don’t need all the other features of WP Rocket to speed up your site.

The first thing you need to do is install and activate the Autoptimize plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to visit the Settings » Autoptimize page to configure the plugin settings. Once there, you need to scroll down to the CSS Options section and check the Optimize CSS Code box at the top.

Scroll Down to CSS Options

Once you do that you need to make sure that ‘Aggregate CSS-files’ option is unchecked and then check ‘Eliminate render-blocking CSS’.

You can now click on the ‘Save Changes and Empty Cache’ button to store your settings.

But the plugin will not work properly until you sign up for a Critical CSS account. This is a premium subscription service that will provide Autoptimize the critical CSS code it needs to optimize your WordPress CSS delivery.

To do that, navigate to the Critical CSS tab in Autoptimize’s settings. Here you’ll find the information you need to sign up with Critical CSS. You can get started by clicking the sign up link in the third paragraph.

Sign Up for a Critical CSS Account

Once you’ve received your Critical CSS API key, scroll down to the API Key section so you can paste it into the ‘Your API key’ text box. After that, make sure you click the Save Changes button.

Paste Your Critical CSS API Key

Autoptimize now has all of the information it needs to add the critical CSS inline and defer loading the stylesheets until after the page has been rendered. As a result, your website will load more quickly.

We hope this tutorial helped you learn how to optimize WordPress CSS delivery.

You may also want to see our ultimate guide on how much it really costs to build a WordPress website, and our comparison of the best managed WordPress hosting companies.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Easily Optimize WordPress CSS Delivery (2 Methods) appeared first on WPBeginner.

You want enabling CSS selectors, not disabling ones

Category Image 052

I think this is good advice from Silvestar Bistrović:

An enabling selector is what I call a selector that does a job without disabling the particular rule.

The classic example is applying margin to everything, only to have to remove it from the final element because it adds space in a place you don’t want.

.card {
  margin-bottom: 1rem;
}

/* Wait but not on the last one!! */
.parent-of-cards :last-child {
  margin-bottom: 0;
}

You might also do…

/* "Disabling" rule */
.card:last-child {
  margin-bottom: 0;
}

But that’s maybe not as contextual as selecting from the parent.

Another variation is:

.card:not(:last-of-child) {
  margin-bottom: 1rem;
}

That’s what Silvestar refers to as “enabling” because you’re only ever applying this rule — not applying it and then removing it with another selector later. I agree that’s harder to understand and error-prone.

Yet another example is a scoped version of Lobotomized Owls:

/* Only space them out if they stack */
.card + .card {
  margin-top: 1rem;
}

I think gap is where this is all headed in the long term. Put the onus on the parent, not the child, and keep it an enabling selector:

.parent-of-cards {
  display: grid;
  gap: 1rem;
}

Direct Link to ArticlePermalink


The post You want enabling CSS selectors, not disabling ones appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

Adding Custom HTML Attributes With the Block Attributes Plugin

Category Image 052

Earlier this week, websevendev released its fourth WordPress plugin to the official directory named Block Attributes. The extension allows end-users to add any HTML attribute to nearly any block.

One of the problems with the WordPress editor is that it can be a bit fussy about customizing HTML. Blocks are built on a set of standards, and the markup is supposed to meet those expectations. If something does not fit, users see an invalid markup warning.

However, there are times when users need to drop in a custom HTML attribute for various reasons. For example, I sometimes need to add a custom data- attribute for working with a bit of JavaScript. Since I know my way around code well enough, I typically write out the HTML in those situations via the Custom HTML block. But, that does not make sense when minor attribute additions are called for.

WordPress currently allows users to add classes and IDs (called an “HTML anchor” in the admin) to almost every block. It does not allow for direct input of the dozens of other possible attributes that HTML supports. The use cases for the average user are few and far between.

For those scenarios where some users could use the extra feature, the Block Attributes plugin is handy.

The plugin is straightforward to use. It adds a new field named “Additional attributes” under the Advanced tab of every block. Users can add the attribute name and click the “Add” button. From there, it creates a new field for adding the attribute value.

Adding a custom attribute for JavaScript handling to a Button block in the WordPress editor via the Block Attributes plugin panel.
Adding an onclick attribute to a Button block.

The plugin also supports multiple attributes. Once you add one, you simply use the same input field to create more.

For my first test drive, I added a simple onclick attribute with a value of myFunction(). Then, I hopped over to my theme and created that function via JavaScript to output a simple message in the console. Everything looked good under the hood, and it worked.

Most of the use cases I have in mind are for integrating with JavaScript, and this was a simple example of what is possible. There are far more complex things a developer could do with such a feature. That is reason enough to keep this plugin in the toolbox — sometimes you need a wrench instead of a hammer.

I could also see Block Attributes being used for adding ARIA attributes in other situations where it might aid accessibility.

Users could add custom styles to a specific block via a style attribute with the plugin. However, unless this is a simple one-off, I would recommend against it. For more advanced use cases, Blocks CSS is a far more suitable plugin. It has a built-in syntax highlighter. Plus, a textarea is friendlier than a one-line text input box.

The only downside to Block Attributes I have seen is upon deactivation. You will see the dreaded “this block contains unexpected or invalid content” message in the editor if you have added any custom attributes. The editor has managed to resolve any issues I have run into with the core blocks.

Side-by-side view of the block resolution popup modal in the WordPress editor.
Resolving block warning after deactivating plugin.

Deactivating the plugin should not affect the front-end output. Because the custom attributes are a part of the HTML markup, they will still be there. The error message should only show in the editor.

“We had 90% unused CSS because everybody was afraid to touch the old stuff”

Category Image 052

Over at the JS Party podcast:

[Kend C. Dodds]: […] ask anybody who’s done regular, old CSS and they’ll tell you that “I don’t know if it’s okay for me to change this, so I’m gonna duplicate it.” And now we’ve got – at PayPal (this is not made up) we had 90% unused CSS on the project I was using, because everybody was afraid to touch the old stuff. So we just duplicated something new and called it something else. And you might just say that we’re bad at CSS, but maybe CSS was bad at us, I don’t know… [laughter]

[Emma Bostain]: Well, that’s why styled-components and CSS-in-JS was so pivotal; it was like “Oh, hey, we can actually encapsulate all of this logic inside the component that it’s touching and don’t have to worry about bleeding code anymore.” It’s so much easier to delete things, and add things, and all of those things.

[Kend C. Dodds]: Yeah, you’re precisely right. That was the problem that those things were made to solve.

Audio clip:

I’ve heard this exact story before several times, usually from large companies. Lots of developers, typical developer turnover… nobody knows what CSS is actually used and what isn’t because that is a very hard problem.

That’s one of the reasons I sometimes like component-based-styling solutions (CSS-in-JS, if you’re nasty). Not because I love complex tooling. Not because I like JavaScript syntax better than CSS. Because of the co-location of styles and componentry. Because nobody is afraid of the styles anymore — they are tightly coupled to what they are styling. It’s not needed on every project, but if you’re building with components anyway (an awfully nice way to architect front-ends that doesn’t require JavaScript), you might as well style this way.

For this reason, I’m excited that “scoped styles” are making a bit of a comeback in standards discussions.

I remember an ancient idea (that maybe even shipped in browsers for a minute?) where you’d just chuck a <style scoped> block right in the HTML and whatever the parent was, the styles were scoped to that parent. That was so cool, I wish we could have that again.

But it seems like the newer stuff (here’s Miriam’s original proposal) has some more clever stuff that that basic concept doesn’t cover — like being able to set a lower-boundary in addition to an upper-boundary, making it possible to scope “donut-shaped” styles in the DOM (a Nicole Sullivan term). Whatever happens, shadow DOM-free scoped styles with zero tooling is huge.


The post “We had 90% unused CSS because everybody was afraid to touch the old stuff” appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

Tabs in HTML?

Category Image 052
You know what tabs are, Brian.

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

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

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

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

Direct Link to ArticlePermalink


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