Giter VIP home page Giter VIP logo

Comments (3)

lxhguard avatar lxhguard commented on May 27, 2024 1

浏览器解析 CSS rule 是从右到左。
CSSOM本质是一张映射表,可通过document.styleSheets只读样式表集合。若理解为一棵树,则从右向左的遍历方式,等价于从叶子节点开始向上寻找,到目标为止,避免了无效遍历。
先解析.class2,再解析.class1,再解析div。

from fe-interview.

suukii avatar suukii commented on May 27, 2024 1

为什么浏览器是从右往左解析 CSS 规则的?

div > .class1  > .class2 {}

首先浏览器在计算一个节点的样式时,它是拿着这个节点去跟样式表中所有的 selector 规则进行比较,找到 match 的规则,应用样式。也就是说,样式表中的大部分规则可能都不是浏览器要找的,所以最好尽早把它们排除掉。

如果浏览器从右往左解析 CSS 规则,可能碰到的第一个选择器 .class2 就跟当前的节点不匹配,那么这个规则就可以放弃了。如果匹配,那就继续往左匹配。

如果浏览器从左往右解析,首先得先遍历 DOM 找到匹配 div 选择器的节点,再继续找到它们有没有子节点匹配 .class1 选择器,...,有可能匹配到最右边时,最后会发现这条规则不是我们想要的,这个过程太耗时间了。

from fe-interview.

stale avatar stale commented on May 27, 2024

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

from fe-interview.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.