css - 为什么在使用 flex 时样式标签也得到 "style"?

标签 css html flexbox

当我用这段代码创建一个 html 页面时

     <style> 
          * { 
               display: flex; 
               justify-content:center; 
               align-items:center; 
          } 
     </style>

我得到了这个输出

enter image description here

这是为什么?

[我不是在寻找解决方案,我是在询问为什么我仅在使用“display:flex”时(而不是在使用其他 css 属性时)得到此输出的原因]

最佳答案

假设默认情况下不会显示 head 和 style 当您仅使用此代码创建 html 页面时

<style>
    * { 
       display: flex;
       justify-content:center;
       align-items:center;
    }
</style>

浏览器会生成如下DOM结构

enter image description here

由于您已经为所有元素定义了该样式(通过星号选择器),因此该规则也适用于 headstyle 元素,因此它们与你定义的风格

为了防止这种行为,如果这是您的目标,您可以将该样式仅应用于 body 及其后代,例如

<style>
    body, body * { 
       display: flex;
       justify-content:center;
       align-items:center;
    }
</style>

或者简单地指向除head

之外的所有元素
<style>
    :not(head) { 
       display: flex;
       justify-content:center;
       align-items:center;
    }
</style>

关于css - 为什么在使用 flex 时样式标签也得到 "style"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31674324/

相关文章:

javascript - 几个div,如何查找图像并删除父div

css - inline-block 与 H1 和 Image 的具体展示

html - 带有 flexbox 的字体图标作为页面背景

html - 我如何设置下一个 img 标签的 div 高度?

html - 悬停后链接整个 div 而不仅仅是图标

html - 在另一个矩形内制作一个矩形并定位元素

css - 在段落末尾添加阅读更多链接?

html - 垂直对齐不适用于 flex 元素

html - 相对于父容器而不是浏览器将固定位置的 html 元素居中

html - 将 CSS 标注添加到工具提示