This article discusses 20 methods to optimize CSS, aiming to improve loading speed, simplify development and improve efficiency. According to the latest HTTP Archive report, there is a widespread problem of resource redundancy on websites, median websites require 1700KB of data, 80 HTTP requests, and it takes 17 seconds to fully load on mobile devices. A complete guide to reducing page weight provides a variety of suggestions, and this article will focus on CSS optimization. Although CSS is usually not the culprit of performance issues, a typical website uses only 40KB of CSS scattered in five style sheets, there is still room for optimization, and changing the way CSS is used can also improve website performance.
Key Points
The performance issue cannot be solved unless you know the problem. Browser Developer Tools are the best starting point: Start from the menu or press F12, Ctrl Shift I or Safari on macOS Cmd Alt I. All browsers offer similar features, and the tool will load slowly on poorly performing pages! However, the most useful tabs include the following… The Network tab displays a waterfall diagram of the resource download. For best results, disable caching and consider slowing down network speed. Find files that download slowly or block other resources. Browsers usually block browser rendering when CSS and JavaScript files are downloaded and parsed. The Performance tab analyzes browser processes. Start recording, run activities such as page reloading, and then stop recording to view the results. Search: 1. Too many layout/rearrange operations, the browser is forced to recalculate the position and size of the page elements; 2. In the costly drawing operation, the pixel changes; 3. Composition
operation, grouping the drawn parts of the page together for display on the screen. This is usually the least processor resource-consuming operation.The Chrome-based browser provides an "Audit" tab that runs Google's Lighthouse tool. It is usually used by progressive web application developers, but also provides CSS performance recommendations.
Online options
Or, use online analytics tools that are not affected by device and network speed and capabilities. Most tools can be tested from different locations around the world:
CSS is unlikely to be a direct cause of performance issues. However, it may load heavyweight resources that need to be optimized in minutes. For example:
Images are usually the reason for the largest page size, but many websites fail to optimize effectively:
That is, please note that the image data of xKB is not equivalent to the CSS code of xKB. Binary images are downloaded in parallel and need little processing to be placed on the page. CSS blocks rendering and must be parsed into an object model to continue.
It is rare to use background images to create borders, shadows, rounded corners, gradients and some geometric shapes. Defining "images" with CSS code will use less bandwidth and will be easier to modify or animate later.
Services such as Google Fonts make it easy to add custom fonts to any page. Unfortunately, one or two lines of code can retrieve hundreds of kilobytes of font data. Suggestions:
Use only the required fonts.
Load only the required thickness and styles - for example, Roman, 400 thickness, no italics.
Limit character sets as much as possible. Google Fonts allows you to select certain characters by adding a &text=
value to the font URL - for example, fonts.googleapis.com/css?family=Open Sans&text=SitePon
to display "SitePoint" in Open Sans.
Consider variable fonts, which define multiple thicknesses and styles through interpolation, so the file is smaller. Currently support is limited to Chrome, Edge and some versions of Safari, but it should grow rapidly.
Consider operating system fonts. Your 500KB web font may be brand-friendly, but if you switch to the commonly used Helvetica or Arial, will anyone notice it? Many websites use custom web fonts, so the standard operating system fonts are much less than before!
Avoid using @import
@import
Rules allow any CSS file to be included in another CSS file. For example:
/* main.css */ @import url("base.css"); @import url("layout.css"); @import url("carousel.css");
This seems to be a reasonable way to load smaller components and fonts. This is not the case. rules can be nested, so the browser must load and parse each file in order. Multiple @import
tags in HTML will load CSS files in parallel, which is much more efficient – especially when using HTTP/2: <link>
<link rel="stylesheet" href="base.css"> <link rel="stylesheet" href="layout.css"> <link rel="stylesheet" href="carousel.css">
widgets/_carousel.css
. !important
to overwrite cascades. Tools such as UnCSS can help remove redundant code by analyzing your HTML, but be careful about the CSS state caused by JavaScript interactions.
The rise of CSS-in-JS allows developers to avoid CSS global namespaces. Usually, randomly generated class names are created at build time, so components cannot conflict. If CSS-in-JS improves your life, then keep using it. However, it is worth understanding the advantages of CSS cascading, rather than fighting it in every project. For example, you can set default font, color, size, table, and form fields that are commonly applied to each element in a single location. It is rare to declare each style in each component.
Even the most complex CSS selectors take a few milliseconds to parse, but reducing complexity will reduce file size and help browser parse. Do you really need this selector? !
/* main.css */ @import url("base.css"); @import url("layout.css"); @import url("carousel.css");
Similarly, be aware of deep nesting in preprocessors such as Sass, where complex selectors may be created inadvertently.
Some properties render slower than others. To increase lag, try placing box shadows on all elements!
<link rel="stylesheet" href="base.css"> <link rel="stylesheet" href="layout.css"> <link rel="stylesheet" href="carousel.css">
Browser performance will vary, but generally speaking, any operation that causes recalculation before drawing will be more expensive in terms of performance:
border-radius
box-shadow
opacity
transform
filter
position: fixed
Native CSS conversions and animations are always faster than JavaScript drivers that modify the same properties. CSS animations don't work in older browsers like IE9 and below, but these users will never know what they're missing. That is, avoid animation for animation. Subtle effects can enhance the user experience without adversely affecting performance. Too much animation may slow down the browser and may cause motion sickness in some users.
Animating the size or position of the element may cause the entire page to be re-layout on every frame. If the animation only affects the synthesis stage, performance can be improved. The most effective animation usage:
opacity
and/or transform
to pan (move), scale or rotate elements (the original space used by the element will not change). Browsers usually use hardware-accelerated GPUs to render these effects. If neither is ideal, consider using position: absolute
to remove elements from the page stream so that they can be animate in their own layers.
will-change
attribute allows the CSS author to indicate that the elements will be animate so that the browser can perform performance optimization in advance. For example, to declare that the application is converted to an element:
/* main.css */ @import url("base.css"); @import url("layout.css"); @import url("carousel.css");
Any number of comma-separated properties can be defined. But:
will-change
as a last resort to solve performance problemsScalable vector graphics (SVG) are commonly used for logos, charts, icons and simpler charts. Instead of defining the color of each pixel like JPG and PNG bitmaps, SVG defines shapes such as lines, rectangles, and circles using XML. For example:
<link rel="stylesheet" href="base.css"> <link rel="stylesheet" href="layout.css"> <link rel="stylesheet" href="carousel.css">
Simpler SVGs are smaller than equivalent bitmaps and can be scaled infinitely without losing clarity. SVG can be inlined directly as background images in CSS code. This may be ideal for smaller, reusable icons and avoids additional HTTP requests. For example:
body > main.main > section.first h2:nth-of-type(odd) + p::first-line > a[href$=".pdf"]
More typical, SVG is embedded directly into HTML documents:
*, ::before, ::after { box-shadow: 5px 5px 5px rgba(0,0,0,0.5); }
This will add the SVG node directly to the DOM. Therefore, all SVG style properties can be applied using CSS:
.myelement { will-change: transform; }
The number of embedded SVG code is reduced, and CSS styles can be reused or animated as needed. Note that using SVG inside img
tags or as CSS background images means they are separated from the DOM and the CSS style will not work.
Standard bitmap JPG, PNG, and GIF can be encoded as base64 strings in data URI. For example:
<svg xmlns="https://www.w3.org/2000/svg" viewBox="0 0 800 600"> <circle cx="400" cy="300" r="50" stroke-width="5" stroke="#f00" fill="#ff0" /> </svg>
Unfortunately:
While reducing HTTP requests, it rarely provides obvious benefits—especially on HTTP/2 connections. Generally, avoid inline bitmaps unless the image is unlikely to change frequently and the resulting base64 string is unlikely to exceed a few hundred characters.
Users using Google Page Analytics Tools will usually see suggestions "Inline Critical CSS" or "Reduce render blocking stylesheets" . Loading a CSS file blocks rendering, so you can use the following steps to improve performance:
<head>
element in HTML<style>
. This technology undoubtedly improves performance and may benefit progressive web or single-page applications with a continuous interface. For other websites/apps, the benefits may be less obvious:
Each
/* main.css */ @import url("base.css"); @import url("layout.css"); @import url("carousel.css");
. Progressive rendering may benefit large websites where individual pages are built with choices of different components. <link>
The most important tip: Learn your style sheet! Adding a lot of CSS from StackOverflow or BootStrap may produce fast results, but it will also bloat your codebase with unused junk. Further customization becomes frustratingly difficult and the application will never be efficient. CSS is easy to learn, but difficult to master. If you want to create valid client code, you cannot avoid this technique. Understanding some CSS basics can revolutionize your workflow, enhance your application and significantly improve performance. Am I missing your favorite CSS performance tips?
Frequently Asked Questions about Optimizing CSS Performance
CSS performance is affected by a variety of factors. First is the size of the CSS file. Larger files take longer to download and parse, thus slowing down the website. The second factor is the complexity of the CSS selector. Complex selectors require more processing power to match elements on the page. Finally, using CSS animations and transformations can also affect performance, especially on mobile devices with limited processing power.
There are various strategies to reduce the size of CSS files. One is to delete unused styles. Tools like PurifyCSS can help identify and delete unused CSS. Another strategy is to compress CSS, which removes unnecessary characters such as spaces and comments. Finally, consider using the CSS compression tool or enabling GZIP compression on the server to further reduce file size.
Complex CSS selectors slow down websites because they require more processing power to match elements on the page. For example, descendant selectors (e.g., .parent .child
) are more expensive than class selectors (e.g., .class
). As a rule of thumb, selectors should be kept as simple and specific as possible to improve performance.
CSS animations and transformations can significantly affect performance, especially on mobile devices with limited processing power. They can cause layout offsets and redraws, which can slow down the website. To improve performance, consider using the will-change
attribute to tell the browser in advance which attributes and elements will be animated.
Optimizing CSS for mobile devices involves a variety of strategies. First, consider using media queries to provide different styles based on device characteristics. Second, avoid complex animations and transformations that slow down performance on mobile devices. Finally, consider using responsive images and lazy loading to reduce the amount of data you need to download.
You can use a variety of tools to measure CSS performance. Google's Lighthouse and PageSpeed Insights can provide a comprehensive overview of website performance, including CSS. Additionally, the Performance panel of Chrome Developer Tools can help you identify and optimize costly CSS.
While CSS itself does not directly affect SEO, it will indirectly affect your ranking. Slow loading websites (usually caused by large unoptimized CSS) can lead to a bad user experience, which can negatively affect your SEO. Additionally, Google treats page speed as a ranking factor, so optimizing CSS can help improve your SEO.
CSS preprocessors such as Sass and Less can help improve performance by allowing you to write more efficient and easier to maintain code. They provide features like variables, nesting, and mixins that reduce the amount of code you need to write and make it easier to manage.
Critical CSS is the minimum amount of blocking CSS required to render the content above the web page screen. By identifying and inlining critical CSS, you can speed up the initial rendering of your page, thus improving perceptual performance.
Optimizing CSS delivery involves a variety of strategies. First, consider inlining small CSS directly into HTML to avoid additional HTTP requests. Second, delay non-critical CSS to reduce render blocking resources. Finally, consider using HTTP/2 to deliver CSS files more efficiently.
The above is the detailed content of 20 Tips for Optimizing CSS Performance. For more information, please follow other related articles on the PHP Chinese website!