You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么CSS伪类:not(:fullscreen)对部分元素的样式设置不生效?

问题根本原因

你遇到的样式失效问题是后代选择器的匹配逻辑不符合预期导致的,和:fullscreen伪类本身的实现无关:

  • 你写的:not(:fullscreen) body是后代选择器,匹配规则是「所有祖先元素处于非全屏状态的body元素」。由于body的父元素只有html根节点,非全屏状态下html不属于:fullscreen状态,因此规则匹配成功,样式生效;全屏状态下html被设为全屏元素,不存在符合:not(:fullscreen)的祖先元素,规则失效,刚好符合你的预期。
  • 你写的:not(:fullscreen) p同样是后代选择器,匹配规则是「所有祖先元素处于非全屏状态的p元素」。你触发全屏时是将html根节点设为全屏元素,此时页面内所有元素的唯一顶层祖先都是处于:fullscreen状态的html,没有符合:not(:fullscreen)的祖先节点,因此这个规则永远无法匹配到p元素,样式自然不生效。
正确实现方案

如果你需要根据整个页面是否处于全屏状态来设置元素的非全屏样式,直接基于根节点的全屏状态写后代选择器即可:

/* 根节点非全屏时的body样式 */
:root:not(:fullscreen) body {
  background-color: gold;
}

/* 根节点非全屏时的p样式 */
:root:not(:fullscreen) p {
  background-color: orange;
}

如果你需要匹配自身处于非全屏状态的特定元素(比如单独设置某个可独立全屏的div的非全屏样式),直接把伪类绑定到对应元素的选择器上即可:

p:not(:fullscreen) {
  background-color: orange;
}
修正后完整可运行代码
:fullscreen button {
  background-color: green;
}

:root:not(:fullscreen) body {
  background-color: gold;
}

:root:not(:fullscreen) p {
  background-color: orange;
}

div {
  background-color: blue;
}

:fullscreen div {
  background-color: white;
}
<button onclick="if (document.fullscreenElement) {(document.exitFullscreen || document.webkitExitFullscreen).call(document)}
   else {var elem = document.documentElement; (elem.requestFullscreen || elem.webkitRequestFullscreen).call(elem)}">toggle fullscreen</button>

<p>
  Negating fullscreen works for body but not for div. In fullscreen mode body turns white, but div stays orange.
</p>

<div>
  A work around.
</div>

注:直接在当前页面运行代码片段会抛出Fullscreen request denied错误,属于页面安全策略限制,部署到正常站点即可正常运行。

内容的提问来源于stack exchange,提问作者Friedrich -- Слава Україні

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:27:00