在html元素或body元素上是否应设置全局CSS样式?

有时候,我看到人们将全局CSS样式应用到html,有时我看到它们将它们应用到body,同时使用raw css和javascript.

两者之间有什么区别吗?制作全球css风格的标准是什么?我们应该知道什么吗?

解决方法

我假设这里的“全局页面样式”是指字体,颜色和背景等.

就个人而言,我应用全局页面样式,大部分应用于主体和简单元素选择器(p,h1,h2,h3 …,input,img等).这些元素与HTML页面内容用户呈现更密切相关.

我的理由很简单:将表示属性bgcolor,background,text,topmargin,leftmargin等赋予body元素,而不是html元素.这些属性现在转换为their respective CSS rules with extremely low precedence in the cascade

The UA may choose to honor presentational attributes in an HTML source document. If so,these attributes are translated to the corresponding CSS rules with specificity equal to 0,and are treated as if they were inserted at the start of the author style sheet.

我知道的大多数(如果不是全部)实现将会根据它们的HTML等价物将它们转换为身体上的CSS规则.链接,alink和vlink等其他内容将分别成为:link,a:active和a:visited规则.

当然,应该注意的是,CSS本身本身并没有真正具有任何语义,因为它本身就是一种与HTML文档的内容结构完全分离的样式语言.尽管introduction to CSS2.1涵盖了HTML文档样式的基础知识,但请注意,该部分称自身为非规范性(或信息性);这意味着它不会为CSS实现者设置任何艰难和快速的规则.相反,它只是为读者提供信息.

也就是说,某些样式可能会应用于html来修改视口行为.例如,隐藏页面滚动条使用:

html {
    overflow: hidden;
}

您还可以对html和body应用规则,以获得有趣的效果;有关详细信息和示例,请参阅以下问题:

> What’s the difference in applying CSS to html,body,and *?
> Applying a background to <html> and/or <body>

请注意,html不是视口;该视口建立了html所在的初始包含块.该初始包含块不能用CSS定位,因为在HTML中,根元素是html.

还要注意的是,从技术上讲,在认情况下继承html和body的属性(如font-family和color)之间没有区别.

最后但并非最不重要的是,这是一个非常出色的article,详细介绍了CSS和HTML之间的差异.总而言之(引自第一部分):

  • The html and body elements are distinct block-level entities,in a
    parent/child relationship.
  • The html element’s height and width are controlled by the browser window.
  • It is the html element which has (by default) overflow:auto,causing
    scrollbars to appear when needed.
  • The body element is (by default) position:static,which means that
    positioned children of it are
    positioned relative to the html
    element’s coordinate system.
  • In almost all modern browsers,the built-in offset from the edge of the
    page is applied through a margin on
    the body element,not padding on the
    html element.

作为根元素,html与浏览器视口比body更紧密相关(这就是为什么它表示html已经溢出:auto for scrollbars).但是请注意,滚动条不一定由html元素本身生成.认情况下,它是生成这些滚动条的视口;根据您设置的值,在body,html和viewport之间简单地传递(或传播)溢出值.所有这些的细节都在CSS2.1规范中介绍,其中says

UAs must apply the ‘overflow’ property set on the root element to the viewport. When the root element is an HTML “HTML” element or an XHTML “html” element,and that element has an HTML “BODY” element or an XHTML “body” element as a child,user agents must instead apply the ‘overflow’ property from the first such child element to the viewport,if the value on the root element is ‘visible’. The ‘visible’ value when used for the viewport must be interpreted as ‘auto’. The element from which the value is propagated must have a used value for ‘overflow’ of ‘visible’.

最后一个项目符号可能有其根源在上述的主体元素的topmargin和leftmargin属性.

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些