html - 将类名分配给 <img> 标签而不是将其写入 css 文件?

标签 html css

我很想知道,为 <img> 分配一个类名是否更好?标记在 html 文件中而不是直接写到 css 文件中?

<div class="column">
   <img class="custom-style" alt="" />
   <img class="custom-style" alt="" />
   <img class="custom-style" alt="" />
</div>

代替

.column img{/*styling for image here*/}

我需要知道它们在网络性能方面是否存在差异?

更新:

对不起,假设问题是多个<img> .column div 内的标签并且所有图像都使用相同的样式。

最佳答案

简短的回答是直接向您想要设置样式的元素添加一个类确实是定位该元素并为其设置样式的最有效方式。但是,在现实世界的场景中,它是如此微不足道,根本不是一个值得担心的问题。

引用 Steve Ouders(CSS 优化专家)http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/ :

Based on tests I have the following hypothesis: For most web sites, the possible performance gains from optimizing CSS selectors will be small, and are not worth the costs.

代码的可维护性在现实世界场景中更为重要。 由于这里的基础主题是前端性能;快速页面呈现的真正性能助推器位于:

  • 减少 HTTP 请求
  • 使用 CDN
  • 添加一个 Expires header
  • Gzip 组件
  • 将样式表放在顶部
  • 将脚本放在底部
  • 避免使用 CSS 表达式
  • 使 JS 和 CSS 成为外部
  • 减少 DNS 查询
  • 压缩 JS
  • 避免重定向
  • 删除重复的脚本
  • 配置 ETag
  • 使 AJAX 可缓存

来源:http://stevesouders.com/docs/web20expo-20090402.ppt

所以只是为了确认,答案是肯定的,下面的例子确实更快,但要注意大局:

<div class="column">
   <img class="custom-style" alt="appropriate alt text" />
</div>

关于html - 将类名分配给 <img> 标签而不是将其写入 css 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16228845/

相关文章:

javascript - 来自 JS Fiddle 的 JS 在浏览器测试中不起作用

javascript - 如何创建出现在可见元素下的弹出窗口?

jquery - 无限滚动 jQuery 插件 : how to fix loading graphic from "animating" left to center of page?

css - 在 cdk-virtual-scroll-viewport Angular 之外显示绝对元素

css - Bootstrap : cannot horizontally center content inside nested columns

css - 如何将要在屏幕上播放的视频缩放到移动设备

javascript - 单击同一个 div 中的 li 元素? JQuery/JavaScript

javascript - drawImage - 调整大小并保持比例

jquery - 设置宽度的中心 "ul"元素

html - IE8 按钮的 CSS "initial"值