Even in 2021, network performance is still a problem. According to HTTP Archive, an average of 2MB downloads are required per page, more than 60 HTTP requests are issued, and it may take 18 seconds to fully load on a mobile device. The stylesheet occupies 60 kB and is divided into seven requests, so it is rarely a top priority when trying to solve performance problems.
, however, CSS does have an impact, no matter how slight it may seem. Once the JavaScript problem is solved, learning to optimize CSS correctly should be the next priority. How
- CSS affects page performance
- CSS performance analysis tools
- indirect CSS performance optimization
- optimization CSS loading performance
- optimization CSS performance
CSS affects page performance
CSS looks innocent But it may require some heavy processing.
CSS rendering blocking
when the browser encounters atag, it stops downloading and processing by other browsers when it gets and parses the CSS file.
JavaScript can also prevent browsers from rendering, but asynchronous processing can be achieved by downloading the script in parallel with the
-
async
property and running the script as soon as it is ready. The -
defer
property is downloaded in parallel and then run sequentially when DOM is ready. The -
type="module"
property loads the ES module (which behaves likedefer
).
resources such as images usually require more bandwidth, but can use an efficient format and can delay loading (theloading="lazy"
property) without preventing browsers from rendering.
none of this is possible with CSS. The file is cached, so subsequent page loads should be faster, but the render blocking process still exists. The more time it takes for
large CSS files to process
stylesheets, the longer it will take to download and process the CSS object Model (CSSOM), which browsers and JavaScript API can use to display pages. Although CSS stylesheets are smaller than most other Web site files, they are not immune from the rule of thumb that the smaller the better.
CSS files grow it can be difficult for
to identify styles that are no longer in use, and deleting incorrect styles can cause serious damage to the site. Developers usually choose the safest “keep everything” approach. Page styles, components, and widgets that are no longer in use still exist in CSS. How did it turn out? File size, complexity, and maintenance workload have increased exponentially, making it less and less likely for developers to delete redundant code.
stylesheets can introduce other resources
CSS can use the @ import rule to reference other stylesheets. These imports block the processing of the current stylesheet and further load the CSS file in series. Other
assets, such as fonts and images, can also be referenced. The browser will try to optimize the download, but when in doubt, it will get them immediately. The 64-coded files on the lining base still need to be further processed.
CSS can reference other stylesheets using the @ import rule. These imports block the processing of the current stylesheet and load more CSS files serially.
can also reference other resources, such as fonts and images. The browser will try to optimize the download, but if in doubt, it will get the download immediately. Inline base64 encoding files need to be further processed. The
CSS effect rendering
browser has three rendering phases:
- The layout layout (or reflux reflow) phase calculates the size of each element and how it affects the size or position of the surrounding elements.
- The drawing paint phase draws the visual portion of each element onto a separate layer: text, color, image, border, shadow, and so on.
- render layer compositing (composite draws)draws each layer to the page in the correct order based on the stacking context, location, z-indexes, and so on. If
is not careful, CSS property changes and animation may cause all three stages to re-render. Some properties, such as shadows and gradients, are also more expensive to calculate than block colors and margins. The
CSS performance analysis tool
admits that you have a CSS performance problem is the first step to recovery! Finding and solving the cause is another matter.
the following tools and services (not in any order) can help you identify style bottlenecks in your code.
1. Developer tools
Web performance experts spend a lot of time developing tools, especially on the web panel. DevTools is the native version of most modern browsers, but we will use Google Chrome in the example.
DevTools can be opened from the browser menu, usually in “more tools” & gt; “developer tools”, or through keyboard shortcuts Ctrl, Cmd+Shift+I or F12.
Switch to the Network tab and make sure that disable caching is selected to prevent the cache file from affecting the report. You can also change the restriction option to simulate a slower mobile network.
refreshes the page to see the download and processing waterfall: any time-consuming load progress bar in the
DevTools network panel
is worth watching, but you should pay special attention to the blocking / stagnant loading progress bar (shown in white). In this case, the highlighted lines and all subsequent lines cannot start downloading until the rendering blocking CSS and JavaScript files are handled at the top of the HTML page. The
filter box allows you to show or hide specific resources:
-
larger-than:
: limit files larger than, representing -
-larger-than:
in bytes (10000), kilobytes (1000 kB), or megabytes (1m): limit files less than -
-domain:*
: show third-party requests that are not loaded from the primary domain. These are the main reasons for the slow speed of the website.
high-performance pages with optimized CSS usually have fewer resources, which are loaded in parallel with short blocking / pause bars.
2. WebPageTest
WebGetest provides a similar network waterfall view, as well as many other performance diagrams:
WebPageTest.org page resource loading waterfall diagram
this service uses devices based on different global locations, so you can evaluate real-world performance and CSS optimization.
3.The Chrome developer tools Lighthouse panel
DevTools Lighthouse panel is available in chromium-based browsers such as Chrome, Edge, Brave, Opera, and Vivaldi. You can generate performance, progressive Web applications, best practices, accessibility, and search engine optimization reports for mobile and desktop devices.
DevTools Lighthouse panel
this tool provides suggestions for improvements, including ways to optimize CSS. Not all of these are feasible, but the points that are most conducive to performance improvement are highlighted.
4. Google PageSpeed Insights
PageSpeed Insights is the online version of Lighthouse. It has fewer features, but can be used in any browser and provides some optional insights.
for example, a tree shows the largest JavaScript resource with a coverage metric that indicates the ratio of used to unused code: the
Google PageSpeed Insights tree
CSS does not show, but the number of JavaScript affects the efficiency of the style.
‘s similar website speed testing tools include more than a dozen such as Pingdom and GTmetrix.
5. Chrome developer tools coverage panel the DevTools coverage panel in the
Chromium browser helps locate unused CSS (and JavaScript) code. Select coverage from the DevTools more tools submenu, then refresh the page and browse the site / application: the
DevTools coverage panel
CSS and JavaScript assets are displayed in the coverage panel, and the proportion of unused code is indicated in red. Click any file to view its source code, and unused code is highlighted in red in the line number bar. A few things to keep in mind for
: if
- refreshes or navigates to a new page, the coverage metrics will be reset, which is typical on WordPress sites. Unused code metrics are reduced only when browsing a single-page application that loads content without refreshing the page.
- this tool can only explain CSS used at a specific point in time. It cannot determine whether the widget is not viewed or has multiple JavaScript binding states.
6. Chrome developer tools performance Monitor
Chromium-based browsers have a real-time performance monitor. Again, this is available from DevTools’s “more tools” menu. When you browse the page, scroll, and trigger the animation, the chart updates:
DevTools performance Monitor
the following metrics are particularly important for optimizing CSS performance (the lower the better):
- CPU usage: processor usage ranges from 0 to 100%.
- Layout / second: the rate at which the browser rearranges the page.
- Number of style recalculations per second: the browser must recalculate the rate of the style.
if CSS is in trouble due to external factors, other indicators may also be useful (again, lower values indicate better performance):
- JS heap size: the total memory used by the JavaScript object.
- DOM node: the number of elements in the HTML document.
- JS event listeners: the number of registered JavaScript event listeners.
- Documents: the number of resources, including pages, CSS files, JavaScript modules, etc.
- Document frames: the number of frames, iframe, and JavaScript working scripts.
7. Chrome developer tools performance report
DevTools performance panel allows you to record page activity for further analysis and to help identify performance issues The generated reports are complex and many developers avoid using them, but they provide valuable information. The settings icon in the
performance panel allows you to set various options, such as slowing down the network and CPU. You can also disable the JavaScript sample so that the detailed call stack is not recorded. To start
, click the circular record icon, load and / or use the page, and then click the stop button to view the report:
DevTools performance report
almost all of these metrics are useful to JavaScript developers, but CSS optimization problems may be particularly obvious in the following ways:
- Red bar at the top: this indicates a significant drop in frame rate, which can cause performance problems. This is appropriate at the beginning of page loading, but too much CSS animation can also be a problem.
- Summary chart: high loading, rendering, and plotting metrics may indicate CSS problems.
indirect CSS performance tuning the optimizers under
do not directly solve CSS problems, but they can help you solve some performance problems with relatively little effort.
make good use of the host
Using a good-performing host to bring the server closer to the user physically will bring immediate performance benefits. Hosting plans vary, but there are three main types:
- Shared hosting: your site is hosted on a physical server, possibly with hundreds of other sites. Share disk space, RAM, CPU time, and bandwidth. Planning is usually low-cost, but performance and availability are affected by other sites. Upgrades may be possible, but your site usually remains on the same infrastructure.
- Dedicated hosting: your site is hosted on one or more physical servers you own. Hardware can be configured and upgraded as needed. Planning is usually expensive, and hardware failures are still problematic.
- Cloud hosting: cloud hosting abstracts the hardware infrastructure into a set of services that can be accessed on demand. Your site can be configured across a range of devices to facilitate upgrades.
cloud hosting plans and prices vary widely. You can consider:
- Platform as a service (PaaS) options, such as virtual web servers and databases, or
- Software as a Service (SaaS) option that provides fully managed applications, such as WordPress.
switching hosts can improve performance. It is unlikely to solve all your problems, but it is a cost-effective solution to back-end and bandwidth problems.
you can also consider using a content delivery network (CDN) or professional image and video CDN, which distributes loads in multiple locations that are geographically closer to the user.
takes advantage of browser and server efficiency features
about 10% of sites do not activate gzip (or better) compression, which is usually the default server option. You can reduce the size of the CSS by 60% or more by compressing the file before transfer. It won’t fix inefficient CSS, but the code will arrive faster!
you should also activate HTTP/2 (or better), which sends data in a smaller binary format, compresses headers, and can send multiple files on the same TCP connection.
finally, make sure that browsers can cache CSS and other files effectively. This is usually a problem with setting Expires, Last Modified, and / or ETag hashes in the HTTP header.
optimized CMS
content management systems such as WordPress can be extended with themes and plug-ins that serve their own CSS. Where possible, you should speed up CMS to:
- remove unused plug-ins.
- uses a more concise theme,
- , to enable caching to prevent excessive page regeneration. The processing and rendering costs of
optimized images
images are different from those of HTML, CSS, and JavaScript, but they account for a large portion of the page weight and available bandwidth. Consider:
- deletes unnecessary images.
- resizes large images-probably no more than 150% of the maximum image size on the screen.
- uses the appropriate image format-ideally a highly compressed option such as WebP or AVIF, but it may be SVG for logos and charts.
- replaces the image with CSS gradients or other effects.
- adds width and height attributes to the
tag of the HTML, or uses the new CSS aspect ratio attribute to ensure that appropriate space is left on the page before the image is downloaded.
professional image CDN can handle some of this work for you. For more tips, check out our guide on how to optimize images for Web.
the fastest ways to remove unused CSS
styles are those that you never need to load or render! Try to delete / edit any CSS code that you no longer need, such as CSS code for legacy pages, widgets, or frames. On larger sites, this can be difficult, and it is not always clear whether a particular style set is required.
the following tools analyze the use of HTML and CSS at build time, or identify redundant code by crawling URL. This is not always sufficient, so you can set up other configurations to ensure that styles triggered by JavaScript and user interaction are listed:
- UnCSS
- UnusedCSS
- PurgeCSS
- PurifyCSS
has a better option: split CSS into separate files with a clear level of responsibility and document accordingly. Then, it becomes quite easy to delete unnecessary styles.
optimizes CSS loading performance
not all CSS loads are the same. The humbletag has many options and quirks that are not always logical.
optimized Web fonts using
Google fonts and similar font designers have revolutionized web fonts, but a few lines of font code can take up hundreds of KB of bandwidth.
the following are our optimization recommendations:
- Load only the fonts you need: delete unused fonts and check to see if new fonts are needed.
- Load only the required size and style: most font foundries can limit downloads to certain character sets (such as Latin only), weights (thickness), and italics (slanting). Browsers can automatically render missing styles, although the results may be poor.
- Limit the required characters: fonts that are not used frequently can be limited to specific characters. For example, the title “CSS tutorial” in the open SAN can be defined by adding a
&text=
parameter to the Google font query string:fonts.googleapis.com/css?family=Open+Sans&text=CStuorial
- Consider variable fonts: variable fonts define a large number of styles, weights, and italics, using vector interpolation. The font file is a little larger, but you only need one, not a few. Recursive font shows the flexibility of variable fonts.
- Load fonts from the local server: self-hosted fonts are more efficient than using contract manufacturing. Fewer DNS lookups are required, and you can restrict downloads to WOFF2, and all modern browsers support WOFF2. Older browsers (I’m looking at your IE) can go back to operating system fonts.
- Consider OS fonts: 500 KB Web fonts may look great, but if you switch to generic Helvetica, Arial, Georgia or Verdana, will anyone notice? Operating system or web-safe fonts are an easy way to improve performance. It may take several seconds for
to download and process Web fonts using the appropriate font loading option
. The browser will:
- Display unstyled text (FOUT): the first available fallback font is initially used, but once the web font is ready, it will be replaced.
- Show invisible text (FOIT): no text is displayed until the web font is ready. This is the default procedure in modern browsers and usually takes three seconds to revert to a fallback font. Neither of
is ideal. The CSS font-display property and the Google Font & display = parameter can choose an alternative:
- Auto: the default behavior of the browser (usually FOIT).
- Block: effectively stop. The text is not visible for up to three seconds. There is no font swapping, but text may take time to display.
- Swap: it’s actually FOUT. The first fallback will be used before the web font is available. The text can be read immediately, but the font exchange effect may not be harmonious. Font Style Matcher can be used to define fallbacks of a similar size.
- The compromise between fallback:FOIT and FOUT. The text is not visible for a short period of time (usually 100ms), then use the first fallback until the web font is available.
- Optional: similar to fallback, except that no font swapping occurs. Web fonts are used only when they are available during the initial period. Your first page view may display fallback fonts, and subsequent views will use downloaded and cached web fonts.
uses swap, fallback, or optional to improve performance.
avoids CSS @ import
import at-rule to allow CSS files to be included in other files:
/* main.css */ @import url("reset.css"); @import url("grid.css"); @import url("widget.css");
, which seems to be an effective way to load smaller components and fonts. Unfortunately, every @ import is a render block, and each file must be loaded and parsed sequentially. Multiple
tags inHTML are more efficient, and you can load CSS files in parallel:
, that is, it makes more sense.
concatenated and minimized CSS
modern build tools, CSS preprocessors such as Sass, and WordPress plug-ins can combine all parts into one large CSS file. Then remove unnecessary white space, comments, and characters to minimize the file size. With HTTP/2 and later versions of
, there are fewer performance problems for multiple files, but a single file requires only one header for more efficient gzip compression and caching. A separate CSS file for
is useful only if you have one or more stylesheets that change frequently, perhaps several times a week. Even so, most static CSS code can still be merged into one file. For more tips, check out our tutorial on how to minimize CSS and JS. The
avoid Base64 Encoding
tool can encode an image into an base64 string, which you can use as antag for HTML and as a data URI:
.background { background-image: url('data:image/jpg;base64,ABC123...'); }
in CSS background, which reduces the number of HTTP requests but harms CSS performance:
- base64 strings can be 30% larger than their binary equivalent strings.
- browsers must decode strings before they can use images, and
- changing one image pixel invalidates the entire CSS file.
only considers Base64 encoding if you are using very small, infrequently changed images where the resulting string is not longer than URL.
that is, you can use UTF8 to encode reusable SVG icons, for example.
.svgbackground { background-image: url('data:image/svg+xml;utf8,'); }
remove CSS Hacks and IE Fallbacks
unless you are unlucky and have a lot of Internet Explorer users, you can remove conditional stylesheets and hackers from your CSS. In most cases, IE users will still see something, especially if you are using a "mobility first" design, which will display a simpler linear view by default. The result may not be good, and it won't be perfect pixels, but it's best to consider the accessibility of all users in your development budget. The
preload CSS file
tag provides an optional preload attribute to start downloading immediately rather than waiting for the real introduction in HTML:
My page
is particularly useful in WordPress and other CMS, where plug-ins can add style sheets at the bottom of the page.
's use of key inline CSS
analysis tools may suggest that you "inline key CSS" or "reduce render blocking stylesheets." This can improve performance by recognizing the basic style used by the elements above the fold (the style that is visible when the page loads)
- inlines the key CSS into the
- tag in
loads the remaining CSS asynchronously to avoid rendering blocking. This can be achieved by loading stylesheets in the "print" style that the browser gives lower priority. After the page is loaded, JavaScript switches it to "all" media style (
- ensures that JavaScript is not available when CSS works):
tools such as critical and criticalCSS can help extract the styles of elements in the view.
/* critical styles */ body { font-family: sans-serif; color: #111; }
technology significantly improves performance and audit scores. Sites or applications with a consistent interface should be easier to implement, but they may be harder to implement elsewhere:
build tools are essential for all sites except the simplest. The "fold" on each device of the
- is different.
- sites can have a variety of layouts and require different key CSS.
- 's key CSS tools can fight against specific frameworks, HTML-generated clients, and dynamic content.
- is a technique that mainly facilitates the loading of the first page. CSS is cached for subsequent pages, so additional inline styles will increase the weight of the page.
- Rendering
individual connections and shrinks using media queries will benefit most sites, but sites that require a large number of larger screen styles can split CSS files and load using media queries:
this example assumes a move-first approach. The mobile device loads core.css, but may not need to download or parse the rest of the stylesheet.
uses progressive rendering
progressive rendering is a technique for defining separate stylesheets for individual pages or components. It can benefit very large sites where a single page is made up of a wide range of components.
loads each CSS file immediately before referencing components in HTML:
works well in most browsers. Safari displays a blank page until all CSS is loaded, but it should not be significantly worse than a single large stylesheet.
...
's adoption of the Web component also encourages the use of range styles that are loaded when rendering custom elements.
optimizes CSS performance
CSS technology and properties put different pressures on browsers, CPU, memory, bandwidth, and other resources. The following tips can help you avoid unnecessary processing and slow performance.
uses modern layout technology (Grid and Flexbox)
based on floating layout is difficult to create, uses a large number of properties, requires continuous adjustment of margins and padding, must be managed by media queries, and requires a lot of browser processing. They have been the only viable layout for many years, but they are no longer necessary. Use any of the following options:
CSS Flexbox is used for one-dimensional layout, and you can wrap to the next line. It is an ideal choice for menus, image libraries, cards, etc.
- CSS Grid is used for 2D layouts with explicit rows and columns. It is very suitable for page layout.
- is both easier to develop, uses less code, renders faster, and adapts to any screen size without media queries.
very old browsers do not recognize modern flexbox and grid attributes, so each element becomes a block. Display them in a simple mobile linear layout: there is no need to use floating-point-based fallback to simulate the design.
replaces the image
with CSS gradients and effects. If possible, select the CSS code instead of the image. Experiment with gradients, boundaries, radii, shadows, filters, blending modes, masks, clipping, and pseudo-element effects to reuse or replace existing images.
CSS effects use less bandwidth, are easier to modify, and can usually be animated.
avoids overusing the high-cost attribute
you may have concise declarative code, but some CSS require more processing than others. The following attributes trigger painting calculations, which can be costly when overused:
uses CSS transitions and animated
position: fixed
border-radius
box-shadow
text-shadow
opacity
transform
filter
backdrop-filter
background-blend-mode
CSS transitions whenever possible, and animation is always smoother than the effects supported by JavaScript, which modifies similar attributes. They are not handled in very old browsers, but this is best because these browsers may run on poor-performing devices.
however, please avoid too much animation. These effects should enhance the user experience without adversely affecting performance or causing carsickness. Check prefers-reduced-motion media queries and disable animation if necessary.
avoids animation attributes that trigger relayout
changing the size (width, height, fill, border) or position (top, bottom, left, right, margin) of an element may cause the entire page to be relaid out at each animation frame. The most effective properties to animate are:
: blur, contrast, Shadows, and other effects
opacity
-
filter
: translate (move), Zoom or rotate Graph elements -
transform
browser can use hardware-accelerated GPU to render these effects in its own layers, thus affecting only the compositing phase. If
must animate other attributes, you can improve performance by using position:absolute to remove elements from the page flow.
Note complex selectors
browsers will quickly parse the most complex CSS selectors, but simplifying them will reduce file size and improve performance. Complex selectors are usually generated when deeply nested structures are created in CSS preprocessors such as Sass.
indicates which elements will change the
CSS will-change attribute allows you to warn you about how the element will be changed or animated so that browsers can optimize ahead of time:
can define any number of comma-separated values, but this attribute can only be used as a last resort to solve known performance problems. You should not apply it to too many elements and make sure it is given enough time to initialize.
.myelement { will-change: transform, opacity; }
considers that CSS Containment
Containment is a new CSS feature that allows you to identify isolated subtrees of a page, thereby improving performance. Browsers can optimize processing by rendering (or not rendering) specific blocks of DOM content. The
contain attribute accepts one or more of the following values in a space-delimited list:
: no Containment
-
none
applied: the layout of the element is isolated from the rest of the page-its content does not affect other elements -
layout
: the child elements of the entity are not displayed outside their boundaries -
paint
: the size of the element can be determined without checking the child elements-the dimension is independent of the content -
size
is also mentioned Two special values are provided:
: apply all containment rules (except no rules)
-
strict
: apply layout and draw -
content
important: a page has a list of
containing the application
contain: strict;
Apply if you change the contents of any child item
, the browser will not recalculate the size or position of that item, other items in the list, or any other element on the page.
most modern browsers support CSS Containment. Containment is not supported in Safari or older applications, but Containment can be safely used in these applications because browsers will ignore this attribute.
Responding to the "Save-Data" header
Save Data is an HTTP request header that indicates that the user has requested reduced data. In some browsers, it may be marked as "Lite" or "Turbo" mode. When
is enabled, each browser request sends a
header:Save-Data
when a Save-Data is detected, the server can respond accordingly. In the case of CSS, it can send a simple mobile linear layout, use OS fonts, switch to block colors, or load low-resolution image backgrounds.
GET /main.css HTTP/1.0 Host: site.com Save-Data: on
Note: the server should return the following header when modifying the request to ensure that the minimum content is not cached and reused when the user turns off Lite/Turbo mode: this header can also be detected by the
client JavaScript. When "Save-Data" is not enabled, the following code adds the bestUX class to the
Vary: Accept-Encoding, Save-Data
element:, the stylesheet can then respond accordingly without any server action: the
if ('connection' in navigator && !navigator.connection.saveData) { document.documentElement.classList.add('bestUX'); }
prefers-reduced-data media query provides an alternative CSS-only option, although at the time of this writing, no browser supports this option: the
/* no hero image by default */ header { background-color: #abc; background-image: none; } /* hero image when no Save-Data */ .bestUX header { background-image: url("hero.jpg"); }
summary
/* no hero image by default */ header { background-color: #abc; background-image: none; } /* hero image when no Save-Data */ @media (prefers-reduced-data: no-preference) { header { background-image: url("hero.jpg"); } }
has many options for optimizing CSS performance, but for new projects Please consider the following approach:
Use the mobility-first approach: first write the simplest mobile layout, and then add enhancements as the screen space and browser feature set increases.
- Split the CSS into separate files with identifiable responsibilities: the CSS preprocessor or CMS plug-in can merge the CSS parts into a single file.
- Add a build step: provides tools to automatically delete code, identify problems, connect, zoom out, reduce image size, and so on. Automation makes life easier, and you are less likely to forget the optimization steps.
- Record stylesheets: style guides with documented examples will make your code easier to obtain and maintain. You will be able to identify and delete the old CSS without paying any price.
- finally, learn CSS! The more you know, the less code you need to write, and the faster your Web application will become. No matter which platform and framework you use, it will make you a better developer.