search
HomeWeb Front-endCSS TutorialWhat is Graceful Degradation in CSS?

What is Graceful Degradation in CSS?

什么是优雅降级?

If you are an experienced web developer, you may have heard the graceful degradation word before. Before we learn about the graceful degradation in web development, let’s break down the word. The meaning of graceful is elegant or beautiful, and degradation is breaking or falling down. So, the overall meaning of the graceful degradation word is that it makes the feature elegant while it breaks.

Developers use the graceful degradation term in web development. It provides various techniques so that any website or application can work correctly in less capable browsers.

For example, modern browsers support advanced CSS and JavaScript features but are not supported by older browsers or older versions of the browsers. In such cases, developers need to ensure that users can access the website in older browsers with a good experience.

Different Techniques for the Graceful Degradation

在上面的部分中,我们了解了什么是优雅降级以及为什么开发人员应该确保它。现在,我们将通过示例学习不同的优雅降级技术。

Progressive Enhancement

在这种技术中,开发人员需要将代码分解成不同的包,并逐个加载每个包。因此,成功加载网页的HTML,然后加载每个浏览器都支持的普通CSS。

At last, load the advanced CSS features, and if the browser supports that feature, it will be applied to the HTML element. Otherwise, the HTML content of the web page remains accessible. So, in this way, even if a modern browser doesn’t support some features, it can still render the HTML content properly.

Feature Detection

在这种方法中,我们检查浏览器是否支持特定的JavaScript功能。如果是,网站允许用户使用该功能来相应地样式化HTML内容。否则,我们可以显示一些错误消息或对HTML内容应用不同的样式。

让我们通过下面的示例来理解。

Example

在下面的示例中,我们创建了一个div元素并给了它一个'id'为'element'。同时,我们在CSS中定义了'class'为'container'的类,并将一些CSS属性包含在其中。

在JavaScript中,每当浏览器加载时,我们通过id访问div元素,并检查div元素是否包含'classList'属性。如果是,我们将'container'类名添加到数组中。否则,我们只是将类名连接到类名字符串中。

所以,我们在这里检测了div元素是否支持classList类,根据这一点,我们使用了不同的技术来向div元素添加类名。

<html>
<head>
   <style>
      .container {
         width: 300px;
         height: 300px;
         background-color: red;
         border: 3px solid green;
         border-radius: 12px;
      }
      #output {
         font-size: 20px;
         font-weight: bold;
         color: blue;
      }
   </style>
</head>
<body>
   <h3 id="Using-the-i-feature-detection-technique-i-for-the-graceful-degradation-in-the-web-development">Using the <i> feature detection technique </i> for the graceful degradation in the web development</h3>
   <div id = "element"> </div>
   <div id = "output"> </div>
   <script>
      var myDiv = document.getElementById('element');
      let output = document.getElementById('output');
      if ('classList' in myDiv) {
         myDiv.classList.add('container');
         output.innerHTML = 'classList is supported';
      } else {
         myDiv.className += ' container';
         output.innerHTML = 'classList is not supported';
      }
   </script>
</body>
</html>

添加备选选项

优雅降级的另一种技术是添加备用选项。在这种技术中,如果浏览器不支持任何CSS,我们使用另一种CSS来完美显示HTML内容在Web浏览器中。

使用下面的示例,让我们了解如何将回退选项添加到网页中。

示例(为CSS渐变添加回退选项)

In the example below, we have created the card div element and used the line-gradient() CSS function to set the background gradient. Also, we have written the fallback CSS if the browser doesn’t support the linear-gradient() CSS function.

In the output, users can observe that either it shows the gradient or background color.

<html>
<head>
   <style>
      .card {
         width: 400px;
         height: auto;
         font-size: 2rem;
         background-color: orange;
         background-image: linear-gradient(to right, #14f71f, #d46a06);
         color: white;
         text-align: center;
      }
      /* Fallback styles */
      @media screen and (-ms-high-contrast: active),
      (-ms-high-contrast: none) {
         .card {
            background-image: none;
            background-color: orange;
         }
      }
   </style>
</head>
<body>
   <h3 id="Using-the-i-fallback-options-for-the-gradient-i-for-the-graceful-degradation-in-the-web-development">Using the <i> fallback options for the gradient </i> for the graceful degradation in the web development</h3>
   <div class = "card"> This is a card element </div>
</body>
</html>

Example (Adding the fallback option for CSS animation)

In the example below, we added the CSS animation's fallback option. Here, we have created three div elements and added the ‘bounce’ animation in all elements. The ‘bounce’ animation moves the div upside from its position and sets it back to its initial position.

In JavaScript, we create a new div element and check if its style contains the ‘animation’ property. If yes, the animation will apply automatically. Otherwise, we need to add a ‘no_animation’ class to every div element using JavaScript, which sets ‘animation: none’.

<html>
<head>
   <style>
      .square{
         background-color: blue;
         color: white;
         width: 100px;
         font-size: 1.5rem;
         padding: 20px;
         margin-bottom: 20px;
         position: relative;
         animation: bounce 2s ease-in-out infinite;
         animation-direction: alternate;
         animation-delay: 0.1s;
         animation-fill-mode: both;
         animation-play-state: running;
      }
      @keyframes bounce {
         0% {transform: translateY(0);}
         100% {transform: translateY(-30px);}
      }
      /* Fallback styles */
      .no-animation .square{
         top: 0;
         animation: none;
      }
   </style>
</head>
<body>
   <h3 id="Using-the-i-fallback-options-for-the-animation-i-for-the-graceful-degradation-in-the-web-development">Using the <i> fallback options for the animation </i> for the graceful degradation in the web development</h3>
   <div class = "square"> div1 </div>
   <div class = "square"> div2 </div>
   <div class = "square"> div3 </div>
   <script>
      window.onload = function () {
         var squares = document.querySelectorAll('.square');
         if (!('animation' in document.createElement('div').style)) {
            for (var i = 0; i < squares.length; i++) {
               squares[i].classList.add('no-animation');
            }
         }
      };
   </script>
</body>
</html>

Users learned about various graceful degradation techniques in this tutorial. All techniques make the HTML content of web pages attractive, even if browsers are not supporting some features.

优雅降级的最佳技术是设置备选方案。开发人员应仅使用标准的HTML和CSS属性,以确保在旧版浏览器中实现优雅降级。

However, graceful degradation is costly to maintain as developers require to add fallback options for multiple features. Still, it gives a smooth web experience to visitors visiting from any web browser.

The above is the detailed content of What is Graceful Degradation in CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Using Pages CMS for Static Site Content ManagementUsing Pages CMS for Static Site Content ManagementMay 13, 2025 am 09:24 AM

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool