Home > Technology peripherals > It Industry > 20 Tips for Optimizing CSS Performance

20 Tips for Optimizing CSS Performance

Lisa Kudrow
Release: 2025-02-16 08:42:09
Original
513 people have browsed it

20 Tips for Optimizing CSS Performance

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

  • Use browser tools and online analyzers: Use online platforms such as browser developer tools and Google PageSpeed ​​Insights to identify and solve the problem of slow CSS loading.
  • Preferred to major improvements: Enable HTTP/2, use GZIP compression, and use CDN to efficiently handle larger resources, significantly improving loading speed.
  • Use CSS effects instead of pictures: Use CSS instead of pictures to achieve visual effects, such as shadows and gradients, to reduce download size and improve maintainability.
  • Minimize font overhead: Limit the use of custom fonts, select only the necessary styles and thicknesses, and consider using system fonts to reduce loading time.
  • Implement efficient CSS practices: Use modern layout methods such as Flexbox and Grid to minimize CSS code and avoid costly properties to simplify performance and maintenance.
  1. Learn to use analysis tools

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:

  • Pingdom website speed test
  • GTmetrix
  • Google PageSpeed ​​Insights
  • WebPageTest
  1. Major progress has been made first

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:

  • Enable HTTP/2 and GZIP compression on the server
  • Use content delivery network (CDN) to increase the number of simultaneous HTTP connections and copy files to other locations around the world
  • Delete unused files

Images are usually the reason for the largest page size, but many websites fail to optimize effectively:

  1. Resize the bitmap image. Multi-megapixel images taken by entry-level smartphones cannot be fully displayed on the largest HD screen. Few websites require images with a width of more than 1600 pixels.
  2. Make sure to use the appropriate image format. Generally, JPG is best for photos, SVG is best for vector images, and PNG is best for all other images. You can experiment to find the best type.
  3. Use the Image Tool to reduce file size by removing metadata and increasing compression factors.

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.

  1. Use CSS effects instead of pictures

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.

  1. Delete unnecessary fonts

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:

  1. Use only the required fonts.

  2. Load only the required thickness and styles - for example, Roman, 400 thickness, no italics.

  3. 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.

  4. 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.

  5. 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!

  6. 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");
Copy after login
Copy after login
Copy after login
Copy after login

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">
Copy after login
Copy after login
Copy after login
In other words, there may be better choices...

  1. Connection and compression
Most build tools allow you to combine all parts into a large CSS file that has removed unnecessary spaces, comments, and characters. When using HTTP/2, which pipes and multiplexes the requests, the necessity of the connection is reduced. In some cases, a separate file may be more beneficial if you have smaller and frequently changed CSS resources. However, most websites may benefit from sending a single file that is immediately cached by the browser. With GZIP enabled, compression may not bring considerable advantages. That is, there are no real shortcomings. Finally, you can consider a build process that sorts properties consistently in the declaration. GZIP can maximize compression when using common strings throughout the file.

  1. Using modern layout technology
For many years, it was necessary to use CSS float to layout pages. This technique is a technique. It requires a lot of code and margin/fill tweaks to ensure the layout is effective. Even so, unless a media query is added, the float breaks at a smaller screen size. Modern alternatives:

    CSS Flexbox is used for one-dimensional layouts, which can wrap lines to the next line based on the width of each block. Flexbox is very suitable for menus, photo galleries, cards, and more.
  • CSS Grid is used for two-dimensional layouts with explicit rows and columns. Grid is perfect for page layout.
Both options are easier to develop, use less code, can adapt to any screen size, and are faster than floating rendering, as the browser can locally determine the best layout.

  1. Reduce CSS code
The most reliable and fastest code is the code you never need to write! The smaller the stylesheet, the faster the download and parse. All developers start with good intentions, but CSS may swell over time as the number of features increases. It's easier to keep old, unnecessary code than to remove it and risk breaking something. Some suggestions to consider:

  • Beware of large CSS frameworks. It is unlikely that you use most of the styles, so just add modules if needed.
  • Organize CSS into smaller documents (parts) with clear responsibilities. It is easier to remove the carousel widget if CSS is clearly defined in widgets/_carousel.css.
  • Consider naming methods such as BEM to help develop standalone components.
  • Avoid deep nested Sass/preprocessor declarations. Extended code may unexpectedly get bigger.
  • Avoid using !important to overwrite cascades.
  • Avoid using inline styles in HTML.

