首页 > 解决方案 > :root, html, * 选择器。有什么不同吗?

问题描述

这三个 CSS 规则之间有什么区别吗?

* {
  font-size: 24px
}
:root {
  font-size: 24px
}
html {
  font-size: 24px
}

标签: css

解决方案


是,有一点不同。下面是一些结果不一样的例子

使用*

* {
  font-size: 24px
}

p {
  font-size:2em;
}
<div>
  <p>some text <span>here</span></p>
</div>

使用html(或:root

html {
  font-size: 24px
}

p {
  font-size:2em;
}
<div>
  <p>some text <span>here</span></p>
</div>

应用于font-size所有元素不同于将 应用于font-sizehtml 元素并让所有元素继承该值。

在第一个示例中,span 将具有font-size等于,24px因为它是由 选择的*。在第二个示例中,span 将继承 的计算值,p因为没有选择器以它为目标。


之间html:root一场特异性战争,其中:root将是赢家:

html {
  font-size: 999px;
}

:root {
  font-size:24px;
}
<div>
  <p>some text <span>here</span></p>
</div>

:root {
  font-size:24px;
}

html {
  font-size: 999px;
}
<div>
  <p>some text <span>here</span></p>
</div>


推荐阅读