在前端领域有一定工作年限,并且接触过前端蛮荒时代(前后端不分离,jQuery,纯HTML+CSS+JS)开发的小伙伴,应该对CSS样式非常熟悉。
早在那个年代,前端在编写CSS代码时,已经听说业界对样式属性书写顺序的标准规范和要求。
时至今日,刚做前端的朋友们,在开发CSS时,大多对样式属性书写顺序没有什么概念和认识。而做过几年开发的“老”前端们可能会说“样式属性应该按照一定顺序书写!”。
那么问题来了,现在,遵照样式属性书写顺序开发对渲染性能到底有没有收益?
这里,我也有疑问,所以简单做一个实验,看看【顺序】和【无序】对渲染性能(主要是时间)的影响到底如何:
(并不保证实验代码和实验手段对结果有误导,如有错误,望大家见谅)
测试代码:
/* CSS */ /* 按照顺序规范 */ .orderly { position: absolute; top: 0; z-index: 3; box-sizing: border-box; display: flex; align-items: center; justify-content: center; flex: 1; width: 400px; min-height: 200px; padding: 20px; margin: 8px 10px; color: #444; font-weight: 600; font-size: 20px; line-height: 20px; background-color: #fc1; border: 1px solid rgba(32, 91, 8, .4); border-radius: 4px; box-shadow: 0 0 4px 8px royalblue; user-select: none; transition: all .3s ease-in-out; } .orderly .child { text-align: center; cursor: pointer; opacity: .9; transform: scale(1.2); }
/* 无序 */ .disrupt { line-height: 20px; z-index: 3; display: flex; align-items: center; width: 400px; position: absolute; border: 1px solid rgba(32, 91, 8, .4); border-radius: 4px; box-shadow: 0 0 4px 8px royalblue; top: 0; min-height: 200px; padding: 20px; justify-content: center; flex: 1; margin: 8px 10px; color: #444; box-sizing: border-box; font-weight: 600; transition: all .3s ease-in-out; font-size: 20px; background-color: #fc1; user-select: none; } .disrupt .child { opacity: .9; cursor: pointer; transform: scale(1.2); text-align: center; }
<body> <div id="app"></div> <script> const tmp = ` <div class="disrupt"> <div class="child"> Test disrupt </div> </div> `; let htmlStr = ''; for (let i = 0; i < 2000; i++) { htmlStr += tmp; } document.getElementById('app').innerHTML = htmlStr; </script> </div>
测试工具:
Chorme浏览器(版本:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36')
控制台 -【Performance Insights】
测试结果:
1. 有序
2. 乱序
综上:样式属性是否按照业界顺序规范书写对渲染性能的影响很小(基于现代浏览器),数据规模较大时,多数情况下,按序书写 对性能有较微弱提升。
虽然,是否按序书写对性能的影响几乎可以忽略,但还是推荐大家尽量按顺序规范书写:
推荐分类顺序: 1. Positioning 2. Box Model 3. Typography 4. Visual 5. Animation 6. Misc
示例:
.orderly { /* Positioning */ position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 10; /* Box Model */ display: block; float: right; width: 100px; height: 100px; margin: 10px; padding: 10px; /* Typography */ color: #888; font: normal 16px Helvetica, sans-serif; line-height: 1.3; text-align: center; /* Visual */ background-color: #eee; border: 1px solid #888; border-radius: 4px; opacity: 1; /* Animation */ transition: all 1s; /* Misc */ user-select: none; }
标签:box,顺序,center,渲染,书写,border,2022.11,CSS From: https://www.cnblogs.com/fanqshun/p/16886656.html