Tools such as UnCSS can help remove redundant code by analyzing your HTML, but be careful about the CSS state caused by JavaScript interactions.

  1. Adhere to cascading!

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.

  1. Simplified selector

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");
Copy after login
Copy after login
Copy after login
Copy after login

Similarly, be aware of deep nesting in preprocessors such as Sass, where complex selectors may be created inadvertently.

  1. Beware of costly attributes

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">
Copy after login
Copy after login
Copy after login

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
  1. Using CSS animation

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.

  1. Avoid costly attributes for animation

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.

  1. Indicates which elements will be animated
The

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");
Copy after login
Copy after login
Copy after login
Copy after login

Any number of comma-separated properties can be defined. But:

  • Use will-change as a last resort to solve performance problems
  • Don't apply it to too many elements
  • Give it enough time to work: that is, don't start animation immediately.
  1. Using SVG images

Scalable 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">
Copy after login
Copy after login
Copy after login

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"]
Copy after login
  1. Set SVG style with CSS

More typical, SVG is embedded directly into HTML documents:

*, ::before, ::after {
  box-shadow: 5px 5px 5px rgba(0,0,0,0.5);
}
Copy after login

This will add the SVG node directly to the DOM. Therefore, all SVG style properties can be applied using CSS:

.myelement {
  will-change: transform;
}
Copy after login

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.

  1. Avoid using Base64 bitmap images

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>
Copy after login

Unfortunately:

  • base64 encoding is usually 30% larger than its binary equivalent
  • The browser must parse the string to use it
  • Changing the image will invalidate the entire (cached) CSS file

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.

  1. Consider key CSS

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:

  1. Extract the style used to render elements above the screen. Tools like criticalCSS can help.
  2. Add these styles to the <head> element in HTML<style>.
  3. Use JavaScript to load the main CSS file asynchronously (probably after the page is loaded).

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:

  • The "collapse" is not recognized and it changes on each device.
  • Most websites have different page layouts. Each page may require a different critical CSS, so building tools become crucial.
  • Dynamic, JavaScript-driven events may cause changes above screens that are not recognized by critical CSS tools.
  • This technology is mainly conducive to the user's first page loading. CSS is cached to subsequent pages, so the extra inline style increases the page weight.
  • That is, Google will like your website and push it to the No. 1 ranking for each search term.
(The SEO "expert" can quote me. Everyone else will know that this is nonsense.)

    Consider progressive rendering
  1. Progressive rendering is a technique that instead of using a single site-wide CSS file, it defines separate stylesheets for individual components. Each stylesheet is loaded immediately before the component is referenced in HTML:

Each
/* main.css */
@import url("base.css");
@import url("layout.css");
@import url("carousel.css");
Copy after login
Copy after login
Copy after login
Copy after login
will still block rendering, but it will be shorter because the files are smaller. Pages can be used faster because each component is rendered in order; the top of the page can be viewed while the rest is loaded. This technology is suitable for Firefox, Edge and IE. Chrome and Safari experience it by loading all CSS files and showing a white screen when this happens - but it's no worse than loading each file in

. Progressive rendering may benefit large websites where individual pages are built with choices of different components. <link>

  1. Learn to love CSS

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

What are the key factors affecting 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.

How to reduce the size of CSS files to improve performance?

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.

How does a complex CSS selector affect performance?

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.

What is the impact of CSS animation and conversion on 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.

How to optimize CSS for mobile devices?

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.

What tools can I use to measure CSS performance?

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.

How does CSS affect SEO?

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.

How to use CSS preprocessor to improve performance?

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.

What is a critical CSS and how does it improve performance?

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.

How to optimize CSS delivery?

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template