HTML5-和-CSS3-设计模式高级教程-全-

HTML5 和 CSS3 设计模式高级教程(全)

原文:Pro HTML5 and CSS3 Design Patterns

协议:CC BY-NC-SA 4.0

零、简介

这是一本用 CSS3 设计 HTML5 样式的解决方案书。它包含了 350 多种设计模式,您可以立即投入使用。每个设计模式都是模块化和可定制的,您可以组合模式来创建无限数量的设计。

每种设计模式都经过了全面的测试,并被证明可以在所有主流的浏览器中运行,包括 Chrome、Firefox、Internet Explorer、Opera 和 Safari。这本书的所有内容都是有用的和实用的。你不会浪费时间去读那些没用的东西!有了这本书,你将不再需要使用黑客、技巧、无止境的测试,以及在多个浏览器中不断的调整来获得工作。

使用设计模式就像将它复制粘贴到代码中并调整一些值一样简单。您将立即看到可以修改哪些值以及它们如何影响结果,这样您就可以创建您想要的精确样式和布局,而不用担心它是否有效。

这不仅仅是一本烹饪书。它系统地介绍了 CSS 的几个可用特性,并将这些特性与 HTML 结合起来创建可重用的模式。每种模式都有一个直观的名称,便于查找、记忆和讨论。可访问性和最佳实践被精心设计到每个设计模式、示例和源代码中。

你可以直接通读这本书,把它作为参考,用它来寻找解决方法。每个例子都包括一个截图和所有相关的 HTML 和 CSS 代码,所以你可以很容易地看到每个设计模式是如何工作的。每种设计模式的解释都包含在旁边,所以当您阅读它是如何工作的时候,您可以很容易地研究这个例子。

设计模式是按主题组织的,所有可用的 CSS 规则都像其他书一样在上下文中深入讨论。所有的设计模式都是可访问的,并遵循最佳实践,这使得这本书从头到尾都是值得一读的,也是您在设计和编码时随身携带的优秀参考资料。

这本书释放了你在网页设计和开发中的生产力和创造力。设计模式就像乐高积木——你可以用无数种方式组合它们来创造任何设计。它们就像工具箱中的工具,这本书为你提供了数百种工具,你可以快速可靠地解决问题。这本书向你展示了如何通过结合可预测的模式,创造出可预测的设计,而不是一蹴而就的解决方案。

观众

这本书是为那些对 CSS 和 HTML 有一些熟悉的人写的。它是为那些以前读过一本关于 CSS 和 HTML 的入门书籍的新手准备的。它是为曾经尝试过 CSS,但因为它似乎从来没有正确工作而放弃的设计者和开发者准备的。它是为那些想把他们的 CSS 技能提升到一个更高水平的专业人士准备的。它是为所有那些想快速创建设计而不是到处乱砍的人准备的,直到他们找到在所有浏览器上都可以工作的东西。

我们假设你知道编码 CSS 和 HTML 的基础知识。如果你只在 Dreamweaver 或 FrontPage 这样的 WYSIWYG 设计器中工作,并且从不看 HTML 或 CSS 代码,你可能会发现这本书里的代码让人应接不暇。

如果你喜欢通过例子学习,喜欢看代码如何工作,并且对 CSS 和 HTML 有一些熟悉,你会喜欢这本书。

一些设计模式使用 JavaScript。要完全理解它们,您需要理解 JavaScript 的基础知识,但是使用这些模式并不需要了解 JavaScript。最重要的是,您不需要了解任何关于 JavaScript 的知识来理解和使用剩余的 340 多种设计模式,因为它们与 JavaScript 无关!

创新

这本书包含几个创新的概念,术语和方法。这些都不是新的或激进的:该技术已经内置于主流浏览器中,概念隐含在 CSS 规范中,术语也是常用的。它们的创新之处在于我们如何定义和使用它们来展示 CSS 和 HTML 能做些什么。换句话说,它们是创新的,因为它们简化了 CSS 和 HTML 的学习、理解和使用。这些想法改变了你对 CSS 和 HTML 的看法,这让一切都变得不同。此外,书中的许多设计模式都是创新的,因为它们记录了属性和元素的组合,以解决前所未有的难题。

六个盒子模型

书中的一个创新是 CSS 有六个而不是一个盒子模型。CSS 官方有一个盒子模型,它定义了一组公共的属性和行为。单个盒子模型是一个非常有用的概念,但是它过于简单了。多年来,我们艰难地认识到盒子模型属性根据盒子的类型而不同地工作。

这是为什么这么多人纠结于 CSS 的一个原因。盒子模型看起来很简单,但是当一个人使用盒子模型属性时,比如width,它只在某些时候起作用,或者可能与预期的不同。例如,width属性设置块框的内部宽度,但是在表格框上它设置边框的外部宽度,而在内嵌框上它什么也不做。

我们没有将不同的行为视为一个非常复杂的盒子模型的例外,而是定义了六个简单的盒子模型,为每种类型的盒子指定行为。第四章介绍了六种盒子模型,即内联、内联块、块、表、绝对和浮点。因为您总是知道您正在使用这六个盒子模型中的哪一个,所以您总是知道每个盒子模型属性将如何表现。

此外,每个盒子模型都定义了自己的流动或定位方式。例如,行内框水平排列并换行。接线盒垂直流动。表格按列和行排列其单元格。浮动水平流动,在其他浮动下面换行,并把内嵌的框和表推开。绝对和固定框不流动;相反,它们被从流中移除,并相对于其最近的定位祖先进行定位。

方框模型范围

这本书的另一个创新是有三种方法可以确定盒子的尺寸:可以定尺寸、收缩或拉伸(见第五章)。每种类型的框都需要不同的特性和特性值组合来调整大小、收缩或拉伸。在第五章到第九章中的各种设计模式展示了这是如何做到的。这三个术语不是正式的 CSS 术语,但是它们隐含在 CSS 规范的公式中,以及提到“尺寸”、“收缩到适合”和“拉伸”的地方 1


1 在 CSS 2.1 规范中,术语“size”和“sized”在第八章、第九章、第十章、第十一章、第十七章和第十八章中出现了 15 次。这些事件指的是一般意义上的盒子有大小。

当然,定型、收缩和拉伸并不是什么新想法。创新之处在于,这本书清楚地定义了这三个术语,并展示了它们是如何成为 CSS 的基础特性和 CSS 设计模式的关键生成器

盒子模型放置

另一个创新是有三种方法可以放置一个盒子到它的容器或者它的兄弟:特别是,它可以缩进(或者突出),从它的兄弟偏移,或者从它的容器对齐和偏移(见第八章)。CSS 规范谈了很多关于偏移定位元素的内容,也谈了一些关于对齐元素的内容(参见 CSS 2.1 规范的第九章),但是它没有讨论元素如何能够缩进,尽管这种行为隐含在它的公式中。

缩进、偏移和对齐是不同的行为。例如,缩进的框被拉伸,其边距缩小其宽度,而对齐的框被调整大小或收缩,其边距不缩小其宽度。对齐和缩进的框与其容器对齐,而偏移框可以从其容器偏移或从其同级偏移。

需要不同的属性和属性值组合来缩进、偏移和对齐不同类型的框。第八章和第九章中的设计模式展示了这是如何实现的。

当然,缩进、偏移和对齐并不是什么新概念。创新之处在于,这本书清楚地定义了这三个术语,并展示了它们是 CSS 的一个基本特性,也是 CSS 设计模式的一个关键生成器

列布局

另一项创新是发现、命名和记录浏览器内置的 12 项自动技术,用于在表格中布置列(见第十六章)。

所有主流浏览器都包含这些强大的分栏功能。它们兼容各种主流浏览器,非常可靠。即使不建议使用表格进行页面布局, 2 表格数据仍然需要进行布局,您可以利用这些列布局使表格数据看起来很棒。

流畅的布局

另一个创新是流畅的布局(见第十七章)。流体布局的概念并不新鲜,但是创建它们的过程通常是一个反复试验的过程。在第十七章中,我们展示了四种简单的设计模式,你可以用它们在所有主流浏览器中自信而可预测地创建复杂的流畅布局。


CSS 2.1 规范的第九章和第十章中,术语“收缩”和“收缩到合适”出现了九次。第 10.3.5 节至第 10.3.9 节以及第 17.5.2 节中暗示了不同的盒子可以收缩以适应其内容的想法。

术语“拉伸”和“被拉伸”在第九章和第十六章中出现了四次。将一个盒子拉伸到其容器的想法在下面的引用中被顺便提及(斜体是添加的),“许多盒子的位置和大小是相对于称为包含块的矩形盒子的边缘计算的。”(参见第 9.1.2、9.3.1 和 10.1 节。)

2 使用表格进行布局会给视力不佳的用户带来可访问性问题。此外,流体布局技术(如第十七章所示)是完全可以使用的,比表格适应性更强。

这些设计模式,由外向内框、浮动部分、浮动分隔线和流体布局,使用浮动和百分比宽度使它们变得流畅,但它们没有使用这些技术时通常会遇到的问题,例如折叠容器、交错浮动和将浮动推到彼此下方的百分比。3

Fluid Layout 设计模式使用表格的多功能性创建列布局,但不使用表格。比表格更好的是,这些布局可以根据需要自动调整宽度,并从列重排到行,以适应狭窄的显示。

事件风格

另一个创新是第十七章中介绍的事件样式 JavaScript 框架。这是一个简单、强大、开源的框架,用于动态地、交互式地对文档进行样式化。它使用最新的最佳实践来确保 HTML 标记完全没有 JavaScript 代码,并且完全可访问,所有样式都是用 CSS 完成的。此外,该框架允许您使用与选择 CSS 元素相同的选择器来选择 JavaScript 中的元素。这极大地简化和统一了动态 HTML 文档的样式和脚本!

这本书包括了这个框架,展示了如何集成 JavaScript、CSS 和 HTML,这样你就可以交互式地使用样式。当然,如果你不想使用 JavaScript,你可以跳过第十七章的五个 JavaScript 设计模式和第二十章的两个 JavaScript 模式——剩下的 343+设计模式不使用 JavaScript。

结合 HTML5 和 CSS3 创建设计模式

书中最后也是最普遍的创新是将 HTML 元素的一般类型与 CSS 属性结合起来创建设计模式的想法。这本书在第二章定义了 HTML 元素的四种主要类型(结构块、终端块、多用途块和内联),第四章将它们映射到六种盒子模型(内联、内联块、块、表、绝对和浮动)。

每个设计模式指定了它如何应用于 HTML 元素的类型。换句话说,设计模式不仅仅是一个只在你使用特定元素时才起作用的配方;这是一种适用于所有等价的 HTML 元素的类型的模式。

例如,第十八章中的浮动首字下沉设计模式指定了一个使用块和行内元素的模式,但是它没有指定必须使用哪些块和行内元素(参见清单 1)。例如,您可以为BLOCK元素使用一个段落,为INLINE元素使用一个跨度(参见清单 2),或者您可以为BLOCK使用一个除法,为INLINE使用一个<strong>,等等。

在一些例外的情况下,设计模式可能会指定一个实际的元素,比如<span>。当特定元素是最佳解决方案、唯一解决方案或极其常见的解决方案时,就会出现这种情况。即使在这些情况下,您通常也可以用相同类型的另一个元素替换指定的元素。


当你浮动元素时,Internet Explorer 6 有许多可能发生的 ?? 错误。不幸的是,尽管 Fluid Layout 设计模式在大多数时候很好地避免了这些错误,但是没有办法创建一个总是绕过这些错误的解决方案。幸运的是,Internet Explorer 7 修复了这些错误。

1。清单 1。浮动首字下沉设计图案

HTML

<BLOCK class="hanging-indent">   <**INLINE** class="hanging-dropcap"> text **</INLINE>**   **</BLOCK>**

CSS

  .hanging-indent { padding-left:+VALUE; text-indent:-VALUE; margin-top:±VALUE; }   .hanging-dropcap { position:relative; top:±**VALUE**; left:-**VALUE**; font-size:**+SIZE;**     line-height:**+SIZE;**}

2。清单 2。浮动首字下沉示例

HTML

<p class="hanging-indent">    <**span** class="hanging-dropcap" >H**</span>**anging Dropcap. </**p**>

CSS

.hanging-indent { padding-left:50px; text-indent:-50px; margin-top:-25px; } .hanging-dropcap { position:relative; top:**0.55em;** left:**-3px**; font-size:**60px;**   line-height:**60px;**}

约定

每种设计模式都使用以下约定:

大写标记应替换为实际值。(注意清单 1 中的大写标记是如何被清单 2 中的值替换的。)

当您应该用自己选择的元素替换元素时,它们是大写的。如果一个元素名称是小写的,除非你确保改变产生相同的盒子模型,否则不应该改变它。以下是典型的元素占位符:

ELEMENT代表任何类型的元素。

INLINE代表行内元素。

INLINE_TEXT表示包含文本的行内元素,如<span><em><code>

BLOCK代表块状元素。

TERMINAL_BLOCK代表端子板元件。

INLINE_BLOCK表示内嵌块元素。

HEADING代表<h1>, <h2>, <h3>, <h4>, <h5>, and <h6>

PARENT表示可以成为其子元素的有效父元素的任何元素。

CHILD表示可以是其父元素的有效子元素的任何元素。

LIST代表任何列表元素,包括<ol><ul><dl>

LIST_ITEM代表任何列表项,包括<li><dd><dt>

你应该替换的选择器都是大写的。如果选择器包含小写文本,那么选择器的这一部分就不应该更改,除非您也修改了 HTML 模式,比如更改类名。以下是典型的占位符:

SELECTOR {}代表任何选择器。

INLINE_SELECTOR {}代表任何选择行内元素的选择器。

INLINE_BLOCK_SELECTOR {}表示选择内嵌块元素的任何选择器。

BLOCK_SELECTOR {}代表选择块元素的任何选择器。

TERMINAL_BLOCK_SELECTOR {}代表选择端子板元件的任何选择器。

SIZED_BLOCK_SELECTOR {}代表选择尺寸块元素的任何选择器。

TABLE_SELECTOR {}代表选择表格元素的任何选择器。

CELL_SELECTOR {}表示选择表格单元格元素的任何选择器。

PARENT_SELECTOR {}代表在设计模式中选择父元素的任何选择器。

SIBLING_SELECTOR {}代表任何选择模式中的子元素的选择器。

TYPE {}代表一个选择器,根据您选择的类型选择元素,如h1span

*.CLASS {}代表一个选择器,它根据您选择的类名来选择元素。

#ID {}代表一个选择器,它根据您选择的 ID 来选择元素。

应该替换的符号用大写符号表示。如果值包含小写文本,则不应更改该部分值。以下是典型的值令牌:

有些值是文字值,不能被替换,如0-9999px1px1emnoneabsoluterelativeauto。这些值总是小写。

+VALUE表示大于或等于零的正测量值,如010px2em

-VALUE表示小于或等于零的正测量值,如0-10px-2em

±VALUE代表任何测量值。

VALUEem代表电磁测量。

VALUEpx代表像素测量。

VALUE%代表百分比测量。

VALUE_OR_PERCENT代表一个值,可以是度量值或百分比。

WIDTH STYLE COLOR代表多个属性值,如border所要求的属性值。我们为每个值使用一个大写的令牌。

url("FILE.EXT")代表一个背景图像,您可以用图像的 URL 替换FILE.EXT

CONSTANT代表有效的常数值。例如,white-space允许三个常量值:normalprenowrap。为了方便起见,我们经常用大写字母列出有效的常量值,在每个可能的值之间加下划线,比如NORMAL_PRE_NOWRAP

ABSOLUTE_FIXED代表常数值列表,您可以从中选择一个值。下划线分隔常量值。position的完整值列表包括staticrelativeabsolutefixed。如果一个设计模式只对absolutefixed有效,则该模式指定position:ABSOLUTE_FIXED。如果对所有四个值都有效,则指定position:STATIC_RELATIVE_ABSOLUTE_FIXEDposition:CONSTANT

-(TAB_BOTTOM + EXTRA_BORDER + EXTRA_PADDING)是一个可以用计算值替换的公式示例。公式中的大写标记是出现在设计模式中其他地方的标记。例如,如果您将TAB_BOTTOM分配给10px,将EXTRA_BORDER分配给10px,将EXTRA_PADDING分配给10px,那么您将使用-30px替换该公式。

使用这本书

你可以用这本书来掌握 CSS。你可以直接通读这本书,将你的 CSS 技能提升到一个更高的水平,并发现隐藏在设计模式中的许多金块。每一章都是有组织的,因此它建立在本章前面和前面章节中介绍的设计模式的基础上。另一方面,由于各个章节和设计模式是独立的,所以您可以按任意顺序逐一阅读它们,以掌握特定的主题或技术。

你可以把这本书当作参考书。这本书解释了所有可用的 CSS 属性,并展示了如何在例子中使用它们。更重要的是,许多属性在与其他属性组合时表现不同。每个设计模式都识别并记录了创建特定结果所需的独特属性组合。这使得它不仅是一本关于 CSS 属性如何单独工作的参考书,也是一本关于它们如何组合工作的参考书

*你可以用这本书来举例学习。由于书中所有的例子都遵循最佳实践,你可以通过学习来学习好的习惯和技巧。为了通过例子更容易地学习本书,您可以使用“另请参阅”部分来查找所有相关的设计模式。这使您可以很容易地看到如何在各种上下文中使用特定 CSS 属性或功能的许多示例。

你可以把这本书当作食谱来使用,帮助你创造设计或解决问题。设计模式是按主题组织的,因此您可以快速找到相关的解决方案。

我们在书中添加了额外的功能,以便在您需要时可以轻松找到解决方案。您可以使用目录、索引、缩略图、章节大纲、设计模式名称以及每个设计模式的“另请参阅”部分来快速查找属性、模式、答案和解决方案。由于每个例子中的截屏都在每页的相同位置,您甚至可以在查看截屏的同时翻阅书籍以找到解决方案。我们发现视觉扫描是一种非常简单、快速、有效的解决方案!

这本书是如何构成的

第一章到第三章探索 CSS 和 HTML 的基础:

第一章展示了设计模式如何让 CSS 变得简单。在这里,我们展示了如何将简单的设计模式组合成更加复杂和强大的模式。我们还回顾了 CSS 的语法和层叠顺序。此外,我们还提供了几个图表来简化 CSS 的使用:有用的 CSS 网站的链接列表,CSS 属性的总结;一份四页的清单,列出了所有可用的 CSS 属性、值和选择器,并按照它们的使用位置进行了组织;关于测量单位和字体大小的图表;在所有浏览器中标准化元素样式的两个示例样式表;媒体询问;过渡、动画和 2D 变换;以及 CSS 故障排除的 12 步指南。

第二章介绍了 HTML 的设计模式。在这一章中,我们展示了使用 HTML 的最佳实践,包括用 XHTML 编码。我们还探索了可以用 HTML 创建的结构类型,包括结构块、终端块、多用途块和内联。我们还展示了如何使用 id 和属性来方便 CSS 选择器的选择。

第三章介绍 CSS 选择器和继承的设计模式。在这里,我们展示了选择器如何成为 HTML 和 CSS 之间的桥梁。我们展示了类型、类、ID、位置、组、属性、伪元素、伪类和子类选择器的设计模式。我们也探索 CSS 继承。

第四章到第六章探索六种 CSS 盒子模型。它们显示了每个 HTML 元素是如何呈现为这六种类型的框中的一种(或者根本不呈现)。它们展示了相同的属性如何在每个盒子模型中产生不同的结果,以及每个盒子模型如何与其他盒子模型不同地流动。

第四章探讨了六种盒子模型:内联、内联块、块、表、绝对和浮点。

第五章探讨了标注盒子尺寸的三种方式:定尺寸、收缩或拉伸。

第六章探讨了每一个盒子模型属性:边距、边框(半径、阴影等)。)、填充、背景、溢出、可见性和分页。

第七章到第九章探讨盒子如何流动或放置。

第七章探讨了五种定位模型(静态、绝对、相对、固定和浮动)并将它们与六种盒子模型联系起来。

第八章探讨了盒子定位的三种方式——例如,盒子可以缩进或突出,从它的兄弟偏移,或者从它的容器对齐和偏移。

第九章结合了第七章和第八章中的模式。这些组合产生了 50 多种定位元素的设计模式——尤其侧重于绝对和固定定位。

第十章到第十二章详细探讨了内联框如何流动,以及如何设计文本和对象的样式、间距和对齐方式。

第十章探讨了样式文本的属性,还包含了三种隐藏文本的设计模式,同时保持对非视觉用户的可访问性。它还介绍了一些高级技术,比如用 canvas 和 vml 替换文本,以及 CSS3 字体嵌入。

第十一章展示了如何水平和垂直分隔内联内容。

第十二章展示了如何水平和垂直对齐内联内容。

第十三章和第十四章详细探讨了块和图像是如何流动的,以及如何设计它们的样式。

第十三章探索积木,从讨论积木的结构意义以及如何直观地展示这种意义开始。它涵盖了列表、内联块、折叠边距、插入块、块间距和边缘块。

第十四章探索图像,比如图像贴图、半透明图像、用图像替换文本、精灵、阴影图像、圆角。

第十五章和第十六章详细探讨了如何设计表格和单元格的样式和布局。

第十五章探究表格包括表格选择器、折叠边框、隐藏单元格、垂直对齐单元格中的内容,以及将内联和块元素显示为表格。

第十六章探讨了使用 12 种模式来布置表格列,这 12 种模式会自动收缩列、调整列的大小、按比例分配列,等等。

第十七章探讨了如何利用浮动的流动来创建流体布局。

第十七章展示了如何创建自动适应不同设备、字体、宽度和缩放系数的流畅布局。它还展示了如何使用 JavaScript 创建交互式布局。

第十八章到 20 章展示了如何结合设计模式来创建同一问题的多种解决方案。每种解决方案解决不同的需求,并且具有不同的优点和缺点。除了它们本身是有用的解决方案之外,它们还展示了如何组合模式来解决任何设计问题。

第十八章探索首字下沉。在这里,我们将介绍使用七种不同设计模式组合的七种首字下沉。

第十九章探讨标注和引用。本章展示了五种标注和三种报价。

第二十章探究警报。在这里,我们展示了三种类型的交互式提醒和八种类型的文本提醒(即注意力吸引器)。它还探讨了 HTML5 表单验证,并展示了如何对 HTML5 表单进行本机验证,并在错误输入时提醒用户。

下载代码

您可以通过搜索并进入 Pro HTML5 和 CSS3 设计模式的详细页面,在[www.apress.com](http://www.apress.com)下载所有代码。在这本书的详细页面上有一个压缩成 ZIP 文件的示例代码的链接。

使用代码

代码被安排在文件夹中,每章一个文件夹。为了便于导航章节文件夹,每个文件夹名称都包括章节编号和标题。每个章节文件夹中都有示例文件夹:一个文件夹对应一个章节中介绍的设计模式。

所以你可以很容易地找到例子,每个例子文件夹都有和它的设计模式一样的名字。这使得通过搜索文件夹名称来查找设计模式变得简单而快速。因为每个例子中的 HTML 命名并描述了它的设计模式,所以您可以通过在 HTML 文件中搜索单词来找到设计模式。您也可以在 CSS 文件中搜索使用特定 CSS 属性的例子,比如display

为了便于在多个浏览器中查看示例,我们将名为index.html的文件放在链接到所有设计模式文件夹的根文件夹中。反过来,每个文件夹包含一个名为index.html的文件,该文件链接到该文件夹中的所有设计模式。这些导航页面可以让您快速找到并查看每一章中的每个设计模式。

每个示例文件夹包含所有让示例运行所需的文件。这使得在您自己的工作中使用示例变得轻而易举:只需复制一个文件夹并开始进行更改。您不必担心跟踪和包含其他文件夹中的文件。

每个示例文件夹中最重要的文件是example.htmlpage.cssexample.html包含示例的 HTML 代码。page.css是示例的主样式表。

每个例子都使用一个名为site.css的 CSS 文件。它包含一些不重要的字体和标题规则,使书中的所有例子具有相同的基本外观。

在少数例外情况下,我们使用额外的 CSS 文件来克服 Internet Explorer 中的错误或非标准行为,这些规则会覆盖page.css中的规则。

这七个 JavaScript 示例使用了五个 JavaScript 文件。这些在第十七章的事件造型设计模式中解释。page.js是最重要的文件,因为它包含特定于示例的 JavaScript 代码。剩下的 JavaScript 文件都是开源库。

最后,每个示例文件夹包含该示例使用的所有图像文件。

联系作者

您可以通过以下地址联系我们:

  • 迈克尔·鲍尔斯
  • [synodinos@gmail.com](http://synodinos@gmail.com)中的狄奥尼修斯

我们期待您的评论、建议和问题。*

一、设计模式:让 CSS 变得简单!

从表面上看,CSS 似乎很容易。它有 45 个常用属性,可以用来设计文档的样式。在表面之下,属性和属性值的不同组合会触发完全不同的结果。我称之为 CSS 多态性是因为同一个属性有许多含义。CSS 多态性的结果是可能性的组合爆炸。

学习 CSS 不仅仅是学习单个属性。它是关于学习可以使用属性的上下文,以及不同类型的属性值在每个上下文中如何不同地工作。以width属性为例,它有许多不同的含义,这取决于它与其他规则的组合方式以及赋予它的值。例如,width对内联没有任何影响。width:auto包覆面浮动到其内容的宽度。width:autoleftright设置为auto时,绝对收缩。width:auto将块拉伸到其父元素的宽度。width:autoleftright设置为0时,绝对拉伸到其包含块的宽度。width:100%将块和浮动拉伸到其父元素的宽度,只要它们没有边框、填充和边距。width:100%将表格拉伸到其父表格的宽度,即使它们有边框和填充。width:100%将绝对值拉伸到其最近的定位祖先的宽度,而不是其父代的宽度。width:100em根据元素的font-size的高度来调整元素的大小,这使得元素的宽度足以容纳一定数量的字符。width:100px将元素的大小调整为固定的像素数,而不管其文本的font-size

更复杂的是,并非所有的规则都由浏览器实现。例如,122 个属性中超过 40 个和 600 个 CSS 规则中超过 250 个没有被一个或多个主要浏览器实现。CSS 结合了几个定义各种级别和配置文件的规范。CSS 的每一级都建立在最后一级的基础上,通常添加新的功能,通常表示为 CSS 1、CSS 2 和 CSS 3。配置文件通常是为特定设备或用户界面构建的一个或多个 CSS 级别的子集。浏览器对 CSS3 的支持对开发人员来说是一个重要的问题,尤其是因为它作为一个规范仍在快速发展。

试图通过记忆每个规则的异常数量来学习 CSS 是非常令人沮丧的。

为了让学习 CSS 变得容易,这本书记录了所有可用的属性和属性值的组合。它将属性放在上下文中,并描绘了 CSS 如何工作的完整画面。

想象一下,您不必阅读不起作用的规则,也不必测试每个规则来查看它是否在每个浏览器中以及与其他规则结合使用,这样可以节省多少时间。我已经帮你做了。我已经进行了成千上万次测试。我已经在每一个主流浏览器中测试了每一个 CSS 属性和属性的每一种组合,包括 Internet Explorer 6/7/8/9、Firefox 7、Chrome 12、Opera 9 和 Safari 5。

我将这些结果归结为简单的设计模式——创建令人惊叹的、高性能的、可访问的网站所需的所有 CSS 和 HTML 设计模式。本书的这一版(第二版)已经更新,包括了关于 HTML5 和 CSS3 的最新信息和提示。

当你学会了这些设计模式后,你会想如果没有它们你是如何开发网站的!

在这一章中,我将讨论设计模式的目的以及它们是如何工作的。我给出了一些如何结合设计模式来创建新模式的例子。我还讨论了如何利用样式表、CSS 语法和层叠顺序。

接下来,我将展示一系列图表,列出所有可用的 CSS 属性和度量单位。然后,我介绍了快速排除 CSS 故障的 12 种技术。最后,我将讨论如何标准化各种浏览器元素的样式——这样您就可以放心地覆盖这些默认样式。

设计模式——结构化食谱

设计模式已经在软件编程中获得了巨大的成功。它们提高了 web 设计和开发的生产率、创造力和效率,并且减少了代码膨胀和复杂性。在 CSS 和 HTML 的上下文中,设计模式是跨各种浏览器和屏幕阅读器工作的通用功能集,不会牺牲设计价值或可访问性,也不依赖黑客和过滤器。但到目前为止,它们还没有被系统地应用到 HTML 和 CSS 网页设计和开发中。

设计模式是所有创造性活动的基础。当我们说话、写作和创作时,我们根据模式来思考。设计模式类似于我们可以用自己的内容填充的文档模板。在文学上,它们就像原型人物和情节。在音乐中,它们就像主题和变奏。在编程中,它们类似于可重复使用的算法,可以系统地变化和相互组合以产生期望的结果。

一旦一个设计模式被揭示出来,它会极大地增加创造力和生产力。它可以单独使用来创建快速的结果,并且可以很容易地与其他模式结合来创建更复杂的结果。设计模式简化并放大了创造过程。他们让创作像用积木或乐高积木一样简单。您只需选择预先设计好的图案,改变它们,然后将它们组合起来,就能创造出您想要的效果。模式不会限制创造力——它们会释放创造力。

Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides (Addison-Wesley,1995)的开创性著作Design Patterns:Elements of Reusable Object-Oriented Software解释了设计模式由四个元素组成:模式名、问题、解决方案和权衡。本书遵循这种方法。

因为这是一本实用的书,所以它直接关注 CSS 和 HTML 中设计的具体模式,这些模式实际上是在主流浏览器中实现的。这本书还通过将内置模式组合成更高级的模式来创建新的设计模式。

在一个非常真实的意义上,这是一本你可以用来创造你的设计的模式书。

使用设计模式

第一章至 7 介绍了造型布局的基本属性和元素。第八章和 9 结合这些属性来创建所有可能的块、定位和浮动布局。第十章到 12 章介绍了文本样式的基本属性,以及可用于创建内联布局的属性组合。第十三章到第十六章将前几章的设计模式与专业属性和元素结合起来,以设计块、列表、图像、表格和表格列。

从第一章到第十六章到第十六章总共介绍了 300 多种设计模式,这些模式是通过将 45 种常见的 CSS 属性与四种类型的元素(内联、内联块、块和表)和五种类型的定位(静态、相对、绝对、固定和浮动)相结合而创建的。

这就是设计模式的强大之处:很容易将基本模式组合起来形成更复杂的模式。这使得学习 CSS 变得容易,并且使得使用 CSS 非常高效。第十七章到 20 章展示了如何结合这些设计模式来创建流畅的布局、首字下沉、标注、引用和提醒。

为了说明设计模式的简单性和强大功能,接下来的五个例子展示了如何将一系列基本设计模式组合成更复杂的模式。您不需要理解每个模式的细节,只需要理解组合模式的过程。

本系列的第一个例子展示了background属性的作用。background是一种内置于 CSS 中的设计模式,在元素后面显示图像。例 1-1 展示了background 属性结合一个 division 元素。该分区的大小为 250×76 像素,因此它将显示整个背景图像。 1

例 1-1。背景图像

Image

HTML

`

Background Image

`
CSS

div { **background:url("heading2.jpg") no-repeat;** width:250px; height:76px; }

例 1-2 展示了绝对设计模式。绝对设计模式背后的思想是从流程中移除一个元素,并相对于另一个元素定位它。CSS 为此提供了position:absolute规则。当position:absolutetopleft属性组合在一起时,您可以将一个元素定位在其最近的祖先的左上方的偏移量处。我使用position:relative来定位分部,这样它将是距离跨度最近的祖先。然后,我将跨度绝对定位在距离该分区顶部和左侧 10 个像素的位置。 2


这个例子很简单,但是它结合了七种设计模式:第二章中的结构块元素设计模式;第三章中的类型选择器模式;第四章中的块盒模式;第五章中的宽度、高度和尺寸模式;和第六章中的背景设计模式。

这个例子很简单,但是它结合了七种设计模式:第二章中的内联元素和结构块元素设计模式;第三章中的类选择器模式;第四章中的绝对盒模式;以及第七章中的绝对、相对和最近定位的祖先模式。

例 1-2。绝对的

Image

HTML

Absolute

  Sized Absolute
`
CSS

`*.positioned { position:relative; }
*.absolute { position:absolute; top:10px; left:10px; }

/* Nonessential styles are not shown */`

例 1-3 结合前两个例子中的设计模式,创建文本替换设计模式。文本替换背后的想法是在某些文本的位置显示一个图像(这样您就可以对文本进行更多的风格控制,因为它是嵌入在图像中的)。此外,您希望文本出现在图像的后面,以便在图像下载失败时可以看到文本。

我结合了背景和绝对设计模式来创建文本替换模式。我在标题中放置了一个空跨度。我相对定位了标题,所以子元素可以相对于它绝对定位。我为 span 分配了一个背景图像,并将其绝对定位在 heading 元素中的文本前面。我将跨度和标题的大小调整为背景图片的大小。

最终结果是,span 的背景图像覆盖了标题中的文本,如果图像下载失败,标题中的样式文本就会显示出来。 3


3 文本替换示例使用了前两个示例中显示的 14 种设计模式。第三章还介绍了 ID 选择器设计模式。你可以在第十章中了解更多关于文本替换设计模式的知识。

例 1-3。文本替换

Image

HTML

`

Text Replacement

Heading 2****

`
CSS

`#h2 { position:relative; width:250px; height:76px; overflow:hidden; }

h2 span { position:absolute; width:250px; height:76px; left:0; top:0;

background:url("heading2.jpg") no-repeat; }`

例 1-4 演示了左边界设计模式。这种模式背后的思想是将一个或多个元素从一个块中移到它的左边,这样你就可以有标题(或者注释、图片等等)。)在左边,内容在右边。 4


4 左边界设计模式结合了第三章中的位置选择器设计模式;第六章的保证金模式;第四章中的绝对盒模式;以及第七章中的绝对、相对和最近定位的祖先模式。

例 1-4。左边界

Image

HTML

`

Left Marginal

  **

Heading

**   You want to excerpt an element and move it into the left margin.
`
CSS

***.left-marginal** { position:relative; margin-left:200px; } ***.marginal-heading** { position:absolute; left:-200px; top:0; margin:0; }

例 1-5 演示了边缘图形首字下沉设计模式。这种模式结合了前面四个例子中展示的所有设计模式。这种模式背后的想法是在块的左边界创建一个图形首字下沉,具有文本替换和左边界设计模式的所有优点。 5

为了满足这些要求,我使用了indent类来相对定位段落,使其成为首字下沉的最近祖先,并为段落添加 120 像素的左边距,为首字下沉留出空间。我使用了graphic-dropcap类来绝对定位首字下沉,将其移动到段落的左边距,并将其设置为首字下沉图像的精确大小。然后,我将 span 完全放置在图形首字下沉内,并将其移动到首字下沉文本上,这样它就用背景图像覆盖了文本。

就其本身来看,边缘图形首字下沉模式是 16+种设计模式的复杂组合。另一方面,当被看作是文本替换和左边缘设计模式的组合时,它是非常简单的。这就是设计模式的力量。


第十八章详细讨论了边缘图形首字下沉设计模式。

例 1-5。边缘图形首字下沉

Image

HTML

`

Marginal Graphic Dropcap

Marginal
  Graphic Dropcap. The letter M has been covered by the dropcap image.
  Screen readers read the text and visual users see the image.
  If the browser cannot display the dropcap image,
  the text becomes visible.

`

CSS

`*.indent { position:relative; margin-left:120px; }

*.graphic-dropcap { position:absolute;
  width:120px; height:90px; left:-120px; top:0; }

*.graphic-dropcap span { position:absolute;
  width:120px; height:90px; margin:0; left:0; top:0;
  background:url("m.jpg") no-repeat; }`

使用样式表

您可以在三个位置放置样式:样式表、<style>style

一个样式表是一个独立的文件,你可以使用<link>元素或者 CSS 的@import语句将它附加到一个 HTML 文档中。<style>是一个 HTML 元素,你可以把它嵌入到 HTML 文档中。style是一个可以嵌入任何 HTML 元素的属性。

我建议将样式放在样式表中。这减少了 HTML 文档中不一致的内容,并将所有样式放在易于管理的文件中。

我建议使用单个单词的小写名称来命名样式表。这使得样式表名称简单易记,并且在所有操作系统中都能安全工作。我建议您使用一个描述样式表的范围和用途的名称,比如site.csspage.csshandheld.cssprint.css等等。样式表的标准扩展名是.css。标准的互联网媒体类型是text/css

我建议使用样式表的位置来控制它的范围。如果样式表是针对整个网站的,您可以将它放在网站的根目录中。如果一个样式表只适用于一个文档,你可以把它放在与该文档相同的目录中。另一种选择是将所有的样式表保存在一个目录中,这取决于您组织站点的方式。

要将样式表链接到 HTML 文档,可以在 HTML 文档的<head>部分包含一个<link>元素,并且可以将样式表的 URI 放在<link>元素的href属性中。清单 1-1 显示了我在本书的每个例子中使用的样式表链接。有关链接样式表的更多信息,请参见第二章中的标题元素和条件样式表设计模式。

清单 1-1。附加样式表

`<link rel="stylesheet" href="site.css" media="all" type="text/css" />

`

为了提高下载性能,您可能希望在<style>元素中包含特定于页面的样式,而不是在单独的特定于页面的样式表中。因为这些样式是特定于页面的,所以将这些样式放在页面的头部没有什么坏处。另一方面,我强烈建议不要使用 HTML 元素的style属性,因为这会创建非常难以维护的代码。

CSS 语法

CSS 语法很简单。一个样式表包含个样式;一个样式包含选择器规则;并且一个规则包含一个属性和一个。以下是一种风格的设计模式:

SELECTORS { RULES }

以下是规则的设计模式:

PROPERTY:VALUE;

比如p{margin:0;}就是一种风格。p是选择器,它选择 HTML 文档中所有的<p>元素。花括号({})操作符将规则margin:0;分配给选择器p。冒号(:)运算符将值0赋给属性margin。分号(;)操作符终止规则。

一个样式可以有一个或多个选择器和一个或多个规则。比如p.tip{margin:0; line-height:150%;}就是一种风格。花括号操作符将两个规则margin:0;line-height:150%;组合成一个规则集,并将其分配给选择器p.tip,后者选择 HTML 文档中的所有<p class="tip">元素。

CSS 语法细节

CSS 语法的要点如下:

  • Unicode UTF-8 应该被用来编码 CSS 文件——就像你应该编码 HTML 文件一样。
  • CSS 代码要小写。在 XHTML 中引用元素名、类、属性和 id 时,选择器区分大小写6CSS 属性和值都不区分大小写。为了简单和一致,我对所有 CSS 代码使用小写字符,包括元素、类和 id。

在 HTML 中,CSS 选择器是不区分大小写的。

  • 元素名、类和 id限于字母、数字、下划线(_)、连字符(-)和 161 及以上的 Unicode 字符。元素、类或 ID 的第一个字符不能是数字或连字符。类名和 ID 不能包含除下划线和连字符以外的标点符号。例如,my_name2-1是一个类或 id 的有效名称,但是下面是无效的 : 11my_name-my_namemy:namemy.namemy,name
  • 可以将多个类分配给一个元素,方法是用空格分隔每个类名,比如class="class1 class2 class3"
  • 常量值不应放在引号中。比如color:black;是正确的,而color:"black";不是。
  • 反斜杠(\ ) 可以用来在通常不会出现的上下文中嵌入字符;例如,\26B&嵌入到一个字符串或标识符中。反斜杠后面可以跟 2 到 8 个十六进制代码,或者反斜杠后面可以跟一个字符。
  • 一个字符串可以包含圆括号、逗号、空格、单引号(')和双引号("),只要用反斜杠转义即可,如下:      "embedded left  parentheses \( "       "embedded right parentheses \) "       "embedded comma \, "       "embedded single quote \' "       "embedded double quote \" "       "embedded single quote  ' in a double-quoted string"       'embedded double quote  " in a single-quoted string'
  • 分号应该终止每个 CSS 规则和@import语句。      color:red;       @import "mystylesheet.css";
  • 规则集是通过用花括号将多个规则括起来创建的,比如{ color:red; font-size:small; }
  • 右花括号(} ) 立即终止一组属性,除非它嵌入在一个字符串内,比如"}"
  • 一个 CSS 注释以/开头,以/结尾,比如/* This is a CSS comment */。注释不能嵌套。因此,浏览器第一次在样式表中遇到/时,它会终止注释。如果随后出现/,它们不会被解释为注释的一部分,例如:      /* This is an incorrect comment         /* because it tries to nest           /* several comments. */             STARTING HERE, THIS TEXT IS OUTSIDE OF ALL COMMENTS! */ */

在 CSS 中使用空格

CSS 中的空格只包括以下字符:空格(\20)、制表符(\09)、换行符(\0A)、回车符(\0D)和换页符(\0C))。浏览器不会将其他 Unicode 空白字符解释为空白,例如不间断空格(\A0)。

您可以选择在以下内容的前后放置空格:选择器、花括号、属性、冒号、值和分号。例如,以下所有语句都是正确的,并且产生完全相同的结果:

`body{font-size:20px;line-height:150%;}

body { font-size:20px; line-height:150%; }

body { font-size : 20px ; line-height : 150% ; }

body
{
  font-size:  20px;
  line-height: 150%;
}`

在本书中,我使用了一种紧凑的编码风格,在规则中没有空格,在规则和选择器之间有一个空格,如下所示:

body { font-size:20px; line-height:150%; }

空白从不出现在属性名或常量属性值中。每当 CSS 使用多个单词作为属性名或常量属性值时,它都使用连字符来分隔单词,例如font-familysans-serif。在极少数情况下,CSS 使用 CamelCase 将多个单词组合成一个常量值,比如ThreeDLightShadow

使用属性值

属性值有以下几种形式:常量文本、常量数字、长度、百分比、函数、逗号分隔的值列表和空格分隔的值序列。每个属性都接受一个或多个这种类型的值。

我已经在示例 1-6 中包含了所有常见类型的值。但首先,我在这里列出了它们并附有解释:

  • **color:black;**将常量值black分配给color属性。大多数属性都有唯一的常数值。例如,color属性可以分配给 170 多个常量,这些常量代表从papayawhipThreeDDarkShadow的颜色。
  • **background-color:white;**将常量值white分配给background-color属性。请注意,以下三条规则与这条规则做的是同样的事情,但是使用了不同类型的属性值。十六进制也常用于样式中的颜色属性,如background-color:#000000;
  • **background-color:rgb(100%,100%,100%);**将 CSS 功能rgb()分配给background-colorrgb()在圆括号之间有三个逗号分隔的参数,它们指定了用于颜色的红色、绿色和蓝色的数量。在本例中,使用了百分比。每种颜色百分之百都是白色。
  • **background-color:rgb(255,255,255);**将白色分配给background-color。在这种情况下,使用 0 到 255 之间的值来代替百分比。值 0 表示没有颜色。值 255 等于颜色的 100%。对红色、绿色和蓝色使用 255 会产生白色。
  • **background-color:WindowInfoBackground;**将操作系统颜色WindowInfoBackground分配给background-color。注意 CamelCase 中的操作系统颜色常量。 7
  • **font-style:italic;**italic的常数值分配给font-style。属性还允许另外两个常量:normaloblique
  • **font-size:20px;**font-size分配 20 个像素的长度。您可以为大多数属性指定各种度量,包括px(像素)、em(字体高度或font-size)、ex(字母“x”的高度)、pt(点,即 1/72 英寸)、in(英寸)、cm(厘米)、mm(毫米)和pc(十二点活字,即 12 点,即 1/6 英寸)。
  • **font-family:"Century Gothic", verdana, arial, sans-serif;**将逗号分隔的字体名称列表分配给font-family。如果第一个字体名称不可用,浏览器将使用第二个,依此类推。最后一个字体名称应该是通用字体名称之一:“衬线”、“无衬线”、“草书”、“幻想”、“等宽”,在每个浏览器中都有效。每当字体名称包含空格时,必须用双引号括起来,例如"Century Gothic"
  • **line-height:150%;**font-size的 150%分配给line-height
  • **margin:1em;**将字体大小分配给margin(即font-size乘以 1)。
  • **border:4px double black;**创建一个 4 像素的黑色双线边框。注意border是如何接受三个空格分隔的值来表示边框的宽度、样式和颜色的。值的顺序无关紧要。border是三个属性的快捷属性:border-widthborder-styleborder-color。还有其他几个快捷属性,包括backgroundfontlist-stylemarginpadding
  • **padding:0.25em;**将字体大小的四分之一分配给padding(即font-size乘以0.25)。
  • **background-image:url("gradient.jpg");**使用url函数将gradient.jpg图像分配给background-image,该函数将文件的 URL 作为其唯一的参数。我总是把 URL 放在引号中,但是只有当 URL 包含空格时才需要。
  • **background-repeat:repeat-x;**将常数repeat-x分配给background-repeat。其他background-repeat值包括repeat-yrepeatno-repeat
  • **margin:0;**将零分配给margin。零是唯一没有测量单位的长度。所有其他长度必须立即进行测量,例如1px-1.5em2ex14pt0.5in-3cm30mm5pc
  • **font-weight:900;**将常数900分配给font-weight。这个数字实际上是一个常数。font-weight可以使用以下常量:normalboldbolderlighter100200300400500600700800900。(注意浏览器对数字字体粗细的支持较差,一般把100400当做normal,把500900当做bold。此外,bolderlighter很少被浏览器和/或操作系统字体支持。因此,除了normalbold之外,我很少使用font-weight的任何值。)

每次你将相同的属性分配给相同的元素时,新的规则会覆盖先前的规则。由于该示例在一行中包含四个背景色规则,因此应用最后一个。

在本章的后面,我将展示一个四页的图表,列出所有可用的 CSS 属性和值。color是图表中唯一具有不完整可用值列表的属性。它显示了 170 个颜色常数中的 79 个。我将 79 个颜色常量组织成三组,您可能会发现这三组很有用:16 种按色调组织的标准颜色,35 种按色调从亮到暗组织的常见颜色,以及 28 种操作系统颜色。在整本书中,我经常使用颜色gold。我也使用相关的色调,如wheatorangetomatofirebrickyellow

Image 提示您可以通过在属性名前面直接加上数字 1(或任何其他字符)来禁用规则,例如1background-color:white。这将使该规则无效,但只有一个规则无效。无效规则之前和之后的所有其他有效规则仍会被处理。在测试其他规则时,我经常使用这种技术使一个规则暂时无效,以禁用它的效果。

例 1-6。CSS 语法很简单

Image

HTML

`

<head><title>CSS Syntax</title>   <meta http-equiv="Content-type" content="text/html; charset=utf-8" />   **<link rel="stylesheet" href="page.css"   media="all"    type="text/css" />** </head>


  

CSS syntax is EASY!

</body> `
CSS

**body** { font-family:**"Century Gothic"**,verdana,arial,sans-serif;   font-size:20px; line-height:150%;   margin:1em; border:4px double black; padding:0.25em;   background-image:url("gradient.gif"); background-repeat:repeat-x; } **p** { margin:0; } **span** { font-weight:900; }

使用级联顺序

CSS 允许你多次分配相同的规则给相同的元素。我称这些竞争规则为 ??。浏览器使用层叠顺序来确定应用一组竞争规则中的哪个规则。例如,浏览器为每个元素分配默认规则。当您将规则分配给元素时,您的规则会与默认规则竞争,但是由于它具有更高的级联优先级,所以它会覆盖默认规则。

级联顺序根据规则中使用的选择器类型将规则分为六组。高优先级组中的规则会覆盖低优先级组中的竞争规则。组是由它们的选择器的特性组织的。低优先级组中的选择器比高优先级组中的选择器具有更少的特异性。

级联顺序背后的指导原则是通用选择器设置文档的整体样式,而更具体的选择器覆盖通用选择器以应用特定的样式。

例如,您可能希望使用*{margin-bottom:0;}来设计文档中所有元素的样式,使其没有下边距。你可能还想使用p{margin-bottom:10px;}来设计文档中所有段落的样式,底部边距为 10 像素。您可能还想使用*.double-space{margin-bottom:2em;}将属于double-space类的几个段落的底部边距设置为 2 ems。您可能还想使用#paragraph3{margin-bottom:40px;}为一个段落设置 40 像素的超大底部边距。在每种情况下,级联顺序确保更具体的选择器覆盖更一般的选择器。

以下是按优先级从高到低排列的六个选择器组:

  1. 最高优先级组包含添加了!important的规则。它们覆盖所有非!important规则。例如,#i100{border:6px solid -black!important;}优先于#i100{border:6px solid black;}
  2. 第二高优先级组包含嵌入在style属性中的规则。因为使用style属性会产生难以维护的代码,所以我不推荐使用它。
  3. 第三高优先级组包含具有一个或多个 ID 选择器的规则。例如,#i100{border:6px solid black;}优先于*.c10{border:4px solid black;}
  4. 第四高优先级组包含具有一个或多个属性选择器的规则。例如,*.c10{border:4px solid black;}优先于div{border:2px solid black;}
  5. 第五高优先级组包含具有一个或多个元素选择器的规则。例如,div{border:2px solid black;}优先于*{border:0px solid black;}
  6. 最低优先级组包含只有一个通用选择器的规则——例如,*{border:0px solid black;}

当竞争规则属于同一个选择器组时(例如两个规则都包含 ID 选择器),选择器的类型和数量会进一步区分它们的优先级。当一个选择器拥有比竞争的选择器多个高优先级选择器时,该选择器具有更高的优先级。例如,#i100 *.c20 *.c10{}的优先级高于#i100 *.c10 div p span em{}。因为两个选择器都包含一个 ID 选择器,所以它们都属于第三高优先级的组。因为第一个有两个类选择器,第二个只有一个类选择器,所以第一个有更高的优先级——即使第二个有更多的选择器。

当竞争规则在同一个选择器组中,并且具有相同数量和级别的选择器时,它们将按位置进一步区分优先级。优先级较高的位置中的任何规则都会覆盖优先级较低的位置中的竞争规则。(同样,这仅适用于竞争规则在相同的选择器组中,并且具有相同数量和级别的选择器的情况。选择器组始终优先于位置组。)

这六个位置按优先级从高到低排列如下:

  1. 最高优先级的位置是 HTML 文档头中的<style>元素。例如,<style>中的一个规则覆盖了由嵌入在<style>中的@import语句导入的样式表中的一个竞争规则。
  2. 第二高优先级的位置是由嵌入在<style>元素中的@import语句导入的样式表。例如,由嵌入在<style>中的@import语句导入的样式表中的规则会覆盖由<link>元素附加的样式表中的竞争规则。
  3. 第三高优先级的位置是由一个<link>元素附加的样式表。例如,由一个<link>元素附加的样式表中的一个规则覆盖了由样式表中嵌入的一个@import语句导入的一个竞争规则。
  4. 第四高优先级的位置是一个样式表,由嵌入在由一个<link>元素附加的样式表中的一个@import语句导入。例如,嵌入在链接样式表中的@import语句导入的规则会覆盖最终用户附加的样式表中的竞争规则。
  5. 第五高优先级的位置是最终用户附加的样式表。
    • 最终用户样式表中的!important规则是一个例外。这些规则被赋予最高优先级。这允许最终用户创建规则来覆盖作者样式表中的竞争规则。
  6. 最低优先级的位置是浏览器提供的默认样式表。

当在同一位置级别附加或导入多个样式表时,它们被附加的顺序决定了优先级。稍后附加的样式表会覆盖先前附加的样式表。

当竞争规则在同一个选择器组中,具有相同数量和级别的选择器,并且具有相同的位置级别时,代码中后面列出的规则将覆盖前面列出的规则。

在示例 1-7 、中,样式表中的每个规则都应用于 division 元素。每个规则对<div>应用不同的border-width。级联顺序决定了实际应用哪个规则。我按照从最不重要到最重要的层叠顺序对样式表中的样式进行了排序。从截图中可以看到,浏览器对<div>应用了最后一个规则,在<div>周围设置了 14 像素的边框。浏览器应用这个规则是因为它在层叠顺序中具有最高的优先级——它是一个附加了!important的 ID 选择器。

注意 ID 选择器如何覆盖类选择器,类选择器又覆盖元素选择器,元素选择器又覆盖通用选择器。注意!important是如何赋予选择器全新的重要性的。例如,!important通用选择器比非!important ID 选择器更重要!

注意border-style:none!important;是如何放置在bodyhtml选择器中的,以防止通用选择器*<body><html>周围放置边框。这也说明了元素选择器如何覆盖通用选择器。

例 1-7。级联顺序

Image

HTML

`
  

!important has highest priority.

`
CSS

`html, body { border-style:none!important; }

***** { border:0px  solid black; }          /* Universal Selector /
div { border:2px  solid black; }        /
Element Selector */
.c10 { border:4px  solid black; }      / Secondary Selector /
#i100 { border:6px  solid black; }      /
ID Selector */

***** { border:8px  solid black!important; }        /* !Universal Selector /
div { border:10px solid black!important; }      /
!Element Selector */
.c10 { border:12px solid black!important; }    / !Secondary Selector */

i100 { border:14px solid black!important; }    /* !ID Selector */`

简化级联

为了保持层叠顺序尽可能简单,我尽量减少了附加的样式表数量,并且不使用@import语句。我也避免使用!important操作符。最重要的是,我对我的选择器进行了排序,使它们在每个样式表中以级联顺序列出。

我将样式表组织成六组。我将所有通用选择器放在第一位,然后是元素、类、属性、伪和 ID 选择器。如果我有任何!important选择器,我将它们放在另一组组中的 ID 选择器之后。

保持样式表以层叠顺序排序有助于我记住 ID 选择器覆盖所有的类、属性、伪、元素和通用选择器——不管它们出现在当前样式表和所有其他样式表中的什么地方。同样,它提醒我每个样式表中的类、属性和伪选择器覆盖所有元素和通用选择器——不管它们出现在哪里。

按照层叠顺序对规则进行排序,可以很容易地看到竞争规则的应用顺序。这使得跟踪哪些规则覆盖了其他规则变得容易。我按照层叠顺序对规则进行排序,如下所示:

`/* Universal Selectors /
/
Element Selectors /
/
Class, Attribute, and Pseudo Selectors /
/
ID Selectors */

/* !important Universal Selectors /
/
!important Element Selectors /
/
!important Class, Attribute, and Pseudo Selectors /
/
!important ID Selectors */`

CSS 和 HTML 链接

Image

常用 CSS 属性

`display margin  text-indent
visibility      margin-left      text-align
        margin-right
float   margin-top      color
clear   margin-bottom
                font
position        border  font-family
z-index border-left     font-size
overflow        border-left-color       font-style
cursor  border-left-width       font-variant
        border-left-style       font-weight

left    border-right    text-decoration
right   border-right-color      text-transform
width   border-right-width
min-width       border-right-style      vertical-align
max-width
        border-top      line-height
top     border-top-color        white-space
bottom  border-top-width        word-spacing
height  border-top-style        etter-spacing
min-height
max-height      border-bottom   direction
        border-bottom-color     unicode-bidi
        border-bottom-width
/* LESS USABLE-------/ border-bottom-style
/
caption-side             /
/
clip                           /    padding list-style
/
content                    /        padding-left    list-style-type
/
empty-cells              /  padding-right   list-style-position
/
outline                     /       padding-top     list-style-image
/
outline-color            /  padding-bottom
/
outline-style            /  border-collapse
/
outline-width           /   background      table-layout
/
quotes                    / background-color
/
orphans                  /  background-image        page-break-after
/
page-break-inside  /        background-repeat       page-break-before
/
widows                   /  background-attachment
/
--------------------------*/  background-position`

CSS 属性和值:常用

这个列表只包括那些在所有主流浏览器中都有效的 CSS 属性和值。财产前的字母“I”表示它是继承的。斜体中的值是默认值。一些值是代表一个值的多种可能性的符号。例如,LENGTH代表0autonone以及所有测量值(%pxemexptincmmmpc)。

`Common  applies to all elements and box models.
        display:        inline, none, block, inline-block, list-item,
        table-cell, table, table-row

I      visibility:     visible, hidden

background-color:       transparent, COLOR
        background-image:       none, url("file.jpg")
        background-repeat:      repeat, repeat-x, repeat-y, no-repeat
        background-attachment:  scroll, fixed
        background-position:    0% 0%,   H% V%,  H V,
        left top, left center, left bottom,
        right top, right center, right bottom,
        center top, center center, center bottom

border: WIDTH   STYLE   COLOR
        border-width:   medium, LENGTH, thin,   thick
        border-style:   none,   hidden, dotted, dashed, solid, double,
        groove, ridge,  inset,  outset
        border-color:   black,  COLOR

border-left:    WIDTH   STYLE   COLOR
        border-left-width:      same as border-width
        border-left-style:      same as border-style
        border-left-color:      same as border-color
        border-right:   WIDTH   STYLE   COLOR
        border-right-width:     same as border-width
        border-right-style:     same as border-style
        border-right-color:     same as border-color
        border-top:     WIDTH   STYLE   COLOR
        border-top-width:       same as border-width
        border-top-style:       same as border-style
        border-top-color:       same as border-color
        border-bottom:  WIDTH   STYLE   COLOR
        border-bottom-width:    same as border-width
        border-bottom-style:    same as border-style
        border-bottom-color:    same as border-color

I      cursor: auto, default, pointer,
        help, wait, progress, move, crosshair, text,
        n-resize, s-resize, e-resize, w-resize`

CSS 属性和值:内容

`Content  applies to all except for rows.
         padding:        0, LENGTH
         padding-left:   0, LENGTH
         padding-right:  0, LENGTH
         padding-top:    0, LENGTH
         padding-bottom: 0, LENGTH

i   font:      caption, icon, menu, message-box, small-caption, status-bar
  i   font-family:       serif,  FONTLIST, sans-serif, monospace, fantasy, cursive
  i   font-size: medium, LENGTH, %ParentElementFontSize, xx-small, x-small,
         smaller, small, large, larger, x-large, xx-large
  i   font-style:        normal, italic, oblique
  i   font-variant:      normal, small-caps
  i   font-weight:       normal, lighter, bold, bolder,
         100, 200, 300, 400, 500, 600, 700, 800, 900

i   text-decoration:   none, underline, line-through, overline
  i   text-transform:    none, lowercase, uppercase, capitalize
  i   direction:         ltr, rtl
      unicode-bidi:      normal, bidi-override, embed

i   line-height:       normal, LENGTH, %FontSize, MULTIPLIER
  i   letter-spacing:    normal, LENGTH
  i   word-spacing:      normal, LENGTH
  i   white-space:       normal, pre, nowrap

i   color:     #rrggbb, #rgb, rgb(RED,GREEN,BLUE), rgb(RED%,GREEN%,BLUE%)
        black,  gray,    silver,  white,
         red,    maroon,  purple,  fuchsia,
         lime,   green,   olive,   yellow,
         blue,   navy,    teal,    aqua,

violet,      fuschia,    red,         maroon,  black
         wheat,       gold,       orange,      tomato,  firebrick
         lightyellow, yellow,     yellowgreen, olive,   darkolivegreen
         palegreen,   lime,       seagreen,    green,   darkgreen
         lightcyan,   cyan,       turquoise,   teal,    midnightblue
         lightskyblue,deepskyblue,royalblue,   blue,    darkblue
         whitesmoke,  lightgrey, silver, gray, dimgray, darkslategray

ActiveBorder, ActiveCaption, AppWorkspace, Background,
         ButtonFace, ButtonHighlight, ButtonShadow, ButtonText,
         CaptionText, GrayText, Highlight, HighlightText,
         InactiveBorder, InactiveCaption, InactiveCaptionText,
         InfoBackground, InfoText, Menu, MenuText, Scrollbar,
         ThreeDDarkShadow, ThreeDFace, ThreeDHighlight,
         ThreeDLightShadow, ThreeDShadow, Window, WindowFrame, WindowText`

CSS 属性和值:布局

`Float  applies  to all except cells and rows.
       float:   none,  left, right

Clear  applies  to all except inlines, inline-blocks, cells, & rows.
       clear:   none,  left, right, both

Positioned      applies to all except cells and rows.
        position:       static, relative; absolute, fixed
        left:   auto,  LENGTH, %WidthOfContainingBlock
        right:  auto,  LENGTH, %WidthOfContainingBlock
        top:    auto,  LENGTH, %HeightOfContainingBlock
        bottom: auto,  LENGTH, %HeightOfContainingBlock
        z-index:        auto,  INTEGER

Horizontal Margin       applies to all except cells and rows.
        margin: 0,     LENGTH, %WidthOfContainingBlock, auto
        margin-left:    0,     LENGTH, %WidthOfContainingBlock, auto
        margin-right:   0,     LENGTH, %WidthOfContainingBlock, auto

Vertical Margin applies to all except inlines, cells, and rows.
        margin: 0,     LENGTH, %WidthOfContainingBlock, auto
        margin-top:     0,     LENGTH, %WidthOfContainingBlock, auto
        margin-bottom:  0,     LENGTH, %WidthOfContainingBlock, auto

Width   applies to all except inlines and rows.
        width:  auto,  LENGTH, %WidthOfContainingBlock
        min-width:      0,     LENGTH, %WidthOfContainingBlock
        max-width:      none,  LENGTH, %WidthOfContainingBlock

Height  applies to all except inlines and tables.
        height: auto,  LENGTH, %HeightOfContainingBlock
        min-height:     0,     LENGTH, %HeightOfContainingBlock
        max-height:     none,  LENGTH, %HeightOfContainingBlock

Content Layout  applies to all except inlines, tables, and rows.
  i  text-indent:       0,     LENGTH, %WidthOfContainingBlock
  i  text-align:        left,  center, right, justify
     overflow:  visible, hidden, auto, scroll`

CSS 属性和值:专用

`List    applies only to lists.
  i  list-style:        TYPE POSITION IMAGE
  i  list-style-type:   disc, circle, square, none, decimal,
        lower-alpha, upper-alpha, lower-roman, upper-roman
  i  list-style-position:       outside,inside
  i  list-style-image: none,   url("file.jpg")

Table   applies only to tables.
  i  border-collapse:   separate, collapse
        table-layout:   auto, fixed

Cell    applies only to cells.
        vertical-align: baseline, bottom, middle, top

Inline  applies only to inlines and inline-blocks.
        vertical-align: baseline, LENGTH, %LineHeight,
        text-bottom, text-top, middle, top, bottom

Page    applies only to blocks and tables.
        page-break-after: auto, always, avoid
        page-break-before: auto, always, avoid`

选择器

`* {}    selects all elements
p  {}   selects all

elements
*.c {}  selects all elements where class="c"
p.c  {} selects all

elements where class="c"

main {}        selects one element where id ="main"

a:link  {}      selects all unvisited links
a:visited{}     selects all visited links
a:hover   {}    selects all links being hovered over
a:active   {}   selects the current link being activated
a:focus     {}  selects all links that have the focus
p:first-letter {}       selects first letter of all

elements
p:first-line    {}      selects first line   of all

elements
p:first-child    {}     selects first child  of all

elements
tr:nth-child(even)      selects every even row of a table
tr:nth-child(2n+0)      same as above
tr:nth-child(2n+0)      same as above
tr:nth-child(10n+9)     same as above

n   *.c   :first-line {}       selects every 9th, 19th, 29th, etc., row

n > *.c > :first-line {}       child selector example

n + *.c + :first-line {}       sibling selector example

n , *.c , :first-line {}       applies independent selectors to same block of properties

*[title]               {}       selects all elements with a title attribute
*[title~="WORD"]       {}       selects all where title attribute contains "WORD"
*[title="EXACT_MATCH_OF_ENTIRE_VALUE"]  {} selects all with exact attribute match`

媒体查询

CSS 长期以来一直支持为不同媒体类型定制的媒体相关样式表。例如,文档在屏幕上显示时可能使用无衬线字体,在打印时可能使用衬线字体。“屏幕”和“打印”是已经定义的两种媒体类型。

在 HTML4 的旧时代,可以这样写:

`

`

使用 CSS3,媒体查询通过允许更精确地标记样式表来扩展媒体类型的功能。媒体查询由媒体类型和零个或多个表达式组成,用于检查特定媒体特征的条件。通过使用媒体查询,可以根据特定范围的输出设备定制演示文稿,而无需更改内容本身。媒体查询是为真或为假的逻辑表达式。如果媒体查询的媒体类型与运行用户代理的设备的媒体类型匹配,并且媒体查询中的所有表达式都为真,则媒体查询为真。

这里有几个例子:

`<--! Applies to devices of a certain media type ('screen') with certain feature (it must be a
color screen)-->

@import url(color.css) screen and (color);`

为适用于所有媒体类型的媒体查询提供了速记语法;关键字“all”可以省略(连同尾随的“and”),即以下内容是相同的:

@media (orientation: portrait) { … } @media all and (orientation: portrait) { … }

这样,设计人员和开发人员就可以创建更复杂的查询来满足他们的特定需求:

@media all and (max-width: 698px) and (min-width: 520px), (min-width: 1150px) {   body {     background: #ccc;   } }

有一个很大的媒体功能列表,包括以下内容:

  • 宽度和设备宽度
  • 高度和设备高度
  • 方向
  • 纵横比和设备纵横比
  • 颜色和颜色指数
  • 单色(如果不是单色设备,等于 0)
  • 解决
  • 扫描(描述“电视”输出设备的扫描过程)
  • 网格(指定输出设备是网格还是位图)

灵活的计量单位

Image

固定计量单位

Image

96 dpi 时测量单位之间的比率

Image

96 dpi 时的典型字体大小值

Image

过渡、动画和 2D 变换

CSS 转换规范允许 CSS 值的属性变化在指定的持续时间内平稳地发生。通常,当 CSS 属性的值发生变化时,渲染结果会立即更新,但是通过 CSS 转换,作者能够随着时间的推移平滑地从旧状态转换到新状态。

这里有一个例子:

#box { transition-property: opacity, left; transition-duration: 3s, 5s; }

上述代码将导致opacity属性在三秒的时间内转换,而left属性在五秒的时间内转换。

CSS 动画类似于过渡,因为它们会随着时间的推移改变 CSS 属性的表示值。主要区别在于,当属性值更改时,转换会隐式触发,而当应用动画属性时,动画会显式执行。因此,动画需要被动画化的属性的显式值。这些值是使用关键帧指定的。

作者可以指定动画迭代多少次,是否在beginend值之间交替,动画是否应该运行或暂停,等等。

这里有一个例子:

` #warning {
    animation-name: 'horizontal-slide';
    animation-duration: 5s;
    animation-iteration-count: 10;
  }

@keyframes 'horizontal-slide' {

from {
      left: 0;
    }

to {
      left: 100px;    
}

}`

这将产生一个动画,在 5 秒钟内将#warning水平移动 100 像素,并重复 9 次,总共 10 次迭代。

CSS 2D 变换规范允许 CSS 渲染的元素在二维空间中进行变换。这里有一个例子:

#box {       height: 100px; width: 100px;       transform: translate(50px, 50px) scale(1.5, 1.5) rotate(90deg);   }

前面的例子在 X 和 Y 方向上移动#box50 个像素,缩放元素 150%,然后围绕 z 轴顺时针旋转 90 度。

CSS 故障排除

您可以使用下列步骤来解决样式表不工作的问题。我按顺序列出了最有可能帮助您快速找到问题的步骤。

  1. 验证 HTML 文档。这确保您不会遇到语法问题,这些问题可能会导致浏览器对文档结构的解释与您预期的不同。开发人员可以使用 W3C 验证服务([validator.w3.org/](http://validator.w3.org/))、W3C Unicorn 验证器([validator.w3.org/unicorn/](http://validator.w3.org/unicorn/))或者提供标记和样式验证的各种浏览器插件。
  2. 验证每个 CSS 样式表。这确保您没有语法问题,语法问题会导致一个或多个规则被忽略。
    • 确保非零测量值后有一个正确的计量单位(UOM) ,并且数字和它的计量单位之间没有空格,如1em100%。(line-height是个例外;它允许没有计量单位的非零测量。)
    • 确保属性名和它的值之间只有冒号(: ) 和可选的空格,比如width:100%width : 100%
    • 确保分号(; ) 关闭每个规则,比如width:100%;
  3. 使用 Mozilla 浏览器中的错误控制台查看 CSS 解析错误列表。浏览器会忽略每个有解析错误的规则,但与许多其他编程语言不同,它们会继续解析并应用剩余的规则。
  4. 验证一个选择器正在选择你认为它应该选择的所有元素,并且只选择那些元素。通过将outline:2px solid invert;放入选择器中,可以很容易地看到选择器的结果。(请注意,outline在 ie 7 中不工作,但border可以。)
  5. 仔细查看未应用的每个规则的级联优先级。级联优先级优先于文档顺序。例如,#myid{color:red;}优先于*.myclass{color:blue;},而#myid *.myclass{color:green;}优先于两者——不管它们出现在样式表中的什么位置,也不管它们出现在当前样式表之前还是之后加载的样式表中。我发现这是一个常见的问题,因为具有更高级联优先级的规则可以是任何样式表中的任何地方。假设您已经验证了您的样式表,当选择器中的一些属性有效,而其他属性无效时,您通常可以判断级联优先级何时出现问题——无论您使用什么值。当属性被具有更高级联优先级的另一个规则覆盖时,通常会发生这种情况。您通常可以通过在属性后添加!important来验证这种情况。!important赋予一个属性比所有非!important属性更高的优先级。如果!important使一个属性工作,你可能有一个级联优先级问题。
  6. 验证样式表中元素、类和 id的大小写与它们在 HTML 文档中的大小写完全匹配。这很重要,因为 XHTML 是区分大小写的。您可能希望始终使用小写值,以避免意外的不匹配。
  7. 仔细检查速记属性查看您在创建规则时是否遗漏了任何属性值。速记属性的问题在于,它们会给所有速记的属性赋值——即使你只设置了一个值!例如,background:blue;background-color设置为blue,还将background-image设置为nonebackground-repeat设置为repeatbackground-attachment设置为scrollbackground-position设置为0% 0%。如果包含background:blue;的规则比将background-image分配给url("image.jpg")的重叠规则具有更高的层叠优先级,您将看不到背景图像,因为速记属性background:blue;覆盖了它并将background-image设置为none
    • 速记属性包括marginborderpaddingbackgroundfontlist-style
    • font是一个特别麻烦的简写属性,因为它把这么多属性组合成一个,而且这些值都是继承的!这些属性包括font-familyfont-sizefont-weightfont-variantfont-styleline-height。请记住,即使给font分配一个值,比如font:1em;,也会导致浏览器为的所有属性设置默认值!
  8. 验证浏览器加载了你所有的样式表。你可以确保每一个都通过 HTML 文档的<head>部分中的<link>语句或者样式表中的@import语句被引用。如果您不确定是否正在加载样式表,您可以在样式表中放置一个独特的规则,以查看它是否得到应用。这样的规则是显而易见的,比如*{border:1px solid black;}
  9. 避免使用@import语句。如果使用@import语句,验证它们是否作为样式表中的第一项出现,以确保它们的优先级低于样式表中的规则。
  10. 通过按优先级升序列出<link>语句和@import语句,验证样式表是否按您想要的顺序加载。级联顺序中同一级别的规则被后来链接或导入的样式表中的规则覆盖。但是请记住,具有较高级联优先级的规则总是优先于具有较低优先级的规则,不管这些规则在样式表中出现的顺序如何,也不管它们是出现在后来链接或导入的样式表中。**
  11. 验证服务器发送text/css作为 CSS 样式表Content-Type头。Mozilla 浏览器拒绝使用样式表,除非它的内容类型是text/css。您可以使用 Web Developer 工具栏并选择菜单选项“查看响应头”,在 Mozilla 浏览器中查看 HTTP 头。
  12. 移除可能已经放在 CSS 样式表中的 HTML 元素,比如<style>。还要确保没有子元素被意外地放置在 HTML 文档头部的<style>元素中。

规范化样式表

因为每个浏览器的默认设置略有不同,所以您可能希望在样式表中构建规则来定义每个元素的基线设置。例如,不同的浏览器给<h1>元素分配不同的大小和边距。通过给<h1>分配你自己的尺寸和边距,你可以在所有浏览器中标准化它的外观。

最简单的方法(也是最容易维护的方法)是为所有元素创建一组基线规则,并将这些规则加载到附加到文档的第一个样式表中。您可以加载一小组规则,将所有元素重置为最简单的样式,如清单 1-2 所示。或者你可以加载一组更广泛的规则,为你的网站创建一个标准的风格,比如清单 1-3 中的那些。你可以在互联网上找到标准的基线规则,比如雅虎的 YUI 重置 CSS 规则(见[developer.yahoo.com/yui/reset/](http://developer.yahoo.com/yui/reset/))。

加载单独的基线样式表会影响页面呈现的速度(参见侧栏“页面加载速度有多快?”).因此,出于性能原因,您可能希望合并样式表或将样式移动到 HTML 文档的<style>部分。

清单 1-2。简单的基线样式表(类似于雅虎的 YUI 重置 CSS)

body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,p, blockquote,th,td { margin:0; padding:0; } table { border-collapse:collapse; border-spacing:0; } fieldset,img { border:0; } address,caption,cite,code,dfn,em,strong,th,var { font-style:normal; font-weight:normal; } ol,ul { margin:1em 0; margin-left:40px; padding-left:0; } ul { list-style-type:disc; } ol { list-style-type:decimal; } caption,th { text-align:left; } h1,h2,h3,h4,h5,h6 { font-size:100%; }

你的网页加载速度有多快?

文档呈现的速度很重要。在 0.5 秒内呈现的网页被认为是即时的;1 秒是快;2 秒是正常的;超过 2 秒变得明显;大约 6 秒是大多数宽带用户所能容忍的。根据经验,查找每个文件的延迟通常需要 0.1 到 0.5 秒,这是在宽带连接上,不包括实际下载文件所需的时间。由于延迟,快速页面通常可以加载三个额外的文件,比如一个样式表、一个 JavaScript 文件和一个图像,而普通页面可以加载大约七个额外的文件。

为了提高性能,浏览器会缓存文件。这可能对后续下载有帮助,但对页面第一次下载没有帮助。此外,只有当服务器将缓存文件的到期日期设置为将来到期时,缓存文件才会提高性能。当缓存文件的刷新日期到期时,浏览器会询问服务器该文件是否已更改。每个文件大约需要 0.1 到 0.5 秒,即使文件没有更改并且不需要再次下载。因此,尽可能将到期日期设定在未来是很重要的。未来多久取决于您预期文件在服务器上更改的频率。问题是,如果您在到期日期之前更改了服务器上的文件,用户将无法获得更新后的文件,因为除非您清除缓存,否则浏览器不会主动询问。

清单 1-3。完成基线样式表

`/* BLOCK ELEMENTS */
html, div, map, dt, form { display:block; }
body       { display:block; margin:8px; font-family:serif; font-size:medium; }
p, dl      { display:block; margin-top:1em; margin-bottom:1em; }
dd         { display:block; margin-left:40px; }
address    { display:block; font-style:italic; }
blockquote { display:block; margin:1em 40px; }
h1 { display:block; font-size:2em;      font-weight:bold;   margin:0.67em 0; }
h2 { display:block; font-size:1.5em;    font-weight:bold;   margin:0.83em 0; }
h3 { display:block; font-size:1.125em;  font-weight:bold;   margin:1em    0; }
h4 { display:block; font-size:1em;      font-weight:bold;   margin:1.33em 0; }
h5 { display:block; font-size:0.75em;   font-weight:bold;   margin:1.67em 0; }
h6 { display:block; font-size:0.5625em; font-weight:bold;   margin:2.33em 0; }
pre{ display:block; font-family:monospace; white-space:pre; margin:1em    0; }
hr { display:block; height:2px; border:1px; margin:0.5em auto 0.5em auto; }

/* TABLE ELEMENTS */
table   { border-spacing:2px; border-collapse:separate;
          margin-top:0; margin-bottom:0; text-indent:0; }
caption { text-align:center; }
td      { padding:1px; }
th      { font-weight:bold; padding:1px; }
tbody, thead, tfoot { vertical-align:middle; }

/* INLINE ELEMENTS */
strong { font-weight:bold; }
cite, em, var, dfn { font-style:italic; }
code, kbd, samp { font-family:monospace; }
ins { text-decoration:underline; }
del { text-decoration:line-through; }
sub { vertical-align:-0.25em; font-size:smaller; line-height:normal; }
sup { vertical-align: 0.5em;  font-size:smaller; line-height:normal; }
abbr[title], { border-bottom:dotted 1px; }

/* LIST ELEMENTS /
ul { list-style-type:disc;    margin:1em 0; margin-left:40px; padding-left:0;}
ol { list-style-type:decimal; margin:1em 0; margin-left:40px; padding-left:0;}
/
remove top & bottom margins for nested lists /
ul ul, ul ol, ul dl, ol ul, ol ol, ol dl, dl ul, dl ol, dl dl
{ margin-top:0; margin-bottom:0; }
/
use circle when ul nested 2 deep /
ol ul, ul ul { list-style-type:circle; }
/
use square when ul nested 3 deep */
ol ol ul, ol ul ul, ul ol ul, ul ul ul { list-style-type:square; }`

Image 提示你可以使用resource://gre-resources/html.css查看 Mozilla Firefox 的内部默认样式表。

二、HTML 设计模式

本章只探讨与 CSS 相关的 HTML。它包含了用 CSS 设计文档样式的基本设计模式。它在高层次上探索 HTML,着眼于解释如何在结构和语义上使用元素。本书中的每个设计模式都是使用结合 CSS 的结构和语义元素创建的。设计模式中使用了四种主要类型的元素:结构块、终端块、多用途块和内联元素。理解这些类型的元素是理解本书中设计模式的关键,也是创建你自己的设计模式的基础。

章节大纲

  • HTML 结构显示了 HTML 元素如何一起工作来创建一个文档。
  • 展示了如何用有效的 XHTML 标记文档。它还指出了为什么使用有效的 XHTML 会使 CSS 样式更加可靠。
  • DOCTYPE 展示了如何使用文档类型来验证文档的编码方式,并探索了什么样的文档类型最适合 CSS 和 HTML。
  • Header Elements 展示了如何创建关于文档的元数据,以及如何将文档链接到支持文档和相关文档。
  • 条件样式表展示了如何加载一个样式表来修复 Internet Explorer 特有的问题。
  • 结构块元素展示了如何在文档中创建结构意义。
  • 终端块元素显示某些块如何具有语义,因为它们包含内容而不是其他块。
  • 多用途块元素展示了某些元素如何用于块结构和语义。
  • Inline Elements 展示了样式如何展现语义标记的含义。
  • Class 和 ID 属性展示了 CSS 如何依靠classid属性来选择元素。它还展示了class属性如何给元素增加意义。
  • HTML 空白显示了如何让空白为你所用,而不是对你不利。

HTML 结构

Image

Image

html 5 规范中包含了其他元素,但是我没有在前面的表格中列出它们,因为它们没有什么语义或结构意义,很少使用,或者有古怪的实现。以下元素样式文本:<i><b><big><small><pre>元素保留空白,但是它不能包含图像、对象、下标或上标。<q>元素根据不同的浏览器自动插入不同的引号。<ins><del>元素将元素标记为插入或删除。框架会给搜索引擎和用户带来问题:<iframe><frameset><frame><noframe>。Internet Explorer 7 不会删除<hr><fieldset><legend>的内置样式,但以后的版本会。此外,从 SEO 的角度来看,传统的框架在显示时索引不好,因为内容通常是在位于单独框架中的控件之外进行索引的。同时,传统的框架集已经相当过时了。最后,<base>改变文档中所有链接的根——只有在你完全理解的情况下才使用它,否则它可能会断开你所有的链接。类似地,HTML5 草案规范中定义的许多其他元素要么还没有在浏览器中实现,要么仍在进行重大修订。

HTML 结构

Image

HTML

`

<head><title>HTML Structure</title>   <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>   <link rel="stylesheet" href="site.css" media="all" type="text/css"/>   <link rel="stylesheet" href="page.css" media="all" type="text/css"/>   <link rel="stylesheet" href="print.css" media="print" type="text/css"/>   <!--[if lte IE 6]>   <link rel="stylesheet" href="ie6.css" media="all" type="text/css"/>   <![endif]--> </head> <body> <noscript>Show this when script cannot run.</noscript> <div>   <h1>HTML Structure</h1>

Paragraph


        
  1. Ordered List Item

  2.     
  3. Ordered List Item

  4.   

  

        
  • Unordered List Item

  •     
  • Unordered List Item

  •   

  

    
Definition Term

    
Definition Term

    
Definition Data

    
Definition Data

  


    
    
      
      
    
    
    
      
      
    
    
    
    
      
      
         
    
    
  
Table Caption
row1-col1row1-col2
row3-col1row3-col2


    


    


    


    


    


    


    


    
    
  

Division within a Division Link
    alt text
    
      left
      right
    

span
    em
    strong
    cite
    code
    kbd
    samp
    var
    abbr
    dfn
    sub
    sup
    backwards`

`    
  


  

    

      

My blog post


        
      


    

    

The article element represents a self-contained composition in page that is independently distributable or
      reusable, e.g., in syndication.


    
  

  

    

First section heading


      The section element represents a generic section of a document (thematic grouping of
content).
    


  

  

    

And one more section

A page could be split into sections for an introduction, news items, contact
information, etc.


  

  
  
address

`

CSS

/* There are no CSS styles attached to this document. */

HTML 结构

Image

XHTML

Image

有效的 XHTML

`


 XHTML
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <link rel="stylesheet" href="page.css" media="all" type="text/css" />
 
 
  

XHTML

Paragraph


Break
  
  1. Ordered List Item
  2.    
  3. Ordered List Item
  4.    

  
Definition Term
     
Definition Data
     

 
`

有效的 HTML

`

 HTML           

HTML

**

**Paragraph **
**Break   

    **
  1. **Ordered List Item   **
  2. **Ordered List Item
  
**
**Definition Term     **
**Definition Data   
`

XHTML

Image

文档类型

HTML

`

`

内容类型与文档类型

Web 服务器用一个 MIME 内容类型来标识它们提供的每个文档。MIME 代表多部分互联网邮件扩展。内容类型在文档的 HTTP 头中标识。浏览器根据文档的 MIME 内容类型决定如何处理文档。当它获得一个内容类型为"text/html"的文档时,它将该文档呈现为 HTML。

根据 W3C 题为“XHTML 媒体类型”([www.w3.org/TR/xhtml-media-types/](http://www.w3.org/TR/xhtml-media-types/))的说明,web 服务器可以提供以下三种内容类型之一的 XHTML。

  • 只要您不希望浏览器将一个 XHTML 文档视为 XML,并且不包含来自其他 XML 名称空间(如 MathML)的内容,就可以将该文档用作"text/html"。接收具有这种内容类型的 XHTML 文档的浏览器将该文档视为 HTML。
  • XHTML 应该作为"application/xhtml+xml"。不幸的是,Internet Explorer 7 和早期版本拒绝显示以这种方式提供的页面。
  • XTHML 可以作为"application/xml"或者"text/xml"。不幸的是,Internet Explorer 7 和更早的版本将这样的文档识别为通用 XML,这意味着它们忽略了所有的 XHTML 语义。这意味着链接和表单不起作用,并且呈现文档需要更长的时间。

Gecko 浏览器在完全下载并且完全没有编码错误之后,只呈现一个使用 XML 内容类型的文档。它还以严格模式呈现文档,而不考虑其文档类型(见[www.mozilla.org/docs/web-developer/faq.html#accept](http://www.mozilla.org/docs/web-developer/faq.html#accept))。

目前,为 XHTML 网页提供服务的最可靠的内容类型是"text/html"。这告诉浏览器将文档呈现为 HTML。W3C 支持这种方法,它在所有主流浏览器中都运行良好。它之所以有效,是因为浏览器不验证 HTML。它们解析网页的方式允许它们显示任何版本的 HTML 和 XHTML——包括包含错误的文档。与浏览器处理 XHTML 文档的方式形成对比,当出现错误时,XML 规则禁止浏览器呈现整个 XHTML 文档——即使是由意外输入造成的最小错误!这样的精度对于计算机对计算机的交易来说是必不可少的,但是对于人工生成的网页来说就不好了。

文档类型

Image

表头元素

HTML

`


  Header Elements


  
  
  
  


  
  


  


  


  

  

Header Elements

  

`

表头元素

Image

条件样式表

Image

在 Firefox 中呈现,没有条件样式表

Image

使用条件样式表在 Internet Explorer 中呈现

HTML

`

Conditional Stylesheet
  
  
  
  
 


  

Conditional Stylesheet


  

In Internet Explorer 6, this box has a border and background.


 

`

CSS page.css

***.test  { font-size:18px; }**

CSS ie6.css

***.test  { border:2px solid black; background-color:gold; }**

条件样式表

Image

结构块元素

HTML 模式

`
  


        
  1.                             

  2.     
  3.   One or more list items...

  4.   


        
  •                             

  •     
  •   One or more list items...

  •   


    
                                  

    
  One or more definition terms...

    
                                  

    
  One or more definitions...      

  


   
   
    
      
        
        

      

    

    

      

        

        

      

    

    

      

        

        

      

    

  
One optional caption per table.
One or more header cells in a row...   One or more data cells  in a row...   
One or more rows in a row group...                                           
Zero or more row groups in a table...                                        

...
`

结构块元素

Image

端子板元件

Image

HTML

`

Terminal Block Elements


  Headings, paragraphs, blockquotes, definition terms, addresses,
  and table captions are terminal block elements. They may contain only content.
  An HTML validator will declare a document invalid if you attempt
  to put block elements inside terminal blocks.

   A blockquote is a terminal block.

  **
NOTE:
**   
The content of terminal blocks is always inline.

      An address is a terminal block.   

** **  
Table caption is a terminal block.
`

端子板元件

Image

多用积木元件

Image

HTML

`

 
  

Multi-purpose Block Elements

 


      This content is inside a list but is not inside a list item like it should be.
      
  1. This content is properly nested in a list item.

  2.   This content outside a list item invalidates and destroys the structure of a list.


  Compare the mixed content in this division with that of the preceding list.
**  
This content is inside a nested structural division.
**
  This mixed content is not invalid, but it destroys the block structure
  and requires a browser to create anonymous blocks in which to render it.

 
      
  •        
  •   
  •  
`

多用积木元件

Image

行内元素

Image

HTML

Inline Elements


 

Italicized


 <em>        emphasized                   

 <cite>      citation                 

 <var>       computer variable          

 <dfn>       definition                 

Bold


 <strong>    strongly emphasized  

Monospace


 <code>      computer code            

 <kbd>       key press                  

 <samp>      sample computer output   

Underlined


 <a>         a                     

  <abbr>      abbreviation  

Vertical-aligned


 <sup>       superscript1               

 <sub>       subscript1                 
`

行内元素

Image

类和 ID 属性

Image

HTML

Class and ID Attributes

<div id="hcalendar1" class="vevent">
  <h3 class="summary">Calendar Event Summary

<p class="description">Calendar Event Description

From
   <span class="dtstart" title="2007-05-01T08:30:00-05:00"
    >01 May 2007 from 8:30am EST to
   <span class="dtend" title="2007-05-01T09:30:00-05:00"
    >9:30am EST

Location:  <span class="location">Meeting Location


  

Booked by: <span class="uid">globally-unique-id.host.com
     on <span class="dtstamp" title="20070101T231000Z"
         >Jan 1, 2007 at 6:00pm


 

See microformats.org
  for more information about microformats.

`

CSS

`*.vevent p          { margin:0 0 5px 0; font-size:0.9em; }
*.vevent h3         { margin:0 0 5px 0; }
*.vevent *.location { font-style:italic; }
*.vevent *.uid      { font-family:monospace; }
*.vevent *.dtstart,
*.vevent *.dtend,
*.vevent *.dtstamp  { color:green; }

#hcalendar1 { margin:5px; border:1px solid black; padding:10px; }`

类和 ID 属性

Image

HTML 空白

Image

HTML

`

HTML Whitespace

     start    middle     **     **                                            end      

Controlling Where Whitespace Collapses

**start  middle end**—inside element

**start middle  end**—outside element

Embedding Whitespace Inside Tags

 

start**middle**end

Embedding Space Entities

&zwnj;   **‌**      &thinsp; ** **    &nbsp;   ** **      &ensp;   ** **      &emsp;   ** **     `

CSS

`em { padding-left:50px; }
p { font-family:monospace; font-size:18px; }

*.border { font-weight:bold;
  border-left:2px solid black; border-right:2px solid black; }`

HTML 空白

Image

三、CSS 选择器和继承

本章介绍了选择样式元素的设计模式。

因为选择器设计模式很简单,所以我分组讨论选择器设计模式,而不是一次讨论一个。这使得比较和对比选择器的相关形式变得容易。因此,尽管这一章只有六个例子,但它包含了十三个不同的设计模式。

本章包含了继承,因为它只是一种选择后代元素的内置方式。继承与后代选择器密切相关。可视继承模式包含在本章中,因为它是一种本质上可视的继承形式。

章节大纲

  • 类型、类和 ID 选择器展示了如何通过标签、类和 ID 选择元素。
  • 位置和组选择器显示了如何通过元素在文档中的嵌套方式来选择元素。它还展示了如何将多个选择器应用于同一组规则。
  • 属性选择器展示了如何根据属性选择元素。
  • 伪元件选择器显示如何选择端子板元件的第一个字母或第一行。
  • 伪类选择器展示了当一个超链接未被访问、被访问、被鼠标悬停、或者因为用户用鼠标点击它而获得焦点时,如何设计它的样式。
  • 子类选择器展示了如何使用类和子类将多个样式应用到同一个元素。
  • 继承展示了如何通过分配给祖先的规则来设计元素的样式。
  • 视觉继承显示元素如何视觉继承其父元素的背景。

类型、类别和 ID 选择器

Image

HTML

Type, Class, and ID Selectors

The type selector, p, adds a border to all paragraphs.


  The class selector, *.my-class1, adds padding.


  The class selector, *.my-class2, adds letter-spacing.


  The ID selector, #my-id, adds a background color.

`

CSS

`p { border:2px solid black; }

*.my-class1 { padding:10px; }
*.my-class2 { letter-spacing:0.11em; }

#my-id { background-color:gold; }`

类型、类别和 ID 选择器

Image

Image

位置和组选择器

Image

HTML

Position and Group Selectors

p.my-class


 

  

       
  1. div ol li

  2.    
  3. div ol li

  4.    

  5.     

    div ol li p.my-class


       

  6.   

 

CSS
/* Group Selectors */
p,ol,li { border:1px solid black; padding-left:10px; font-family:monospace;
  margin:10px; margin-left:0px; }
ol { margin-left:0px; padding-left:40px; margin-top:20px; }

/* Position Selectors */
div .my-class { font-size:1.2em; font-weight:bold; }  / Descendant  Selector /
#my-id   p { background-color:gold; }                  /
Descendant  Selector /
#my-id > * { border:3px solid black; }                 /
Child       Selector */

:root {background: white;} /* Root Selector /
li:nth-child(2n+1) /
Nth-child Selector /
li:nth-last-child(-n+2)    /
Nth-last-child Selector /
li:nth-of-type(2n+1) { float: right; } /
Nth-of-type Selector */

li:nth-last-of-type(2n+1) { float: right; } /* Nth-last-of-type Selector /
li:first-child { font-weight:bold; color:red; }        /
Fiwrst-child Selector /
li:last-child { font-weight:bold; color:red; }        /
Last-child Selector /
ul li:first-of-type {color: red} /
  First-of-type Selector /
tr > td:last-of-type  /
  Last-of-type Selector /
li:only-child /
Only-child Selector /
div:only-of-type /
Only-of-type Selector /
p:empty {display: hidden} /
Empty Selector /
li + li { font-style:italic; color:blue; }             /
Sibling     Selector */`

位置和组选择器

Image

属性选择器

Image

HTML

Attribute Selectors

This is a paragraph without the title attribute.


  p[title] selects all paragraphs containing a title attribute.


  p[title~="paragraph"] selects all paragraphs with a
  title attribute containing the word, paragraph.


  p[title="#4   paragraph"] selects all paragraphs with a
  title attribute containing the exact text, #4   paragraph. Matches
  are case-sensitive and must match letter-for-letter including whitespace.

<a href="http://www.example.com” target="_blank" hreflang="en-GB">hello`

CSS

`code { white-space:pre; }

p[title] { padding:5px 10px; border:1px solid gray; }
p[title~="paragraph"] { background-color:gold; }
p[title="#4   test paragraph"] { font-weight:bold; }
a[href="http://www.example.com"][target="_blank"] { font-weight:bold; }
p[type^="#4"] {color: grey }
a[href$=".com"] { font-weight:bold; }
p[title*="test"] { font-weight:bold; }`

属性选择器

Image

伪元素选择器

Image

HTML

Pseudo-element Selectors

first-letter selects the first letter, and
    first-line selects the first line of a terminal block element,
    like this paragraph.

Pseudo-element selectors do not work on inline elements.


  
Pseudo-element selectors do not work on structural block elements.

 
`

CSS

`p:first-line { font-weight:bold; word-spacing:2px; letter-spacing:1px; }
p:first-letter { font-size:48px; }
span:first-line { font-weight:bold; word-spacing:2px; letter-spacing:1px; }
span:first-letter { font-size:48px; }

dl:first-line { font-weight:bold; word-spacing:2px; letter-spacing:1px; }
dl:first-letter { font-size:48px; }`

伪元素选择器

Image

伪类选择器

Image

HTML

Pseudo-class Selectors


  a:link -- unvisited link
  a:visited -- visited link
  a:hover -- mouse hovering
  a:active -- visiting a link
 

`

CSS

`a { padding:3px 10px; margin:20px 10px; text-decoration:none;
  display:block; width:260px;
  border-left:1px solid dimgray; border-right:2px solid black;
  border-top:1px solid dimgray;  border-bottom:2px solid black;  }

a:link { color:black; background-color:white; }
a:visited { color:gray;  background-color:white; }
a:hover { color:white; background-color:green; }
a:active, a:focus { color:green; background-color:gold; }`

伪类选择器

Image

子类选择器

Image

HTML

Subclass Selector


  <p class="button square">Square


  <p class="button rounded">Rounded


  <p class="button go">Go


 
`

CSS

`*.button { width:175px; padding:3px 10px; margin:20px 0; text-align:center;
  font-weight:bold; margin-left:50px; line-height:normal; }

*.button.square  { color:darkblue; background-color:gold;
  border-left:1px solid dimgray; border-right:2px solid black;
  border-top:1px solid dimgray;  border-bottom:2px solid black; }

*.button.rounded { color:darkblue; background-color:white;
  line-height:45px; margin-top:30px;
  background:url("oval.gif") no-repeat center center; }

*.button.go { background-color:white; line-height:26px;
  text-indent:-9999px; font-size:10px;
  background: url("go.jpg") no-repeat center center; }`

子类选择器

Image

继承

Image

HTML

`
 

Inheritance


  


   
    
     - This span inherits font from its ancestor, <body>.

     - It inherits line-height from its ancestor, <div>.  

     - It inherits letter-spacing from its ancestor, <p>.

     - It inherits italics from its ancestor, <em>,
       but it is also directly assigned to font-style:normal , which
       overrides its inherited italics.
    
   

  


 

`

CSS

**body** { font-family:verdana,arial,sans-serif; font-size:18px; } **div** { line-height:2em; } **p** { letter-spacing:0.8px; } **em** { font-style:italic; } **span** { font-style:normal; }

继承

Image

视觉继承

Image

HTML

 <h1>Visual Inheritance</h1>  **<div>**   <p>    <label>     <span>      - This span is nested inside a label, a paragraph, and a division. <br />      - The division is assigned a background color, padding, and a border. <br />      - Since the span, label, and paragraph default to a transparent background        color and have no border, they "visually inherit" the        background, padding, and border of the division. <br />      - Once you assign a background to an element, it no longer visually inherits        the background of its parent—like this <code>&lt;code&gt;</code> element.     </span>    </label>   </p>  </div>

CSS

`div { background-color:gold; color:black; padding:10px 20px;
  border-left:1px solid gray; border-right:2px solid black;
  border-top:1px solid gray; border-bottom:2px solid black; }

p { background-color:transparent; background-image:none; }
label { background-color:transparent; background-image:none; }
span { background-color:transparent; background-image:none; }

code { background-color:firebrick; color:white; }`

视觉继承

Image

四、盒子模型

CSS 中的基本设计模式是盒子模型。盒子模型定义了元素如何呈现为盒子。有六种主要类型的盒子:内嵌、内嵌块、块、表、绝对和浮动。浏览器将每个元素呈现为这些框中的一个。有些元素呈现在这些框的变体中,如列表项或表格单元格。例如,list-item是浏览器自动创建的带有内嵌标记的块框,table-cell是不支持边距的块框。

您可以使用display属性将元素呈现为不同类型的框。您可以使用position:absoluteposition:fixed将任何元素呈现为绝对框。您可以使用float:leftfloat:right规则将任何元素呈现为浮动框。

这是盒子模型三章中的第一章。本章解释了六种主要的盒子类型。第五章介绍范围,由widthheight控制。范围控制长方体是收缩到其内容、调整大小还是拉伸到其容器的侧面。第六章介绍盒模型属性:marginborderpaddingbackgroundoverflowvisibilitypage-break-beforepage-break-after。背景、可见性和分页符在所有框中都是一样的。除了内嵌以外,边框、填充和溢出在所有框中都是一样的。宽度、高度和边距在每种类型的框中有不同的作用。

章节大纲

  • Display 展示了如何将一个元素呈现为一个内嵌框、一个块框、一个内嵌块框、一个列表项框、一个表格框,或者根本不呈现。
  • 盒子模型介绍了所有类型盒子的通用盒子模型。
  • 内嵌框展示了内嵌框是如何工作的。
  • 内嵌块框展示了内嵌块和被替换的内嵌块是如何工作的。
  • 块盒显示块盒如何工作。
  • 表格框展示表格框如何工作。
  • 绝对框展示了绝对框和固定框是如何工作的。
  • 浮动框展示了浮动框的工作原理。

显示

Image

HTML

Display

display:inline
 

p

p

p


 
  1. li
  2. li
  3. li

 
tdtd
tdtd

strong
display:inline-block
  

em display:block em

dfn display:list-itemdfn


<img
src="star.gif" alt="star" /> display:none`

CSS

`p,ol,li,table { display:inline; }
strong { display:inline-block; width:250px; }
em { display:block; }
dfn { display:list-item; list-style-type:square; }
img { display:none; }

*.ul { padding-left:15px; }`

显示

Image

箱子模型

Image

HTML

Box Model

`

CSS

`*.box { display:static;
  overflow:visible;
  visibility:visible;
  width:160px;
  height:150px;
  padding:30px;
  border-top: 30px solid gray; border-bottom:30px solid black;
  border-left:30px solid gray; border-right: 30px solid black;
  margin-left:230px; margin-top:80px;
  background-color:gold; }

/*  Nonessential rules are not shown. */`

箱子模型

Image

内嵌框

Image

HTML

Inline Box


   BEFORE

← Left   ↑ Top  
         Bottom ↓   Right →

AFTER
 

`

CSS

`*.box { display:inline; visibility:visible;
   line-height:100px;
   margin:0 100px;
   padding:20px 120px;

border-top:   5px solid gray;
   border-bottom:5px solid black;
   border-left:  5px solid gray;
   border-right: 5px solid black;

background-color:gold; }

/*  Nonessential rules are not shown. */`

内嵌框

Image

内嵌块框

Image

HTML

Inline-block Box


   BEFORE
   star
   AFTER

BEFORE
   Inline element displayed as an inline block.
   AFTER
 

`

CSS

`*.replaced-box { display:inline-block;
  overflow:visible; visibility:visible;
  width:51px; height:52px;
  margin:10px 100px; padding:10px 120px; }

*.inline-box { display:inline-block;
  overflow:visible; visibility:visible;
  width:275px; height:52px;
  margin:10px 100px; padding:10px 10px; }

/* Nonessential rules are not shown.
  See Inline Box for border and background properties. */`

内嵌块框

Image

块框

Image

HTML

Block Box


   
BEFORE


Top
← Left      
        Right →
Bottom

AFTER

 
`

CSS

`*.box { display:block;
  overflow:auto; visibility:visible;
  width:220px; height:100px;
  margin:10px auto; padding:10px; }

/*  Nonessential rules are not shown.
   See Inline Box for border and background properties. */`

块框

Image

表格框

Image

HTML

Table Box Model


 

   
BEFORE


     
   
Table Cell Table Cell

AFTER

 
`

CSS

`*.table {
  border-collapse:separate; table-layout:auto; visibility:visible;
  width:auto; height:auto; margin:30px 50px; }

*.cell { width:auto; height:auto; padding:20px 50px; overflow:hidden; }

/*  Nonessential rules are not shown.
  See Inline Box for border and background properties. */`

表格框

Image

绝对框

Image

HTML

Absolute Box


   
BEFORE

   
ABSOLUTE BEFORE


Top
← Left    
        Right →
Bottom

ABSOLUTE AFTER

   
AFTER

 
`

CSS

`*.container { position:relative; }

*.box { position:absolute; overflow:auto; visibility:visible;
  z-index:auto; left:0; right:auto; top:0; bottom:auto;
  width:220px; height:100px;
  margin:10px; padding:10px;}

*.before {width:100px; height:auto; left:400px; right:auto; top:100px; bottom:auto;}
*.after {width:100px; height:auto; left:auto;  right:0px;  top:auto; bottom:0px; }

/*  Nonessential rules are not shown.
  See Inline Box for border and background properties. */`

绝对框

Image

浮动框

Image

HTML

Floated Box


   
BEFORE

   
FLOAT BEFORE


Top
← Left    
        Right →
Bottom

FLOAT AFTER

   
AFTER

 
`

CSS

`*.box { float:left;  overflow:auto; visibility:visible;
  width:220px; height:100px;
  margin:10px; padding:10px; }

*.small { width:75px; height:auto; }

/*  Nonessential rules are not shown.
    See Inline Box for border and background properties. */`

浮动框

Image

五、盒子模型的延申

这是关于盒子模型的三章中的第二章。它展示了如何调整盒子的大小、收缩和拉伸。前一章讨论了六种主要的盒子类型:内嵌、内嵌块、块、表、绝对和浮动。下一章讨论设置盒子样式的属性。

每种类型的盒子工作方式不同。本章中的设计模式展示了如何将宽度和高度应用于每种类型的盒子,以调整其大小、进行包膜或拉伸。水平和垂直尺寸是独立的。您可以自由组合不同的垂直和水平设计模式。例如,可以水平拉伸和垂直包膜。

章节大纲

  • Width 对比 Width 如何调整大小、收缩或拉伸每种类型的盒子。
  • Height 对比了高度如何调整、收缩或拉伸每种类型的盒子。
  • 显示了如何设置一个元素的高度或宽度。当您手动为元素指定高度和/或宽度时,会调整元素的大小。例如,您可以使用height:50%将元素的高度调整为其容器高度的 50%。
  • Shrinkwrapped 展示了如何将一个元素的宽度或高度缩小到其内容的大小。例如,height:auto使静态块元素的高度自动扩展以适应其行的总高度,而width:auto使绝对元素的宽度收缩以适应其最宽行的宽度。
  • Stretched 展示了如何将一个元素的宽度或高度拉伸到其容器的两侧。例如,width:auto使静态块元素的宽度自动扩展以适合其容器的宽度。例如,top:0bottom:0height:auto会使一个绝对元素自动扩展以适应其容器的高度。拉伸元素的左侧与其容器的左侧对齐,其右侧与容器的右侧对齐。同样,它的顶部和底部与其容器的顶部和底部对齐。

宽度

Image

CSS

`*.static-inline-shrinkwrapped { width:auto; }
*.replaced-inline-shrinkwrapped { width:auto; }
*.replaced-inline-sized { width:35px; }
*.replaced-inline-stretched { width:100%; }

*.static-block-sized { width:300px; }
*.static-block-stretched { width:auto; }

*.table-shrinkwrapped { width:auto; }
*.table-sized { width:300px; }
*.table-stretched { width:100%; }

*.float-shrinkwrapped { width:auto; float:left; }
*.float-sized { width:300px; float:left; clear:both; }
*.float-stretched { width:100%; float:left; clear:both; }

*.absolute-shrinkwrapped { width:auto; left:0; right:auto; position:absolute; }
*.absolute-sized { width:300px; left:0; right:auto; position:absolute; }
*.absolute-stretched { width:auto; left:0; right:0; position:absolute; }`

宽度

Image

高度

Image

CSS

`*.replaced-inline-shrinkwrapped { height:auto; }
*.replaced-inline-sized { height:65px; }
*.replaced-inline-stretched { height:100%; }

*.block-shrinkwrapped { height:auto; }
*.block-sized { height:65px; }
*.block-stretched { height:100%; }

*.table-shrinkwrapped { height:auto; }
*.table-sized { height:65px; }
*.table-stretched { height:100%; }

*.float-shrinkwrapped { height:auto; float:left; }
*.float-sized { height:65px; float:left; }
*.float-stretched { height:100%; float:left; }

*.absolute-shrinkwrapped { height:auto; top:0; bottom:auto; position:absolute; }
*.absolute-sized { height:65px; top:0; bottom:auto; position:absolute; }
*.absolute-stretched { height:auto; top:0; bottom:0; position:absolute; }`

高度

Image

大小合适

Image

HTML

 <h1>Sized</h1>  <div class="gp">Positioned Grandparent    <div class="parent">Non-positioned Parent      <div **id="float"** class="z">Sized Float</div>      <div **id="static"** class="z">Sized Static</div>      <table **id="table"** class="z"><tr><td>Sized Table</td></tr></table>      <span **id="abs"** class="z">Sized Absolute        <img **id="star"** src="star.gif" alt="star" /></span>    </div>  </div>

CSS

`*.z { padding:5px; border:5px solid black; }

float

static

table

abs

star

/*  Nonessential rules are not shown. */`

大小合适

Image

畏缩不前

Image

HTML

Shrinkwrapped

Positioned Grandparent   
Non-positioned Parent     Shrinkwrapped Float     Shrinkwrapped Static Inline
    star     
Vertically Shrinkwrapped Static Block
    
Shrinkwrapped Table
    Shrinkwrapped Absolute   
 
`

CSS

`#float   { width:auto;  height:auto; float:left; }

inline

star    

block

table  

abs    

/*  Nonessential rules are not shown. */`

畏缩不前

Image

Image

拉伸

Image

HTML

 <h1>Stretched</h1>   <div class="gp">Positioned Grandparent    <div class="parent">Non-positioned Parent      <span  **id="inline"** class="s">Cannot stretch a static inline</span>      <div   **id="sized"**><img id="star" src="star.gif" alt="star" /></div>      <div   **id="block"** class="s">Horizontally Stretched Static Block</div>      <table **id="table"** class="s"><tr><td>Horiz. Stretched Table</td></tr></table>      <div   **id="abs-v"** class="s">Vertically Stretched Absolute</div>      <span  **id="abs-h"** class="s">Horizontally Stretched Absolute</span>      <span  **id="float"** class="s">Almost Stretched Float</span>    </div>  </div>

CSS

`#star { width:100%; height:100%; }

block

table

abs-v

abs-h

float

/*  Nonessential rules are not shown. */`

拉长

Image

Image

六、盒子模型属性

本章展示了盒子模型属性如何设计各种盒子的样式。这些是基本的设计模式。

边距、边框和填充设计模式包含了对比每种类型的框中每个属性如何工作的例子。他们的主要目的是在一个地方对比相同的属性在不同的上下文中意味着不同的东西。当使用这本书作为参考时,您可能还希望参考边距、边框和填充设计模式,以确定哪种类型的元素、框和属性将满足您的需要。

章节大纲

  • 边距对比了不同类型的盒子边距的不同作用。它显示了边距如何改变元素相对于其容器和兄弟元素的位置。
  • Border 对比不同类型盒子的边框效果。它显示了边框如何以类似于边距的方式改变元素的位置,以及在某些方面不同于边距。
  • 填充对比不同类型盒子的填充方式。它展示了填充对于边框和边距的作用方式。
  • 背景展示了如何给一个元素的背景分配颜色。它还展示了如何使用平铺图像作为背景。您可以上下平铺图像、仅横向平铺或仅向下平铺,或者仅显示图像一次。您可以将图像放置在背景中的特定位置。您还可以指示图像是与内容一起滚动,还是保持在固定位置。
  • 溢出展示了如何隐藏溢出的内容,显示它,或者显示滚动条。
  • Visibility 展示了如何隐藏一个元素,同时在流中为它留下一个占位符。
  • 分页符展示了如何在一个元素之前或之后插入一个分页符。它还显示了如何打印空白页。

边距

Image

CSS

`*.before { margin:0; }

*.after { margin-top:10px; margin-bottom:0;
  margin-left:30px; margin-right:10px; }

/* Nonessential rules are not shown.
   HTML code is omitted to allow the example to fit on one page. */`

边距

Image

边框

Image

CSS

`*.before { border:1px solid black; }

*.after { border-top:10px solid dimgray;  border-bottom:1px solid black;
  border-left:30px solid black;   border-right:5px solid black; }

/* Nonessential rules are not shown.
    HTML code is omitted to allow the example to fit on one page. */`

边框

Image

Image

Image

填充

Image

CSS

`*.before { padding:0; }

*.after { padding-top:10px;  padding-bottom:0;
  padding-left:30px; padding-right:10px; }

/* Nonessential rules are not shown.
   HTML code is omitted to allow the example to fit on one page. */`

填充

Image

背景

Image

HTML

 <h1>Background</h1>  <p>**<span class="no-bg">**&nbsp;</span>No background</p>  <p>**<span class="bg-color">**&nbsp;</span>Background color</p>  <p>**<span class="bg-image">**&nbsp;</span>Background image not tiled</p>  <p>**<span class="bg-repeat">**&nbsp;</span>Background image tiled</p>  <p>**<span class="bg-rx">**&nbsp;</span>Background image repeat-x</p>  <p>**<span class="bg-ry">**&nbsp;</span>Background image repeat-y &rarr;</p>  <p>**<span class="bg-pos-lt">**&nbsp;</span>Background image center bottom</p>  <p>**<span class="bg-pos-rb">**&nbsp;</span>Background image right bottom</p>

CSS

`p { margin-left:240px; margin-top:0px; margin-bottom:10px; }
span { margin-left:-230px; margin-right:30px; padding-left:195px; font-size:19px;
  background-position:left bottom; background-repeat:no-repeat;
  background-color:black; background-image:url("star.gif"); }

*.no-bg { background-image:none;  background-color:transparent; }
*.bg-color { background-image:none;  background-color:black; }
*.bg-image { background-repeat:no-repeat; }
*.bg-repeat { background-repeat:repeat; }
*.bg-rx { background-repeat:repeat-x; }
*.bg-pos-lt { background-position:center bottom; }
*.bg-pos-rb { background-position:right bottom; }
*.bg-ry { background-repeat:repeat-y; background-position:center top;
  padding-left:22px; float:right; height:263px; margin:0px;
  position:relative; top:-170px; }`

背景

Image

溢出

Image

HTML

 <div id="ex1">   <h1><code>overflow:visible</code></h1>   <p class="ex1" >     <span class="big">OVERFLOW</span> <br />     <span class="nowrap">The text in this span does not wrap!</span>     <select size="2">       <option>select me</option>       <option selected="selected">select me</option>     </select><br />     <span>Vertical Overflow.</span>   </p>  </div>

CSS

`*.ex1 { overflow:visible; }
*.ex2 { overflow:hidden; }
*.ex3 { overflow:scroll; }
*.ex4 { overflow:auto; }

/*  Nonessential rules are not shown.  */`

溢出

Image

能见度

Image

HTML

`

Visibility

There is hidden content here: ****   You can't see it, because it's styled with visibility:hidden,   but you can see where it would have been rendered.

There is visible content here: **CAN YOU SEE ME NOW?** You can see it, because it's styled with visibility:visible.

`

CSS

`span { padding:4px; background-color:white;
  border-left:1px solid gray; border-right:2px solid black;
  border-top:1px solid gray; border-bottom:2px solid black; }
p  { background-color:gold; padding:10px; line-height:1.5em; }

*.hidden { visibility:hidden; }
*.visible { visibility:visible; }

span:hover { visibility:hidden; }`

能见度

Image

分页

Image

HTML

 <div class="page-break-after">Page break after this element. </div>  **<div class="page-break-after">Page break after this element. </div>**  **<div class="page-break-before">Page break before this element.</div>**

CSS

*.page-break-before { page-break-before:always; } *.page-break-after { page-break-after:always; }

打印预览

Image

分页

Image

七、定位模型

这是关于定位的三章中的第一章。本章介绍 CSS 定位模型。第八章展示了如何缩进、偏移和对齐元素。第九章结合这些技术创建高级定位设计模式。

章节大纲

  • 定位模型介绍并演示六种定位模型。
  • 定位解释、演示和对比position属性的四个值:staticabsolutefixedrelative
  • 最近定位的祖先展示了如何相对于任何祖先元素定位绝对框,而不仅仅是元素的父元素。
  • 堆叠环境展示了如何将定位好的盒子堆叠在静态元素的前面或后面以及彼此之间。
  • Atomic 解释了如何在块中呈现内联内容,而不是在块中呈现
  • 静态解释正常流程的基础。
  • Absolute 显示了如何从正常流中移除任何元素,并相对于其最近定位的祖先的边界内的对其进行绝对定位。
  • 固定显示如何从正常流程中移除任何元素,并相对于视口绝对定位。
  • Relative 展示了如何使用相对定位来控制堆叠顺序,或者偏移一个元素而不影响其形状或其他元素的位置。
  • Float and Clear 展示了如何从正常流中移除一个元素,并将其浮动到其父元素的左侧或右侧。它还展示了如何清除元素,使它们位于浮动的左侧、右侧或两侧。
  • 相对浮动展示了如何相对定位一个浮动。

定位车型

Image

HTML

`

Positioning Models

**

Before

**   

StaticAbsolute     FixedRelative     FloatRelative Float

**

After

**   

    Static     **Absolute     fixed<**/span>     relative<**/span>     float<**/span>     **Relative Float

`

CSS

*.centered { width:380px; margin-left:auto; margin-right:auto; } *.static { **position:static;** } *.absolute { **position:absolute;** top:20px; left:215px; } *.fixed { **position:fixed;** bottom:20px; right:5px; } *.relative { **position:relative;** top:20px; left:30px; } *.float { **float:right;** }

定位车型

Image

摆好位置

Image

HTML

Positioned


 <div class="relative" id="canvas">
  <p class="static">Static Positioned


  <p class="static">This text contains a relatively positioned span that is
    <span class="relative offset">offset from its normal position.


  <em  class="absolute">Absolutely Positioned
  <img class="fixed1" src="star.gif" alt="star" />
  <p   class="fixed2">Fixed Positioned

`

CSS

`div,p,em { margin:10px; padding:10px; background-color:white;
  border-left:1px solid gray; border-right:2px solid black;
  border-top:1px solid gray; border-bottom:2px solid black; }

*.static { position:static; }
*.relative { position:relative; left:auto; top:auto; bottom:auto; right:auto; }
*.absolute { position:absolute; left:35%; top:-40px; }
*.fixed1 { position:fixed; z-index:20; right:5px; bottom:35px; }
*.fixed2 { position:fixed; z-index:10; right:0px; bottom:0;
  width:100px; margin:0;}

*.offset  { bottom:-15px; left:-20px; }

canvas

/*  Nonessential rules are not shown. */`

摆好位置

Image

定位最近的祖先

Image

HTML

`

Closest Positioned Ancestor

Non-positioned Great-grandparent **  
Absolute #1 Bottom Right **    **Nested Absolute
  
Positioned Grandparent     
Non-positioned Parent       ****Absolute #2 Bottom Right          ****Nested Absolute     
`

CSS

`*.static { position:static; }
*.relative { position:relative; }
*.absolute { position:absolute; }

*.sized { width:230px; height:70px; }
*.bottom-right { bottom:0; right:0; }
*.offset { left:45px; top:30px; }

/*  Nonessential rules are not shown. */`

定位最近的祖先

Image

堆叠上下文

Image

HTML

`

Stacking Context

  
1\. Background and Borders of Stacking Context #1     
z-index:2
  2\. Absolute z-index:-999   
3\. Static Block
    4\. Static Float     5\. Static Span

    6\. Relative Span z-index:0     7\. Absolute z-index:999   
`

CSS

`*.stacking-context1 { z-index:2; position:absolute; left:10px;  top:70px;  }
*.stacking-context2 { z-index:1; position:absolute; left:223px; top:120px; }

*.level2 { z-index:-999; position:absolute; }
*.level3 { position:static; }
*.level4 { float:left; }
*.level5 { position:static; }
*.level6 { z-index:0; position:relative; }
*.level7 { z-index:999; position:absolute; }

/*  Nonessential rules are not shown. */`

堆叠上下文

Image

原子

Image

HTML

`

Atomic

Layered   **

Static Overlapping Block

  **

Static Overlapping Block

  **
Overlapping Table
Atomic   

Relative Overlapping Block

  

Fixed Overlapping Block

  

Absolute Overlapping Block

`

CSS

`*.static { position:static; }
*.overlap { margin-top:-22px; }

*.relative { position:relative; }
*.fixed { position:fixed; margin-top:-16px; }
*.absolute { position:absolute; top:65px; }

/*  Nonessential rules are not shown. */`

原子

Image

静态

Image

HTML

`

Static

Positioned Grandparent    
Non-positioned Parent      
Sized Static Block
     
Stretched Static Block
     
Shrinkwrapped Static Inline                                 Shrinkwrapped Static Inline                                 Shrinkwrapped Static Inline                                 Shrinkwrapped Static Inline      
`

CSS

`span { position:static; margin:40px; line-height:32px;
  padding:3px; border:2px solid black; background-color:yellow; }

zs { position:static;  width:120px; height:100px; margin:10px auto; }

ss { position:static;  width:auto;  height:auto; margin:10px 50px; }`

静态

Image

绝对

Image

HTML

`

Absolute

Positioned Grandparent

  

Non-positioned Parent

    Absolute elements are positioned in their own layer in front of or behind the     normal flow.     In-place Absolute     Sized Absolute     

Stretched Absolute

    

Shrinkwrapped Absolute

`

CSS

`#in-place  { position:absolute; z-index:1; }

shrinkwrapped { position:absolute; z-index:0;

width:auto; left:0; bottom:0; margin:0; }

sized { position:absolute; z-index:auto;

width:170px; height:115px; bottom:0; left:270px; margin:0; }

stretched { position:absolute; z-index:-1;

height:auto; right:0; top:0; bottom:0; margin:0; }

/*  Nonessential rules are not shown. */`

绝对

Image

固定

Image

HTML

`

Fixed

Positioned Grandparent

  

Non-positioned Parent

    Absolute elements are positioned in their own layer in front of or behind the     normal flow.     In-place Absolute     Sized Absolute     

Stretched Absolute

    

Shrinkwrapped Absolute

`

CSS

`*.gp { position:relative; z-index:1; }

in-place { position:fixed; z-index:1; }

shrinkwrapped { position:fixed; z-index:0;

width:auto; left:0; bottom:0; margin:0; }

sized { position:fixed; z-index:auto;

width:170px; height:115px; bottom:0; left:270px; margin:0; }

stretched { position:fixed; z-index:-1;

height:auto; right:0; top:0; bottom:0; margin:0; }

/*  Nonessential rules are not shown. */`

固定

Image

相对

Image

HTML

`

Relative

Before Relative Positioning   

Static Block    Static Inline on top

  

Static Block on top

  

Absolute

After Relative Positioning   

Relative Block   Relative Inline on top

  

Relative Block on top

  

Absolute

`

CSS

`*.ontop { z-index:1; }
*.static { position:static; }
*.relative { position:relative; }
*.absolute { position:absolute; z-index:auto; }
*.offset  { left:20px; top:auto; }

/*  Nonessential rules are not shown. */`

相对

Image

漂浮而清晰

Image

HTML

`

Float

  
Float Left
  
Float Right
  **

This paragraph does not clear floats.     Float Right - cleared right     Float Right - NOT cleared

<p class="clear-left">This paragraph clears floats on its left side.


  <div class="float left clear-left">Float Left - cleared left

  <div class="float left clear-none">Float Left - NOT cleared

<p class="clear-right">This paragraph clears floats on its right side.
    <span class="float left  clear-left">Float Left
    <span class="float right clear-right">Float Right

<p class="clear-both">This paragraph clears floats on both sides.

`

CSS

`*.float { margin:0px 10px;  width:120px; background-color:yellow; color:black; }
*.left { float:left; }
*.right { float:right; }
*.clear-left { clear:left; }
*.clear-right { clear:right; }
*.clear-both { clear:both; }
*.clear-none { clear:none;  }

/*  Nonessential rules are not shown. */`

漂浮而清晰

Image

相对浮动

Image

HTML

`

Relative Float

  
Relative Float 1
  
Relative Float 2

This text is next to a relative float. A relative float works just like a
   static float except that it is relatively positioned. This allows it to be
   offset using left and right without affecting
   the position of other elements. It also allows z-index to
   control the stacking order of floats.

<span class="absolute">absolute

`

CSS

`*.parent { position:relative; padding:20px; }

*.relative1 { position:relative; z-index:3; top:10px; left:10px; }
*.relative2 { position:relative; z-index:2; top:20px; left:-30px; }

*.float { float:left; width:100px; height:50px;
  margin-right:25px; margin-bottom:40px; }

*.absolute { position:absolute; z-index:1; top:102px; left:215px; }

/*  Nonessential rules are not shown. */`

相对浮动

Image

八、定位:缩进、偏移和对齐

本章展示了边距如何偏移和对齐元素。

当一个被拉伸的元素的一个或多个边被移入或移出其容器时,该元素会被缩进突出,从而改变元素的宽度或高度。

当整个元素从其正常位置移动而不改变元素的高度或宽度时,调整大小或收缩的元素被偏移

当调整大小或收缩的元素被重新定位到其容器的一侧而不改变其大小和可选地从该侧偏移时,该元素被对齐。

章节大纲

  • 显示了如何从容器的两侧缩进一个元素。
  • 偏移静态显示了如何从周围的元素偏移一个元素。
  • 偏移或缩进静态表格展示了如何从容器中偏移一个表格。
  • 偏移浮动展示了如何从周围的浮动和内容中偏移一个浮动。
  • 绝对偏移和固定偏移显示了如何从正常流程中的位置偏移绝对元素。
  • 相对偏移显示了如何偏移任何元素而不影响其他元素。
  • 对齐静态内联展示了如何水平和垂直对齐内联元素。
  • 对齐和偏移静态块显示了如何对齐和偏移静态块元素。
  • 对齐和偏移静态表格显示如何对齐和偏移表格。
  • 绝对对齐和偏移显示了如何对齐和偏移绝对元素。
  • 绝对居中对齐显示了如何将绝对元素居中对齐。
  • 外部对齐展示了如何将元素对齐到其容器的外部。

缩进

Image

HTML

`

Indented

Positioned Grandparent   
Non-positioned Parent     
Horizontally Stretched Static
    
Vertically Stretched Absolute
    Horizontally Stretched Absolute   
`

CSS

`.gp { position:relative; z-index:10; }

hss { position:static;

width:auto; margin-left:30px; margin-right:30px;
   height:auto; margin-top:auto; margin-bottom:20px; }

vsa { position:absolute;

width:120px; left:auto; margin-left:auto; right:0; margin-right:70px;
   height:auto; top:0; margin-top:-30px; bottom:0; margin-bottom:-30px; }

hsa { position:absolute;

width:auto; left:0; margin-left:-30px; right:0; margin-right:-30px;
   height:auto; top:auto; margin-top:30px; bottom:auto; margin-bottom:auto; }

/* Nonessential rules are not shown. */`

缩进

Image

偏移静态

Image

HTML

`

Offset Static

  ← Moved-left   → Moved-right   Push-right →   Pull-left ←     None

Moved-down Static Block

Moved-up Static Block
Push-down Static Block
Pull-up Static Block
None
`

CSS

`.moved-left { margin-left:-26px; } .push-right { margin-right:50px; } .moved-right { margin-left:50px; } .pull-left { margin-right:-20px; } .moved-down { margin-top:20px; } .push-down { margin-bottom:20px; } .moved-up { margin-top:-13px; } .pull-up { margin-bottom:-16px; }

/* Nonessential rules are not shown. */`

偏移静态

Image

偏移或缩进静态表格

Image

HTML

`

Offset or Indented Static Table

  ****
Left-offset Shrinkwrapped Table
  ****
Right-offset Shrinkwrapped Table
  ****
Indented Stretched Table
  ****
Right-offset Sized Table
  ****
Left-offset Sized Table
`

CSS

`.l-wrap { width:auto; margin-left:60px; margin-right:auto; } .r-wrap { width:auto; margin-left:auto; margin-right:60px;}

.stretched { width:80%; margin-left:auto; margin-right:auto; }

.r-sized { width:300px; margin-left:auto; margin-right:60px; text-align:right; } .l-sized { width:300px; margin-left:60px; margin-right:auto; text-align:left; }

/* Nonessential rules are not shown. */`

偏移或缩进静态表格

Image

偏移浮动

Image

HTML

`

Offset Float

  

Sized Float

  

Right-retracted Float

  

Float

<p class="float-right sized">Sized Float


  <p class="float-right left-retracted">Left-retracted Float


  <p class="float-right shrunk">Float


  <p class="float-right widened right-extended top-extended">
    Right-extended & Top-extended Float


  <p class="float-left clear-left shrunk">Float


  <p class="float-right clear-right shrunk">Float

`

CSS

`.sized { width:70px; height:60px; margin:10px; }
.widened { width:175px; } .shrunk { margin:3px; padding:1px; background-color:white; }

.right-extended { margin-right:120px; } .right-retracted { margin-right:-55px; } .left-retracted { margin-left:-185px; } .top-extended { margin-top:20px; }

.float-left { float:left; } .float-right { float:right; }
.clear-left { clear:left; } .clear-right { clear:right; }

/* Nonessential rules are not shown. */`

偏移浮动

Image

绝对偏移和固定偏移

Image

HTML

`

Offset Absolute and Offset Fixed

Positioned Grandparent

  

Non-positioned Parent

    The default position of an offset absolute element is where it would have     been rendered if it were not absolutely positioned:     **Absolute**

You can use left and top margins to offset it from its
    default position: Fixed


  

`

CSS

`#absolute { position:absolute; width:140px; height:auto; }

#fixed { position:fixed;
  height:50px; margin-top:10px;
  width:auto; margin-left:10px; }

/* Nonessential rules are not shown. */`

绝对偏移和固定偏移

Image

相对偏移

Image

HTML

`

Offset Relative

  

    When inline content is relatively offset, it retains its      rendered shape–including line breaks.

      

Float

      

Sized Static

      

Indented Static Block

`

CSS

`.float { float:left; width:90px; height:40px; } .sized { width:90px; height:40px; margin-left:auto; margin-right:0; } .indented { margin-left:60px; margin-right:60px; }

.relative { position:relative; }

.offset1 { left:0px; top:-12px; } .offset2 { left:-50px; top:10px; } .offset3 { left:50px; top:10px; } .offset4 { left:0px; top:-32px; }

/* Nonessential rules are not shown. */`

相对偏移

Image

对齐静态内嵌

Image

HTML

`

Aligned Static Inline

  

Left-aligned content

  

Horizontally and Vertically Center-aligned Content

  

Right-aligned content

  

Justify-aligned works on all but the last line. This line is     justified but the last line is not.

    

Aligned to baseline.       Lowered relative to the baseline.       Raised relative to...

`

CSS

`.baseline { vertical-align:baseline; } .raised { vertical-align:10px; } .lowered { vertical-align:-10px; }

l { position:static; text-align:left; } #c { position:static; text-align:center; line-height:48px; } #r { position:static; text-align:right; } #j { position:static; text-align:justify; }

/* Nonessential rules are not shown. */`

对齐静态内嵌

Image

对齐和偏移静态块

Image

HTML

`

Aligned and Offset Static Block

  

Left Aligned

  

Left Aligned & Offset

  

Center Aligned

  

Right Aligned & Offset

  

Right Aligned

`

CSS

`#left { position:static; width:120px; margin-left:0; margin-right:auto; }

left-off { position:static; width:200px; margin-left:50px; margin-right:auto; }

center { position:static; width:120px; margin-left:auto; margin-right:auto; }

right { position:static; width:120px; margin-left:auto; margin-right:0; }

right-off { position:static; width:200px; margin-left:auto; margin-right:50px; }

/* Nonessential rules are not shown. */`

对齐和偏移静态块

Image

对齐和偏移静态表

Image

HTML

`

Aligned Static Table

  ****
Left-aligned Shrinkwrapped Table
  ****
Centered Shrinkwrapped Table
  ****
Right-offset Shrinkwrapped Table
  ****
Stretched Table
  ****
Right-aligned Sized Table
  ****
Centered Sized Table
  ****
Left-offset Sized Table
`

CSS

`.l-wrap { width:auto; margin-left:0; margin-right:auto; } .c-wrap { width:auto; margin-left:auto; margin-right:auto;} .r-wrap { width:auto; margin-left:auto; margin-right:20px; }

.stretched { width:100%; margin-left:0; margin-right:0; }

.r-sized { width:350px; margin-left:auto; margin-right:0; text-align:right; } .c-sized {
width:350px; margin-left:auto; margin-right:auto; text-align:center; } .l-sized { width:350px;
margin-left:20px; margin-right:auto; text-align:left; }

/* Nonessential rules are not shown. */`

对齐和偏移静态表

Image

对齐和绝对偏移

Image

HTML

`

Aligned and Offset Absolute

  

Left-top Aligned & Offset

  

Left-bottom Aligned & Offset

  

Center-middle Aligned

  

Right-top Aligned & Offset

  

Right-bottom Aligned & Offset

`

CSS

`div { position:relative; }

lt { position:absolute;

width:auto; left:0; margin-left:8px; right:auto; margin-right:auto;
  height:auto; top:0; margin-top:8px; bottom:auto; margin-bottom:auto; }

lb { position:absolute;

width:240px; left:0; margin-left:8px; right:auto; margin-right:auto;
  height:18px; top:auto; margin-top:auto; bottom:0; margin-bottom:8px; }

cm { position:absolute;

width:200px; left:0; margin-left:auto; right:0; margin-right:auto;
  height:18px; top:0; margin-top:auto; bottom:0; margin-bottom:auto; }

rt { position:absolute;

width:220px; left:auto; margin-left:auto; right:0; margin-right:8px;
  height:18px; top:0; margin-top:8px; bottom:auto; margin-bottom:auto; }

rb { position:absolute;

width:auto; left:auto; margin-left:auto; right:0; margin-right:8px;
  height:auto; top:auto; margin-top:auto; bottom:0; margin-bottom:8px; }

/* Nonessential rules are not shown. */`

对齐和绝对偏移

Image

Image

绝对居中对齐

Image

HTML

`

Aligned-center Absolute

  

Horizontally & Vertically Centered

`

CSS

`div { position:relative; }

cm

.hc { width:200px; left:0; margin-left:auto; right:0; margin-right:auto; } .vc { height:40px; top:0; margin-top:auto; bottom:0; margin-bottom:auto; }

/* Nonessential rules are not shown. */`

绝对居中对齐

Image

外对齐

Image

HTML

`

Aligned Outside

Parent   

Sized Block Outside Left

  

Sized Block Outside Right

  

Sized Float Outside Left

  

Sized Float Outside Right

  

Absolute Outside Top Left

  

Absolute Outside Top Right

  

Absolute Outside Bottom Left

  

Absolute Outside Bottom Right

`

CSS

`.parent { position:relative; height:140px; width:200px; }

.sized-block-outside-left { width:220px; margin-left:-234px; } .sized-block-outside-right { width:220px; margin-left:100%; } .sized-float-outside-left { width:220px; margin-left:-234px; float:left; } .sized-float-outside-right { width:220px; margin-left:100%; float:left; }

.left { position:absolute; right:100%; margin-right:5px; } .right { position:absolute; left:100%; margin-left:5px; } .top { position:absolute; bottom:100%; margin-bottom:5px; } .bottom { position:absolute; top:100%; margin-top:5px; }

/* Nonessential rules are not shown. */`

外对齐

Image

九、定位:高级

这是关于定位的三章中的第三章。它将前两章的定位技术结合到 12 个设计模式中,在拉伸、调整或收缩静态和定位元素时,将它们对齐和偏移到容器的左侧、中间、右侧、顶部、中间或底部。本章主要关注静态和绝对定位的元素。

本章结合了第八章中的设计模式来对齐和偏移容器中的元素。它还引入了新的模式来从容器的顶部、中部和底部对齐和偏移元素。如果你还不熟悉第五章—第八章中的设计模式,你可能想回顾一下。因为从左侧和右侧对齐和偏移是相似的,所以您可能想跳过右对齐和右偏移。

章节大纲

  • 左对齐展示了如何将一个元素与其容器的左侧对齐。
  • 左偏移显示了如何偏移一个左对齐的元素。
  • 右对齐展示了如何将一个元素与其容器的右侧对齐。
  • 右偏移显示了如何偏移一个右对齐的元素。
  • 居中对齐展示了如何将一个元素与其容器的中心对齐。
  • 中心偏移显示如何偏移一个中心对齐的元素。
  • 顶部对齐展示了如何将一个元素对齐到其容器的顶部。
  • 顶部偏移显示了如何偏移顶部对齐的元素。
  • 底部对齐展示了如何将一个元素对齐到其容器的底部。
  • 底部偏移显示了如何偏移一个底部对齐的元素。
  • 居中对齐展示了如何将一个元素对齐到其容器的中间。
  • 中间偏移显示如何偏移中间对齐的元素。

左对齐

Image

HTML

<h1>Left Aligned</h1>  <div **class="gp"**>Positioned Grandparent     <div **class="parent"**>Non-positioned Parent     <div **id="zs"** class="example">Sized Static Block </div>     <div **id="ss"** class="example">Stretched Static Block</div>     <span **id="za"** class="example">Sized Absolute</span>     <span **id="wa"** class="example">Shrinkwrapped Absolute</span>     <span **id="sa"** class="example">Stretched Absolute</span></div></div>

CSS

`.gp { position:relative; height:295px; width:600px; border:2px solid black; }
.parent <{ margin:10px; padding:10px; padding-top:0; border:1px solid black; }
.example { padding:5px; <border:5px solid black; <background-color:gold;   <<}

zs { position:static;          text-align:left;                      margin-top:5px;

width:400px;                    margin-left:0;              margin-right:auto; }

ss { position:static;          text-align:left;                      margin-top:5px;

width:auto;                     margin-left:0;              margin-right:0;    }

za { position:absolute;        text-align:left;                   top:0; margin-top:155px;

width:400px;  left:0;           margin-left:0;  right:auto; margin-right:auto; }

wa { position:absolute;        text-align:left;             top:0; margin-top:200px;

width:auto;   left:0;           margin-left:0;  right:auto; margin-right:auto; }

sa { position:absolute;        text-align:left;              top:0; margin-top:245px;

width:auto;left:0;              margin-left:0;  right:0;    margin-right:0;    }`

左对齐

Image

向左偏移

Image

HTML

`

Left Offset

Positioned Grandparent  
Non-positioned Parent   Sized Static Block: +50px
  Stretched Static Block: +50px
  Sized Absolute: -50px   Shrinkwrapped Absolute: -50px   Stretched Absolute:-50px`

CSS

`.gp { position:relative; height:295px; width:600px; border:2px solid black;  }
.parent  { margin:10px; padding:10px; padding-top:0; border:1px solid black; }
.ex      { padding:5px;  border:5px solid black;  background-color:gold;     }
div.ex  span { margin-left:-60px; border:1px dotted black; }
span.ex span { margin-left:30px;  border:none;             }

zs { position:static;          text-align:left;                   margin-top:5px;

width:400px;            margin-left:50px;                margin-right:auto; }

ss { position:static;          text-align:left;                   margin-top:5px;

width:auto;             margin-left:50px;                margin-right:0;    }

za { position:absolute;        text-align:left;          top:0; margin-top:155px;

width:400px;  left:0;   margin-left:-50px;   right:auto;  margin-right:auto;}

wa { position:absolute;        text-align:left;          top:0; margin-top:200px;

width:auto;   left:0;   margin-left:-50px;   right:auto; margin-right:auto;}

sa { position:absolute;        text-align:left;          top:0; margin-top:245px;

width:auto;   left:0;   margin-left:-50px;   right:0;    margin-right:0;   }`

向左偏移

Image

右对齐

Image

HTML

 <h1>Right Aligned</h1>  <div class="gp">Positioned Grandparent    <div class="parent">Non-positioned Parent      <div  **id="zs"** class="example">Sized Static Block </div>      <div  **id="ss"** class="example">Stretched Static Block</div>      <span **id="za"** class="example">Sized Absolute</span>      <span **id="wa"** class="example">Shrinkwrapped Absolute</span>      <span **id="sa"** class="example">Stretched Absolute</span></div></div>

CSS

`.gp { position:relative; height:295px; width:600px; border:2px solid black;  }
.parent  { margin:10px; padding:10px; padding-top:0; border:1px solid black; }
.example { padding:5px;  border:5px solid black;  background-color:gold;     }

zs { position:static;          text-align:right;                    margin-top:5px;

width:400px;            margin-left:auto;           margin-right:0;       }

ss { position:static;          text-align:right;                    margin-top:5px;

width:auto;             margin-left:0;              margin-right:0;       }

za { position:absolute;        text-align:right;           top:0; margin-top:155px;

width:400px;   left:auto; margin-left:auto; right:0; margin-right:0;       }

wa { position:absolute;        text-align:right;           top:0; margin-top:200px;

width:auto;   left:auto; margin-left:auto; right:0; margin-right:0;       }

sa { position:absolute;        text-align:right;                  top:0; margin-top:245px;

width:auto;   left:0;   margin-left:0;     right:0; margin-right:0;       }`

右对齐

Image

向右偏移

Image

HTML

`

Right Offset

Positioned Grandparent
Non-positioned Parent   Sized Static Block: +50px
  Stretched Static Block: +50px
  Sized Absolute: -50px   Shrinkwrapped Absolute: -50px   Stretched Absolute:-50px`

CSS

`.gp { position:relative; height:295px; width:600px; border:2px solid black;  }
.parent  { margin:10px; padding:10px; padding-top:0; border:1px solid black; }
.ex      { padding:5px;  border:5px solid black;  background-color:gold;     }
div.ex  span { margin-right:-60px; border:1px dotted black; }
span.ex span { margin-right:30px;  border:none;             }

zs { position:static;        text-align:right;                 margin-top:5px;

width:400px;          margin-left:auto;          margin-right:50px;    }

ss { position:static;        text-align:right;                 margin-top:5px;

width:auto;           margin-left:0;             margin-right:50px;    }

za { position:absolute;      text-align:right;         top:0; margin-top:155px;

width:400px; left:auto; margin-left:auto; right:0;  margin-right:-50px;  }

wa { position:absolute;      text-align:right;         top:0; margin-top:200px;

width:auto;  left:auto; margin-left:auto; right:0;      margin-right:-50px;  }

sa { position:absolute;      text-align:right;         top:0; margin-top:245px;

width:auto;  left:0; margin-left:0;    right:0;         margin-right:-50px;  }`

向右偏移

Image

居中对齐

Image

HTML

 <h1>Center Aligned</h1>  <div class="gp">Positioned Grandparent    <div class="parent">Non-positioned Parent      <div  **id="zs"** class="example">Sized Static Block </div>      <div  **id="ss"** class="example">Stretched Static Block</div>      <span **id="za"** class="example">Sized Absolute</span>      <span **id="wa"**>An element can't be shrinkwrapped if it is centered.</span>      <span **id="sa"** class="example">Stretched Absolute</span></div></div>

CSS

`.gp { position:relative; height:295px; width:600px; border:2px solid black;  }
.parent  { margin:10px; padding:10px; padding-top:0; border:1px solid black; }
.example { padding:5px;  border:5px solid black;  background-color:gold;     }

zs { position:static;         text-align:center;                    margin-top:5px;

width:400px;             margin-left:auto;                margin-right:auto;  }

ss { position:static;         text-align:center;                    margin-top:5px;

width:auto;              margin-left:70px;                margin-right:70px;     }

za { position:absolute;       text-align:center;           top:0; margin-top:155px;

width:67%;  left:0;            margin-left:auto; right:0;     margin-right:auto;  }

wa { position:absolute;       text-align:center;             top:0; margin-top:200px;

width:auto;   left:0;    margin-left:0;    right:0;       margin-right:0;     }

sa { position:absolute;       text-align:center;             top:0; margin-top:245px;

width:auto;   left:0;    margin-left:15%;  right:0;       margin-right:15%;     }`

居中对齐

Image

中心偏移

Image

HTML

`

Center Offset

Positioned Grandparent   
Non-positioned Parent     
A sized static block can't be center offset.
    Stretched Static Block → 40px
    Sized Absolute → 40px     An element can't be shrinkwrapped if it is centered.     Stretched Absolute → 40px `

CSS

`.gp { position:relative; height:295px; width:600px; border:2px solid black;      }
.parent { margin:10px; padding:10px; padding-top:0; border:1px solid black;      }
.ex     { padding:5px;  border:5px solid black;  background-color:gold;          }
.ex span { margin-left:-40px; }

zs { position:static;          text-align:center;                  margin-top:5px;

width:auto;               margin-left:90px;            margin-right:10px;    }

ss { position:static;          text-align:center;                  margin-top:5px;

width:auto;               margin-left:90px;          margin-right:10px;    }

za { position:absolute;        text-align:center;         top:0; margin-top:155px;

width:440px; left:80px;   margin-left:auto; right:0; margin-right:auto;    }

wa { position:absolute;        text-align:center;         top:0; margin-top:200px;

width:auto;  left:0;      margin-left:110px; right:0;  margin-right:30px;    }

sa { position:absolute;        text-align:center;         top:0; margin-top:245px;

width:auto;  left:0;      margin-left:110px; right:0;  margin-right:30px;    }`

中心偏移

Image

顶端对齐

Image

HTML

`

Top Aligned

Positioned Grandparent   
Non-positioned Parent     Sized Static Block
    Shrinkwrapped Static Block
    Sized Absolute     Shrinkwrapped Absolute     Stretched Absolute`

CSS

`.gp { position:relative; height:300px; width:700px; border:2px solid black;  }
.parent  { margin:10px; padding:10px; padding-top:0; border:1px solid black; }
.ex      { padding:5px;  border:5px solid black;  background-color:gold;
           width:120px; text-align:center; position:relative;      }
.ex span { left:0; width:130px; height:auto; }

#zs { height:100px;             margin-top:0;                margin-bottom:auto;
      position:static;                                                          }
#ws { height:auto;              margin-top:0;                margin-bottom:auto;
      position:static;                                                          }
#za { height:100px;      top:0; margin-top:0;  bottom:auto;  margin-bottom:auto;
      position:absolute;                                     margin-left:200px; }
#wa { height:auto;       top:0; margin-top:0;  bottom:auto;  margin-bottom:auto;
      position:absolute;                                     margin-left:355px; }
#sa { height:auto;       top:0; margin-top:0;  bottom:0;     margin-bottom:0;
      position:absolute;                                     margin-left:510px; }`

顶端对齐

Image

顶部偏移

Image

HTML

`

Top Offset

Positioned Grandparent   
Non-positioned Parent     Sized Static Block
    Shrinkwrapped Static Block
    Sized Absolute     Shrinkwrapped Absolute     Stretched Absolute`

CSS

`.gp { position:relative; height:300px; width:700px; border:2px solid black;  }
.parent  { margin:10px; padding:10px; padding-top:0; border:1px solid black; }
.ex      { padding:5px;  border:5px solid black;  background-color:gold;
           width:120px; text-align:center; position:relative;      }
.ex span { left:0; width:130px; height:auto; }

#zs { height:100px;             margin-top:25px;                      margin-bottom:0;
position:static;                                                                   }
#ws { height:auto;              margin-top:-70px;                     margin-bottom:0;
position:static;                                                background-color:yellow; }
#za { height:100px;   top:0;    margin-top:70px;  bottom:auto;        margin-bottom:auto;
position:absolute;                                                    margin-left:200px; }
#wa { height:auto;    top:0;    margin-top:70px;  bottom:auto;        margin-bottom:0;
position:absolute;                                                    margin-left:355px; }
#sa { height:auto;    top:0;    margin-top:70px;  bottom:0;           margin-bottom:0;
position:absolute;                                                    margin-left:510px; }`

顶部偏移

Image

底端对齐

Image

HTML

`

Bottom Aligned

Positioned Grandparent  
Non-positioned Parent   Sized Static Block
  Shrinkwrapped Static Block
  Sized Absolute   Shrinkwrapped Absolute   Stretched Absolute`

CSS

`.gp { position:relative; height:300px; width:700px; border:2px solid black;  }
.parent  { margin:10px; padding:10px; padding-top:0; border:1px solid black; }
.ex      { padding:5px;  border:5px solid black;  background-color:gold;
           width:120px; text-align:center; position:relative;  }
.ex span { height:auto; left:0; width:130px; }

span.ex span {position:absolute;top:auto;margin-top:auto;bottom:0;margin-bottom:0; }
#zs { height:100px;           margin-top:auto;           margin-bottom:0;
      position:static;                                          margin-left:0px;   }
#ws { height:auto;            margin-top:auto;           margin-bottom:0;
position:static;                                                                   }
#za { height:100px; top:auto; margin-top:auto; bottom:0; margin-bottom:0;
position:absolute;                                              margin-left:200px; }
#wa { height:auto;  top:auto; margin-top:auto; bottom:0; margin-bottom:0;
      position:absolute;                                              margin-left:355px; }
#sa { height:auto;  top:0;    margin-top:0;    bottom:0; margin-bottom:0;
      position:absolute;                                              margin-left:510px; }`

底端对齐

Image

底部偏移

Image

HTML

`

Bottom Offset

Positioned Grandparent  
Non-positioned Parent   Sized Static Block
  Shrinkwrapped Static Block
  ****Sized Absolute   Shrinkwrapped Absolute   ****Stretched Absolute`

CSS

`.gp { position:relative; height:300px; width:700px; border:2px solid black;  }
.parent  { margin:10px; padding:10px; padding-top:0; border:1px solid black; }
.ex      { padding:5px;  border:5px solid black;  background-color:gold;
           width:120px; text-align:center; position:relative;  }
.ex span { height:auto; left:0; width:130px; }
span.ex span{position:absolute;top:auto;margin-top:auto;bottom:5px;margin-bottom:0;}

#zs { height:100px;           margin-top:auto;          margin-bottom:-70px;
      position:static;                                                             }
#ws { height:auto;            margin-top:auto;          margin-bottom:120px;
      position:static;                                  background-color:yellow;   }
#za { height:100px; top:auto; margin-top:auto; bottom:0; margin-bottom:50px;
      position:absolute;                                        margin-left:200px; }
#wa { height:auto;  top:auto; margin-top:auto; bottom:0; margin-bottom:50px;
      position:absolute;                                        margin-left:355px; }
#sa { height:auto;  top:0;    margin-top:auto; bottom:0; margin-bottom:50px;
      position:absolute;                                        margin-left:510px; }`

底部偏移

Image

居中对齐

Image

HTML

`

Middle Aligned

  
INLINE
  
Sized Absolute
  
Can't middle-align a static element                                or a shrinkwrapped element.
  
Stretched Absolute
`

CSS

`.gp { position:relative; height:300px; width:700px; border:2px solid black;       }
.ex1 { width:120px; padding:5px; text-align:center; border:1px dotted black;      }
.ex2 { position:relative; border:5px solid black;  background-color:gold; left:0; }
.ex1 span  { height:36px; left:0; width:130px;
       position:absolute; top:0; margin-top:auto; bottom:0; margin-bottom:auto;   }

#ia   { height:100px;  top:0; margin-top:auto; bottom:0; margin-bottom:auto;
        position:absolute;    line-height:100px;                margin-left:40px; }
#za   { height:100px;  top:0; margin-top:auto; bottom:0; margin-bottom:auto;
        position:absolute;                                      margin-left:200px; }
#wa   { height:auto;   top:0; margin-top:90px; bottom:0; margin-bottom:90px;
        position:absolute;                                      margin-left:355px; }
#sa   { height:auto;   top:0; margin-top:90px; bottom:0; margin-bottom:90px;
        position:absolute;                                      margin-left:510px; }`

居中对齐

Image

中间偏移

Image

HTML

Middle Offset


 

<div id="ia" class="ex1 ex2">INLINE


  <div id="za" class="ex1 ex2">Sized Absolute
  <div id="wa" class="ex1">Can't middle-offset a static element
                               or a shrinkwrapped element.
  <div id="sa" class="ex1 ex2">Stretched Absolute`

CSS

`.gp { position:relative; height:300px; width:700px; border:2px solid black;               }
.ex1 { width:120px; padding:5px; text-align:center; border:1px dotted black;      }
.ex2 { position:relative; border:5px solid black;  background-color:gold; left:0; }
.ex1 span { height:36px; left:0; width:130px;
        position:absolute; top:0; margin-top:auto; bottom:0; margin-bottom:auto;   }

ia   { height:100px; top:60px; margin-top:auto;  bottom:-60px; margin-bottom:auto;

position:absolute;      line-height:100px;             margin-left:40px; }

za   { height:100px; top:60px; margin-top:auto;  bottom:-60px; margin-bottom:auto;

position:absolute;                        margin-left:200px; }

wa   { height:auto;  top:0;    margin-top:150px; bottom:0;     margin-bottom:30px;

position:absolute;                                      margin-left:355px; }

sa   { height:auto;  top:0;    margin-top:150px; bottom:0;     margin-bottom:30px;

position:absolute;                                      margin-left:510px; }`

中间偏移

Image

十、样式文本

这是包含设计文本样式的设计模式的三章中的第一章。下一章讨论如何在文本周围放置空间。第十二章讨论如何对齐文本。严格地说,这是唯一一章真正为正文设计了样式。接下来的两章使用了风格的内联元素,它们可以包含文本或者被图片、对象、控件、电影等等所替代。

章节大纲

  • 字体展示了如何使用字体来设计文本样式。
  • 高亮显示展示了如何使用彩色和平铺背景图像来高亮显示文本。
  • 显示了如何为下划线、上划线和线条创建自定义样式。
  • 文本阴影展示了如何在 Internet Explorer 6 和 Safari 中自动生成文本背后的阴影。
  • 用图像替换文本展示了如何用图像替换文本。屏幕阅读器可以阅读文本,当图像不可用时,文本质量会下降。这是一个使网站美观和易访问的重要工具。
  • 用画布和 VML 替换文本(矢量标记语言)由两个独立的部分组成:一个字体生成器,它使用 VML 将字体转换为专有格式,以及一个渲染引擎。这种技术的一个优点是用户可以选择和复制文本,而这在图像替换方法中是不可能的。
  • 字体嵌入是 CSS3 对文本替换技术的替代,它使用@font-face属性直接从服务器下载字体文件,然后将其应用于元素。
  • 不可见文本展示了如何在不添加标记的情况下隐藏文本。它不如文本替换有用,但不需要额外的标记。
  • Screenreader-only 展示了如何使文本对屏幕阅读器可读,同时对视力正常的用户完全隐藏。这是一个重要的工具,可以让非视力用户访问网站,同时让视力正常的用户保持网站整洁。

字体

Image

HTML

`

Font

**font-family**:sans serif  serif monospace

**font-size**:small  mediumlarge

**color**:black  gold

**font-style**:normal  italic

**font-weight**:normal  bold

**font-variant**:normal  smallcaps

**text-transform**:none  lowercaseuppercase  capitalize

`

CSS

.family1 { **font-family**:sans-serif; }      .family2 { font-family:serif; } .family3 { font-family:monospace; } .size1 { **font-size**:small; }               .size2 { font-size:medium; } .size3 { font-size:large; } .style1 { **font-style**:normal; }            .style2 { font-style:italic; } .weight1 { **font-weight**:normal; }          .weight2 { font-weight:bold; } .variant1 { **font-variant**:normal; }        .variant2 { font-variant:small-caps; } .color1 { **color**:black; }                  .color2 { **color**:gold; } .trans1 { **text-transform**:none; }          .trans2 { text-transform:lowercase; } .trans3 { text-transform:uppercase; }     .trans4 { text-transform:capitalize; }

字体

Image

高亮显示

Image

HTML

`

You can insert a
**  highlight**
  in any inline context.
**  Highlights can span multiple**
  lines.
A highlight is a
**  foreground color and a**
**  background color**
  applied to an inline element.
**  Padding**
  around a highlight can improve its visual appeal. You can increase the
**  line height**
  to make room for extra padding.

`

CSS

`p { margin-top:20px; letter-spacing:0.5px; line-height:1.9em; }

.highlight { color:white; background-color:black;
**  padding-left:0.25em; padding-right:0.25em;**
**  padding-top:0.05em;  padding-bottom:0.13em;**
**  background-image:none; }**

.black-on-gold { color:black; background-color:gold; }
.white-on-firebrick { color:white; background-color:firebrick; }
.cyan-on-royalblue { color:lightcyan; background-color:royalblue; }
.palegreen-on-darkgreen { color:palegreen; background-color:darkgreen; }
.textured { color:black; background-color:white;
  background-image:url("paper.jpg"); }`

高亮显示

Image

文字装饰

Image

HTML

`

Text Decoration


**  text-decoration:**
**  underline  overline  **
**  line-through
**

**  

border😗*
**  Under 4   Under 5  **
**  Under 6   Over 7  **
**  Over 8   Over 9  **

**  

background😗*
**  Under 10   Under 11  **
**  Under 12   Over 13  **
**  Over 14   Thru 15  **

`

CSS

`*.t1 { text-decoration:underline; }       .t2 { text-decoration:overline; }
.t3 { text-decoration:line-through; }

*.t4 { border-bottom:1px solid black; }   .t5 { border-bottom:1px dotted black; }
*.t6 { border-bottom:2px dashed gray; }   .t7 { border-top:3px double red; }
*.t8 { border-top:4px groove blue; }      .t9 { border-top:6px ridge green; }

.t10 { background:repeat-x left bottom url("tight-dot.gif"); padding-bottom:0px; }
.t11 { background:repeat-x left bottom url("dotted.gif"); padding-bottom:0px; }
.t12 { background:repeat-x left bottom url("wavy-green.gif"); padding-bottom:2px; }
.t13 { background:repeat-x left top url("diamond-blue.gif"); padding-top:3px; }
.t14 { background:repeat-x left top url("gradient3.gif"); padding-top:2px; }
.t15 { background:repeat-x left center url("wavy-red3.gif"); padding:5px; }`

文字装饰

Image

文字阴影

Image

HTML

`

Text Shadow

Text Shadow applies to all text in a block.   This design pattern does not apply to inline elements in Internet Explorer 6.   This design pattern does not work in Opera 9, Firefox 2,   and other Mozilla Browsers

`

CSS 所有浏览器

.shadow { text-shadow:#999999 5px 5px 5px; }

CSS Internet Explorer 6

.shadow { filter:shadow(color=#999999, direction=135, strength=4); zoom:1; }

文字阴影

Image

用图像替换文字

Image

用图像替换文本的示例

Image

浏览器无法显示图像时显示的示例

HTML

`

Text Replacement with Image

Heading 2

`

CSS

`#h2 { position:relative; width:250px; height:76px; padding:0; overflow:hidden; }

h2 span { position:absolute; width:250px; height:76px; left:0; top:0; margin:0;

background-image:url("heading2.jpg"); background-repeat:no-repeat; }`

用图像替换文字

Image

用画布和 Vml 替换文本

Image

显示替换了文本的示例

HTML

`<!doctype html>

                                 

Test Replacement with VML and canvas

    

Heading 2

   `

用画布和 VML 替换文本

Image

字体嵌入

Image

字体渲染示例

HTML

`

Embedding Font

Heading 2

`

CSS

`@font-face {
font-family: Chunkfive;
src: url('chunkfive.otf') format ("opentype");
}

h2 {

font-family: Chunkfive, Arial, sans-serif;
}`

字体嵌入

Image

不可见文字

Image

HTML

`

Invisible Text

Invisible Text

`

CSS

.invisible-text {   text-indent:-9999px;   text-align:left;   width:75px;   height:35px;   background-image:url("go.jpg");   background-repeat:no-repeat;   background-position:center center; }

不可见文字

Image

屏幕阅读器专用

Image

HTML

`

Screenreader-only

Text before screenreader-only text.


**  This text is hidden to sighted users, but is read by screen readers.

**


**  You can make any type of element a screenreader-only element.**

Text after screenreader-only text.

`

CSS

.screenreader-only {   position:absolute;   left:-9999px;   top:-9999px;   width:1px;   height:1px;   overflow:hidden; }

屏幕阅读器专用

Image

十一、间隔内容

本章讨论在内联元素周围放置水平和垂直空间的设计模式,内联元素可能包含文本、图像、对象、控件等等。本章包含以下设计模式:

  • 间距显示了如何分隔文本和内容。它只是将内置于 CSS 中的许多属性组合在一起,在块、文本和内容周围和之间放置空间。
  • Blocked 展示了如何将一个内联元素呈现为一个块元素。这是一个非常重要的设计模式,通常与其他模式结合使用。
  • Nowrap 展示了如何防止浏览器换行。
  • 展示了如何呈现文档中的空白,而不是折叠它。
  • 代码展示了如何标记计算机代码、内联呈现代码、以块的形式显示代码、保留空白以及防止代码换行。
  • 填充内容展示了如何在内联内容周围留出空间来强调内容。
  • Inline Spacer 展示了如何在一行中插入一个水平分隔符,以精确地放置内容之间的距离。
  • 内嵌装饰展示了如何在一行中插入一个装饰。装饰是风格,而不是内容。它允许您将彩色背景、纹理背景或背景图像插入到流程中。你可以给它加上边框。您可以使用它来分开内容,重叠前面的内容,以及重叠后面的内容。
  • 换行符展示了如何将四种不同类型的换行符插入到你的文档中,这些换行符可以增加行间的额外空间或者缩短行间的距离。
  • 行内水平标尺展示了如何使用行内元素插入水平标尺。您可以使用图像、边框、边距等来设置水平标尺的样式。这使您可以在行与行之间留出额外的空间,重叠前面的行,并重叠后面的行。一条内联水平线特别有用,因为你可以在任何地方使用内联元素。HTML 的水平标尺是一个元素,样式选项有限。

间距

Image

HTML

`

Spacing

This paragraph is normal. It has no indentation, margins, padding,  letter spacing, word spacing, text justification, or line spacing.

This paragraph has many forms of spacing. The first line of text
 is indented. Margins indent the paragraph on all sides. Padding puts space
 between the paragraph and its borders. Letters have 1 extra pixel of space between
 them. Words have 2 extra pixels of space between them. Text is justified, which
 adds extra space between words to align text to the left and right edges. And
 lines have extra spacing between them.

`

CSS

.elegant { margin-left:40px; margin-right:80px;   margin-top:30px; margin-bottom:30px;   padding-top:25px; padding-bottom:25px;   letter-spacing:1px;   word-spacing:2px;   line-height:1.7em;   text-indent:40px;   text-align:justify;   border-top:1px solid black; border-bottom:1px solid black; }

间距

Image

受阻

Image

HTML

`

Blocked

The Blocked design pattern displays an inline element as a block element   that can be styled in every way as a block element. **  **This is an inline element displayed as a block.   Its first line is indented and it has collapsing vertical margins.

  Name   

    Street     City,     State,     Zip Code     Country   

  email@email.com
`

CSS

`.blocked { display:block; text-indent:2em; margin-top:5px; }

.vcard { border:4px solid green; padding:10px;  font-style:italic;}
.vcard .org { display:block; }
.vcard .street-address { display:block; }
.vcard .adr { display:block; }
.vcard .email { display:block; }`

受阻

Image

【nowrap】。

Image

HTML

`

Nowrap

  

You can keep a phrase together using nowrap, such as    **DO NOT BREAK THIS ACROSS TWO LINES!

You can use nowrap to keep some browsers from breaking a hyphenated word
    across two lines, such as the following word:
    <span class="nowrap">super-cali-fragilistic-expi-ali-docious!

You can keep together a small code snippet containing a space, such as
    <br />.


  

Notice how it breaks across two lines when nowrap
    is not applied to it: <br />.

Be aware that nowrapped text can overflow its container. This
    does not affect the width of other elements, but it may cause a browser to
    display a horizontal scrollbar requiring users to scroll to see the text.

`

CSS

.nowrap { white-space:nowrap; background-color:gold; }

【nowrap】。

Image

保存下来

Image

HTML

`

Preserved

You   can   preserve   whitespace   using   <pre>.

You can use white-space:pre to insert line breaks and spaces. **  ** **    **Preserved moves this sentence to a new line and indents it five spaces.   
     A better approach is to insert   <br /> and &nbsp;

You can preserve
                 whitespace in blocks.

You can preserve ****                  whitespace in inline elements.

You can turn white-space:pre
                               <span class="not-preserved" >on and off
                                                            at any time.

`

CSS

**.preserved { white-space:pre; }** .not-preserved { white-space:normal; }

保存下来

Image

代码

Image

HTML

`

Code

The following code is blocked and preserved:


  .blocked     { display:block; }
  .preserved   { white-space:pre; }
  .code        { font-family:monospace; }

The following inline code uses the Nowrap design pattern: ****a = x(y2 + z3) + 1.  This prevents it from being wrapped across lines.

`

CSS

**.blocked { display:block; }** **.preserved { white-space:pre; }** **.nowrap { white-space:nowrap; }**

代码

Image

填充内容

Image

HTML

`

Padded Content

Padding sets apart text to emphasize it.   Left and right padding inserts horizontal space before and after content.   Padded content can be   
****a letter...→   
****a word...→   
****a phrase...→   
****a paragraph...→ etc.   **This multi-line text is padded as an     entire block rather than padded on each line.   

`

CSS

`.padded-mild { padding-left:1em; padding-right:1em; line-height:1em; }
.padded-emphasized { padding-left:2em; padding-right:2em; line-height:2em; }
.padded-strong { padding-left:3em; padding-right:3em; line-height:3em; }
.padded-extreme { padding-left:4em; padding-right:4em; line-height:4em; }

.padded-strong-BA { display:block; padding:2em 5em; }`

填充内容

Image

内嵌间隔符

Image

HTML

`

Inline Spacer

Just like you can use <br /> to insert vertical space   into content,
you can use an inline spacer to insert and control   horizontal space. **   **The inline spacer is a marker element   that emphasizes the space in between content. **   **You use it when you do not want to   mark up content, but you still want to control the amount of space   in between content.

For example, if your page design requires extra space before sentences,   it is not a good idea to mark up sentences, because that would prevent you from   cutting across sentence boundaries with additional markup. **   **Marking up the first word of a sentence would not   be semantically accurate because the extra space separates sentences not words. **   **The inline spacer solves this problem   because it does not interfere with other markup. **   **It is also semantically correct   because its purpose is to mark up and emphasize space.

`

CSS

.space { margin-left:0.5em; }

内嵌间隔符

Image

内嵌装饰

Image

HTML

`

Inline Decoration

You can use Inline Decoration to do the following:   
        
  • Insert colored** ** decoration.
  •     
  • Insert patterned** ** decoration.
  •     
  • Insert imaged** ** decoration.
  •   
`

CSS

`div { font-size:18px; }

.deco-solid { padding-left:40px;
  font-size:0.4em; vertical-align:middle; line-height:24px;
  margin-left:3px; margin-right:-15px;
  background-color:gold; }

.deco-groove { padding-left:10px;
  font-size:0.4em; vertical-align:middle; line-height:24px;
  border-left:20px groove black; border-right:20px ridge black;
  margin-left:3px; margin-right:3px;
  background-color:lightgray; }

.deco-spear { padding-left:100px;
  font-size:1em; vertical-align:-3px; line-height:24px;
  margin-left:3px; margin-right:3px;
  background-image:url("spear.jpg"); background-position:top right; }`

内嵌装饰

Image

换行

Image

HTML

`

Line Break

You can insert a line break anywhere. **  ↑ One-half line break.** **  ↑ Normal line break.** **  

↑ Line break plus 10 pixels.** **  ↑ One-and-a-half line break.** **  ↑ Double line break.** **  

↑ Triple line break.** **  ↑ Quadruple line break.** **

**`

CSS

`.lb-half { display:block; margin-top:-0.5em; }
.lb-single { display:block; margin-top:0; }
.lb-one-and-a-half { display:block; margin-top:1.5em; }
.lb-double { display:block; margin-top:2em; }
.lb-quad { display:block; margin-top:4em; }

.br10px { line-height:10px; }
.br3 { line-height:3em; }`

换行

Image

内嵌横线

Image

HTML

`

Inline Horizontal Rule

You can insert an inline horizontal rule anywhere.   **↑ Invisible inline horizontal rule — a line-break.   **↑ Double-border inline horizontal rule.   **↑ Background inline horizontal rule.   **↑ Combination Inline horizontal rule.

`

CSS

`.hr { display:block; margin:0; }

.border { padding-top:1px; margin-top:25px; margin-bottom:0;
  width:auto; margin-left:0; margin-right:0;
  border-top:4px ridge blue; border-bottom:4px groove blue;
  background:none; background-color:yellow; }

.background { padding-top:5px; margin-top:25px; margin-bottom:0;
  width:auto; margin-left:76px; margin-right:76px; border:none;
  background:repeat-x left center url("diamond-blue.gif");
  background-color:transparent; }

.combo { padding-top:5px; margin-top:25px; margin-bottom:0;
  width:400px; margin-left:auto; margin-right:auto;
  border-top:4px ridge blue; border-bottom:4px groove blue;
  background:repeat-x left center url("diamond-blue.gif");
  background-color:white; }`

内嵌横线

Image

十二、对齐内容

本章讨论了将文本和内容与其包含的块水平和垂直对齐的设计模式。这些对齐模式在正常流程中工作,不使用绝对或相对定位。

前三种设计模式水平对齐内容。接下来的三个设计模式垂直对齐内容。最后一个设计模式和本章末尾的例子相当深奥,几乎没有实际应用。我将它们包含在内,以展示内置于内联格式上下文中的强大功能。

  • 文本缩进显示如何缩进第一行文本。
  • 悬挂缩进展示了如何创建悬挂缩进。
  • 水平对齐内容显示了如何将文本和内联内容向左、向右或居中对齐。它还展示了如何对齐文本和内联内容。
  • 垂直对齐的内容展示了如何将一个行内元素垂直对齐到其父元素的字体行。这些字体线定义了对齐上下文。
  • 垂直偏移内容展示了如何从父元素的基线垂直偏移一个行内元素。
  • 下标和上标展示了如何创建下标和上标文本,以及如何在所有浏览器中保持一致。
  • 嵌套对齐展示了如何嵌套对齐上下文。
  • 高级对齐示例不是一个设计模式,而是一个展示对齐和相对定位如何创建复杂的内联布局的有趣示例。

文本缩进

Image

HTML

`

Text Indent

****
**text-indent   indents the first line of a terminal block element, such as a paragraph,   division, heading, list item, or this table cell. **

****text-indent does   not work on inline elements, such as this span.****   text-indent     does work on inline-block elements, such as this span.

`

CSS

`.text-indent { text-indent:60px; }
.inline-block { display:inline-block; }

/*  Nonessential rules are not shown. */`

文本缩进

Image

悬挂缩进

Image

HTML

`

Hanging Indent

A hanging indent uses a negative value for
  text-indent and a positive value for padding-left.
  Hanging indents work only in terminal block elements like this paragraph.

If you do not want the hanging indent to
  go all the way to the left, make the positive value in padding-left
  larger than the absolute value of text-indent.

`

CSS

`.hanging-indent { text-indent:-50px; padding-left:50px; }
.hanging-indent2 { text-indent:-50px; padding-left:70px; }

/*  Nonessential rules are not shown. */`

悬挂缩进

Image

水平对齐内容

Image

HTML

`

Horizontal-Aligned Content

**text-align:left

**text-align:center

**text-align:right

**text-align:justify justifies the content so   that it is aligned to the left side and the right side. Most browsers adjust   the space between the words and objects to justify the text.

`

CSS

`.align-left { text-align:left; }
.align-center { text-align:center; }
.align-right { text-align:right; }
.align-justify { text-align:justify; }

/*  Nonessential rules are not shown. */`

水平对齐内容

Image

垂直对齐内容

Image

HTML

`

Vertical-Aligned Content

<span class="main">ÁMjx
      <img  class="text-top" src="bar.gif" alt="bar"
    /><span class="text-top text"> text-top
      <img  class="middle" src="bar.gif" alt="bar"
    /><span class="middle text"> middle
      <img  class="baseline" src="bar.gif" alt="bar"
    /><span class="baseline text"> baseline
      <img  class="text-bottom" src="bar.gif" alt="bar"
    /><span class="text-bottom text"> text-bottom

<p class="text">
  baseline → <img class="baseline" src="star.gif" alt="star" />
  text-top → <img class="text-top" src="star.gif" alt="star" />
  middle → <img class="middle" src="star.gif" alt="star" />
  text-bottom → <img class="text-bottom" src="star.gif" alt="star" />

`

CSS

`div { font-size:60px; line-height:normal; border:1px solid black; }
.main { background-color:gold; padding:0 10px; }

.text { font-size:18px; }

.text-top { vertical-align:text-top; }
.middle { vertical-align:middle; }
.baseline { vertical-align:baseline; }
.text-bottom { vertical-align:text-bottom; }`

垂直对齐内容

Image

垂直偏移内容

Image

HTML

`

Vertical-Offset Content

  _baseline__

<span class="raised">raised 1em
  <img class="raised" src="star.gif" alt="star" />

baseline

<span class="lowered">lowered 1em
  <img class="lowered" src="star.gif" alt="star" />

_baseline

`

CSS

`div { border:1px solid black; }

.baseline { vertical-align:baseline; }
.raised { vertical-align:1em; }
.lowered { vertical-align:-1em; }`

垂直偏移内容

Image

下标和上标

Image

HTML

`

Subscript and Superscript

sub**1** super**2 Mlle**

`

CSS

`sub { vertical-align:-0.5em; font-size:0.75em; }
sup { vertical-align:0.5em;  font-size:0.75em; }

.large { font-size:32px; }`

CSS Internet Explorer

**sub { font-size:0.9em; }** **sup { font-size:0.9em; }**

下标和上标

Image

嵌套对齐

Image

HTML

`

Nested Alignment


  ÁMjx
**      -20px
**    +35px
**    text-top
**    middle
**    baseline
**    text-bottom
**    -20px
  

 
`

CSS

`.ac1 { font-size:50px; }
.ac2 { font-size:30px; }
.ac3 { font-size:12px; }

.raise35px { vertical-align:35px; }
.lower20px { vertical-align:-20px; }
.text-top { vertical-align:text-top; }
.middle { vertical-align:middle; }
.baseline { vertical-align:baseline; }
.text-bottom { vertical-align:text-bottom; }

/*  Nonessential rules are not shown. */`

嵌套对齐

Image

高级对齐示例

Image

HTML

`

Advanced Alignment Example

** **  **     **ƒ(x) =     **∑     **n=0     **∞     **anx **    **       (n-12        )

`

CSS

`sub { vertical-align:-0.3em; font-size:0.75em; }

.ac1 {font-size:4em; font-family:"Times New Roman" serif; white-space:nowrap; }
.ac1-func{vertical-align:0.6em; font-size:0.3em; font-style:italic; }
.ac1-sum {vertical-align:0.2em; font-size:0.6em; position:relative; left:-0.1em; }
.ac1-max {vertical-align:3em;   font-size:0.2em; position:relative; left:-6em; }
.ac1-min {vertical-align:-1em;  font-size:0.2em; position:relative; left:-3.3em; }
.ac1-formula { vertical-align:0.6em; font-size:0.3em; font-style:italic;
  position:relative; left:-4em; letter-spacing:0.1em; }

.ac2 {vertical-align:0.4em; font-size:1.5em; position:relative; left:-0.3em; }
.ac2-num {vertical-align:0.7em;  font-size:0.4em; border-bottom:1px solid black; }
.ac2-dnm {vertical-align:-0.4em; font-size:0.4em; position:relative; left:-1.4em; }
.ac2-close { position:relative; left:-0.65em; }`

高级对齐示例

Image

十三、块

这一章的主要目的是展示通过样式化块来强调文档结构的各种方法。其他章节中的许多设计模式都适用于块,但是本章包含了特定于样式块元素以显示文档结构的模式。

章节大纲

  • 结构意义展示了块如何创建层次和顺序结构。
  • 视觉结构展示了如何设计块的样式以显示文档结构。
  • Section 展示了如何将你的文档组织成几个部分,以便于搜索引擎和文档处理程序进行样式化和更好的结构化。
  • 列表展示了许多创建列表和列表标记的方法。
  • 显示了如何使用背景图片给列表添加项目符号。
  • inline展示了如何渲染一个块元素,就像它是一个内联元素一样。这允许块从左到右呈现,并换行。
  • 折叠边距显示了如何折叠和取消折叠块元素之间的垂直边距。
  • Run-In 展示了如何将一个块运行到下一个兄弟块中,就好像它是下一个块中的内联元素一样。插入式标题节省空间,非常吸引人。
  • 水平标尺展示了如何使用水平标尺并设置其样式,尽管 Internet Explorer 7 会导致一些问题,它拒绝从<hr />中删除其内置样式。
  • 块间隔符展示了如何在选择的块之间插入精确的垂直间隔,而不必单独调整边距。
  • 块空间移除器展示了如何移除选定块之间的精确垂直空间,而无需单独调整边距。
  • Left Marginal 展示了如何从正常流程中提取标题、注释、警告和图像,并将它们移动到一个较宽的左边距中。
  • 右边距的工作方式类似左边距,除了项目被移动到右边。

结构意义

Image

HTML

`
<div id="wrapper">
**  

**Structural Meaning

**  

**  

**
**    

An Example of Structural Meaning


**    

**      
**
**        

This heading identifies the topic of its section.


**        

This paragraph introduces the topic of the heading.


**        

**This paragraph continues the topic of the heading.

**      

**Everything in a document is related. The block structure identifies the
  order and intensity of the relationships. The more elements you wrap around
  content, the more tightly connected it becomes to ancestors and siblings.

**      

    **
    **        
  • This is an unordered list.

  • **        
  • List items are more closely related than items in divisions.

  • **        
  • **There is no significance to the sequence of unordered list items.

**      

New Structural Elements


**        
**        
**        
**        
**        
**        
articleAn article or other complete piece of content
asideSecondary content, such as a sidebar
footerFooter region
headerHeader region
navNavigation region
**sectionA logical region of a page
    

**    

**
**      

**A footer typically contains information about its section such as who wrote it.

  

**  <aside** id="sidebar">
**    

**An aside indicates content that is tangentially related to the content around it. Can
be used as a sidebar.

`

结构意义

Image

视觉结构

参见结构化含义设计模式中的例子。

CSS(用于结构意义设计模式)

`h1 { margin:0; font-size:1.9em; }
h2 { margin:0; margin-top:3px; font-size:1.2em; }

header,nav,section,aside,footer,article{ display:block; }
ul,div,td,th { border:1px solid black; background-color:gold; margin-top:20px; }
div { padding:0 10px; }
table { border-collapse:collapse; margin:5px 0; }
td,th { background-color:white; width:20%; text-align:center; padding:2px; }
ul { margin-left:0; padding:0 40px; }
p,li { margin:0; padding:2px 0; }`

造型异常

当您设计项目类别时,样式表很好用,但是当您设计例外时,它很快就变得很麻烦。要设置一个元素的样式,通常需要向它添加一个 ID,并在样式表中设置 ID 的样式。这对于单个文档来说是一个小问题,但是随着时间的推移,随着文档的变化、样式的改变以及数百个文档共享相同的样式表,这个问题会变成一个维护问题。例如,由于用于特殊样式的 ID 是元素的一部分,因此当元素移动时,特殊样式也会随之移动。当您修改文档时,这可能会导致意想不到的结果,并且会让您徒劳地寻找问题的原因。

水平标尺、块间隔符或块空间移除器设计模式是设计异常情况的好解决方案,因为它们将元素插入到文档中。该元素具有结构化的含义,是自文档化的,并且易于重新定位。您可以使用标准类来设计这些间隔元素的样式,这样您就不再是设计异常了。间隔元件仅用于特殊情况。

位置造型

有时,您可能希望对某个元素进行样式化,因为它位于特定的位置。例如,您可能希望更改块的第一个子元素之前和最后一个子元素之后的边距量,因为折叠的边距对第一个和最后一个子元素的作用不同。如果将异常边距直接应用于第一个子元素,然后移动第一个子元素使其成为中间的子元素,其异常边距也会随之移动。这不是您想要的结果,因为您想要样式化位置——而不是元素。

设置位置样式的一种方法是使用水平标尺、块间隔符或块空间移除符设计模式。这是因为很容易将一个间隔元素保持在正确的位置——特别是如果你直观地命名它的类,比如"first-child""last-child"。CSS 3 位置选择器对于位置样式来说足够强大,并且几乎完全被现代浏览器支持。

视觉结构

Image

Image

HTML

`

Section

<section class="introduction”>
   

Introduction


   

This paragraph is about the introduction.


  

Content


  

This paragraph is about the content.

**  

**
    

Subsection Example


      
  • This list item relates to the subsection example.

  •         
  • This list item relates to the subsection example.

  

`

CSS

section { padding:10px; margin:10px 0; background-color:gold;   border-left:1px solid gray; border-right:2px solid black;   border-top:1px solid gray; border-bottom:2px solid black; display:block; } section p { margin:0; margin-top:5px; } section h2 { margin:0; margin-bottom:10px; } section h3 { margin:0; margin-bottom:10px; } section.example { background-color:white; } section section { margin-bottom:0; }

Image

列表

Image

HTML

`

Lists

Normal Lists

  
  • **List item with custom bullet
  •     
  • **List item with circle bullet
  •     
  • **List item with numbered bullet
  •     
  • **List item with disc bullet displayed inside the margin
  •     
  • ****-faux marker
  •     
  • ****–&ndash;
  •     
  • ****—&mdash;

Faux Lists

  **display:list-item     

****1:8-5faux marker

    

****·&middot;

    

****•&bull;

    

****◊&loz;

    

****›&rsaquo;

    

****»&raquo;

`

CSS

`ul { margin-left:0; padding-left:0; } /* Normalized list */
ul li { margin-left:60px; }

.listed { margin-left:60px; display:list-item; list-style:square; }

.list { margin-left:60px; }
.marker { float:left; margin-left:-60px; width:60px; text-align:center; }

.custom  { list-style-image:url("check.gif"); }
.circle  { list-style-type:circle; }
.decimal { list-style-type:decimal; }
.inside  { list-style-position:inside; }
.none    { list-style-type:none; }

/* Nonessential rules are not shown. */`

列表

Image

背景项目符号

Image

HTML

`

Background Bulleted

    **   
  • **Unordered list item with a background bullet
    **   
  1. **Ordered list item with a background bullet
**   
**Definition term with a background bullet
  
**Definition data with a background bullet
**   

**Faux list with a background bullet

  

**Faux list with a background bullet

`

CSS

`.bb-list { padding-left:40px; margin-left:0; margin-top:20px; }
.bb-list li,
.bb-list dt,
.bb-list dd,
.bb-list p { padding-left:40px; margin-left:-40px; list-style-type:none;
  margin-top:0; margin-bottom:0; }

.bb1 { background:url("check.gif") no-repeat 10px 1px; }
.bb2 { background:url("star.gif") no-repeat 10px 1px; }`

背景项目符号

Image

内联

Image

HTML

`

Inlined

  

Normal Paragraph

       
Normal Tabler1c2r1c3
row2r2c2r2c3
  
  • Normal List
  • Normal List
**  

**Inlined Paragraph

**  **          
Inlined Tabler1c2r1c3
row2r2c2r2c3
**  
  • **Inlined List
  • **  
  • **Inlined List
`

CSS

`div { padding:10px; margin-bottom:15px; border:2px solid black; }
table, p, td, ul, li { margin-top:0px; margin-bottom:10px; padding-right:5px; }
p, td, ul, li { background-color:gold; padding-top:5px; padding-bottom:5px;
  border-left:1px solid gray; border-right:2px solid black;
  border-top:1px solid gray; border-bottom:2px solid black; }

.inlined { display:inline; line-height:normal; padding:5px; margin:5px; vertical-align:bottom;
}
table.inlined{ display:inline-table; }`

内联

Image

折叠页边距

Image

HTML

`

Collapsed Margins

**
**
**   
  **   **   **

**Uncollapsed (transparent padding) ↑↓

  **

**Uncollapsed (transparent border) ↑

`

CSS

`div { margin:10px; padding-left:30px; background-color:gold;
  background-image: url("ruler.gif"); background-repeat:repeat-y; }
.border { border:2px solid black; }

.collapsed { margin-top:20px; margin-bottom:20px; }

.uncollapsed1 { margin-top:0; margin-bottom:0;
**  padding-top:20px; padding-bottom:20px;**
**  background-color:transparent; }**

.uncollapsed2 { margin-top:0; margin-bottom:0;
**  border-top:20px solid transparent;**
**  border-bottom:20px solid transparent; }**`

折叠页边距

Image

磨合

Image

HTML

`

Run-In

  

Normal Heading

**  

**This is a paragraph following the heading. Notice     how the previous heading and this paragraph are separate blocks.

  

This is another paragraph following the first paragraph.

**  ** **    

Run-In Heading

** **    This is a paragraph following the heading. Notice how** **      the heading runs into the first line of this paragraph, and notice how** **      its styles are transferred to the run-in container.

** **  **   

This is another paragraph following the first paragraph.

`

CSS

`section { padding:10px; margin-bottom:20px; background-color:gold;
  border-left:1px solid gray; border-right:2px solid black;
  border-top:1px solid gray; border-bottom:2px solid black; display: block; }
.indent { margin-left:20px; border-left:4px solid black; padding-left:20px; }

.run-in { display:inline; }
.run-in-container h2 { padding-right:20px; }
.run-in-container p { font-style:italic; }`

磨合

Image

横尺

Image

HTML

`

Horizontal Rule

This paragraph is followed by a standard horizontal rule.


This paragraph is followed by an embedded and styled horizontal rule.


This paragraph is preceded by an embedded and styled horizontal rule.

`

CSS

`.hr { height:40px; width:200px;
  margin:0 auto 0 auto;
  border:0;
  background:url("hr.gif") repeat-x left center;
  line-height:1px; font-size:1px; }

.hr hr { display:none; }

/* Nonessential rules are not shown. */`

横尺

Image

垫块垫片

Image

HTML

`

Block Spacer

This paragraph is not followed by a block spacer.

This paragraph is followed by a block spacer.

This paragraph is preceded by the same block spacer.

This paragraph is not preceded by a block spacer.

`

CSS

`p { margin:0; padding:5px; background-color:gold;
  border-left:1px solid gray; border-right:2px solid black;
  border-top:1px solid gray; border-bottom:2px solid black; }

.spacer-large { padding-bottom:32px; }`

垫块垫片

Image

块空间去除器

Image

HTML

`

Block Space Remover

  

This paragraph has 32-pixel top and bottom margins.

  

This paragraph has 32-pixel top and bottom margins.

**  
**   

This paragraph has 32-pixel top and bottom margins,     but it is preceded and followed by a block space remover.

**  
**   

This paragraph has 32-pixel top and bottom margins,     but it is preceded and followed by a block space remover.

**  
**  
`

CSS

`section { border:2px solid black; margin-bottom:32px; display:block; }
p { margin-top:32px; margin-bottom:32px; padding:5px; background-color:gold;
  border-left:1px solid gray; border-right:2px solid black;
  border-top:1px solid gray; border-bottom:2px solid black; }

.space-remover-large { margin-top:-32px; }`

块空间去除器

Image

左旁注

Image

HTML

`

Left Marginal


<span class="marginal-header">ProblemYou want to
  excerpt an element and move it into the left margin.<span class="marginal-note">
  You want to put images and notes in the margin. You want it to align
  vertically with where it would have been placed in the flow.

****SolutionYou can   create a large left margin and use absolute positioning to move content   into it.

**Disadvantages   Nothing prevents marginal elements from vertically overlapping each other.   **OVERLAP!   However, you can prevent marginal elements from overlapping with content on   the right by creating a wide enough left margin.

  **AdvantagesstarYou can render inline markup like tables.

`

CSS

**.left-marginal { position:relative; width:480px;** **  margin-left:230px; margin-right:auto; }** .marginal-header { position:absolute; left:-220px; width:160px; font-weight:bold; } .marginal-note { position:absolute; left:-180px; width:150px;   font-style:italic; font-size:14px; font-weight:normal; } .marginal-alert { position:absolute; left:-180px; font-style:italic; } .marginal-flag { position:absolute; left:-40px; margin-top:-5px; }

左旁注

Image

右旁注

Image

HTML

`

Right Marginal

****ProblemYou want to   excerpt an element and move it to the right margin. **   You want to put images and notes in the margin. You want it to align   vertically with where it would have been placed in the normal flow.

****SolutionYou can   create a large right margin and use absolute positioning to move content   into it.

**Disadvantages   Nothing prevents marginal elements from vertically overlapping each other.   **OVERLAP!   However, you can prevent marginal elements from overlapping with content on   the left by creating a wide enough right margin.

  **AdvantagesstarYou can render inline markup like tables.

`

CSS

`body { width:702px; }
.right-marginal { position:relative; width:480px;
**  margin-right:210px; margin-left:auto; }**

.marginal-header {position:absolute; right:-230px; width:170px; font-weight:bold; }
.marginal-note { position:absolute; right:-230px; width:150px;
  font-style:italic; font-size:14px; font-weight:normal; }
.marginal-alert {position:absolute; right:-230px; width:150px; font-style:italic; }
.marginal-flag { position:absolute; right:-30px;  margin-top:-5px; }`

右旁注

Image

十四、图象

本章展示了如何使用图像来创建美观实用的文档,以便快速访问和下载。

章节大纲

  • 图片展示了如何使用<img>元素。它还对比了 GIF、JPG 和 PNG 图像格式的优缺点。
  • Image Map 展示了如何用链接到其他页面的可点击区域覆盖图像。
  • 淡出展示了如何使用渐变图像在内容后面添加微妙的阴影。它还展示了如何创建适应当前背景的变色龙渐变。
  • 半透明展示了如何将一个部分透明的背景放在一个元素的后面,这样它就从它下面的背景中突出来,而不会模糊它。
  • 替换文本展示了如何用图像替换文本,同时保持对非视觉用户的可访问性。当图像不可用时,这种技术也显示文本。
  • 图像上的内容展示了如何在图像上叠加文本和其他图像。
  • 背景图片上的内容展示了如何在背景图片上覆盖文本和其他图片。
  • CSS Sprite 展示了如何将多个图像嵌入到一个文件中,并将它们独立显示为文档中不同元素的背景。
  • 基本阴影图像展示了如何在不修改图像本身的情况下,创建并应用一个简单的阴影到图像上。
  • 阴影图像展示了一种将阴影应用于任何尺寸图像的通用方法。
  • 圆角展示了如何将一个元素的边框圆角化,以及如何创建可以想象的任何风格的自定义边框。
  • 图片示例在一个文档中展示了这些模式。

图像

Image

HTML

`<img width="742" height="556" src="cl1-99.jpg" alt="Crater Lake 1" />

`

CSS

`img { display:block; width:auto; height:auto; }

/* Nonessential rules are not shown. */`

举例

这个例子包含了我在 2003 年 8 月 4 日拍摄的火山口湖照片的八个不同版本。源图像为 742×556 像素,文件大小为 1,238,822 字节。我对图像进行了处理,创建了八个独立的文件——每个文件都有不同的图像类型和质量。

第一个图像是最高质量的 JPG 图像,它将文件大小减少到 275,798 字节。这减少了五倍。在 JPG 的最高质量,很难看到任何质量的损失。第二个图像是 90%质量的 JPG,这将文件大小减少到 81,248 字节。这减少了 15 倍。在 90%的质量下,用放大镜几乎看不出区别。您可以在第三个和第四个图像中看到差异,这两个图像是 75%和 50%质量的 jpg,分别为 41,290 和 14,841 字节。这分别减少了 30 倍和 84 倍。

第五张和第六张图是 gif。这些图像比 JPG 图像质量差,尺寸大。这不是对 gif 的公平测试,因为它们不是为包含成千上万种颜色的真实图像而设计的。gif 生成的文件较小,用于包含 256 色或更少颜色的计算机生成的图像时质量较好。

第七个和第八个图像是 png。这些图像的质量最好,文件大小略小于质量最好的 JPG,但无法通过增加压缩率来缩小文件大小。

图像

Image

影像地图

Image

HTML

`

Image Map

Northwest USA

<img src="nw.gif" usemap="#nw-map" alt="Northwest USA" width="290" height="200" />

**  <area** href="washington.html" alt="Washington"
**    shape="poly"** coords="176,8, 164,89, 75,89, 40,72, 45,8" />

**  <area** href="oregon.html" alt="Oregon"
**    shape="rect"** coords="9,90, 155,180" />

**  <area** href="idaho.html" alt="Idaho"
**    shape="circle"** coords="212, 134,55" />
 `

CSS

/* There are no CSS properties for styling image maps. */

影像地图

Image

淡出

Image

HTML

`

Fade-Out

**g1 Horizontal Fade-Out of GIF image to gold background color.

**g2 Horizontal Fade-Out of any background color to PNG image.

**g3 Vertical Fade-Out of GIF image to white background color.

**g4 Vertical Fade-Out of JPG image to white background color.

**g5 Vertical Fade-Out of any background color to PNG image.

**g6 Vertical Fade-Out of PNG image to any background color.

**g7 Vertical Fade-Out of PNG image to any background color from top and bottom.

`

CSS

`.g1 { background:url("h-white2gold.gif") repeat-y left top gold; }
.g2 { background:url("h-trans2white.png") repeat-y right top royalblue; }

.g3 { background:url("v-gold2white.gif") repeat-x left top white; }
.g4 { background:url("v-lightning.jpg") repeat-x left top white; }
.g5 { background:url("v-trans2white.png") repeat-x left bottom red; }
.g6 { background:url("v-white2trans.png") repeat-x left top green; }
.g7 {background:url("v-white2trans.png") repeat-x left top, url("v-trans2white.png") repeat-x
left bottom green; }

/* Nonessential rules are not shown. */`

淡出

Image

半透明

Image

HTML

`

Semi-transparent

  Northwest

<span id="washington" class="overlay">Washington
  <span id="oregon" class="overlay">Oregon
  <span id="idaho" class="overlay">Idaho

<p id="note1">
    Semi-transparent backgrounds are gray in Internet Explorer 6, but they are
    semi-transparent in Internet Explorer 7 and all other major browsers.

`

CSS

`.overlay { background:url("semi-transparent.png") repeat; }

#note1 { background:url("trans2white.png") bottom left repeat-x; }

/* Nonessential rules are not shown. */`

半透明

Image

替换文字

Image

HTML

`

Replaced Text

**Heading **2**

`

CSS

`#h2 { position:relative; width:250px; height:76px;
  padding:0; overflow:hidden; }

h2 span { position:absolute; width:250px; height:76px;

left:0; top:0; margin:0;
  background:url("heading2.jpg") no-repeat; }`

替换文字

Image

内容超过图像

Image

HTML

`

Content over Image

**   

**Crater Lake North Rim

  

** August 4, 2003     

**  Crater Lake North Rim August 4, 2003
`

CSS

`.figure { float:left; position:relative;
  color:white; background-color:black; }

.figure .caption { position:absolute; margin:15px; left:0; top:0;
  font-size:1.05em; }

.framed { display:block;
  border-left:1px solid gray; border-right:2px solid black;
  border-top:1px solid gray; border-bottom:2px solid black; }

crater-date { position:absolute; left:0; bottom:10px; width:518px;

text-align:center; color:white; font-size:0.8em; }`

内容超过图像

Image

背景图片上的内容

Image

HTML

`

Content over Background Image

  

**Crater Lake North Rim

  

** August 4, 2003   

`

CSS

`#crater-lake { position:relative; padding:0; width:700px; height:500px;
**  background:black url("crater-lake.jpg") no-repeat center center; }**

crater-lake .caption { position:absolute; margin:15px; left:0; top:0;

font-size:1.05em; color:white; }

crater-date { position:absolute; left:0; bottom:10px; width:700px;

text-align:center; color:white; font-size:0.8em; }

/* Nonessential rules are not shown. */`

背景图片上的内容

Image

CSS 雪碧

Image

HTML

`

CSS Sprite

  Northwest USA

<a id="olympia" class="bang-bg" href="olympia.html" title="Olympia">
    <span class="screenreader-only">Olympia

<a id="salem" class="flag-bg" href="salem.html" title="Salem">
    <span class="screenreader-only">Salem

<a id="boise" class="star-bg" href="boise.html" title="Boise">
    <span class="screenreader-only">Boise

`

CSS

`.bang-bg { background:url("bt.gif") -48px -16px; width:16px; height:16px; }
.flag-bg { background:url("bt.gif") -64px -16px; width:16px; height:16px; }
.star-bg { background:url("bt.gif") -64px -32px; width:16px; height:16px; }

.star-bg:hover { background-image:url("wt.gif"); background-color:black; }
.flag-bg:hover { background-image:url("wt.gif"); background-color:black; }
.bang-bg:hover { background-image:url("wt.gif"); background-color:black; }

.screenreader-only { position:absolute; left:-9999px; top:-9999px;
  width:1px; height:1px; overflow:hidden; }

/* Nonessential rules are not shown. */`

CSS 雪碧

Image

CSS 雪碧账户。

Image

bt.gif 中使用的 16×16 子画面的偏移

举例

我在例子中使用了两个 CSS sprite 文件:bt.gif(见图 14-1)和wt.gif。这些文件名代表透明背景上的黑色图像和透明背景上的白色图像。当用户将鼠标悬停在图像上时,悬停选择器会切换出bt.gif,并替换为wt.gif,将颜色从黑色转换为白色。背景也变为黑色,透过图像的透明部分显示出来。

我在示例目录中包含了示例中没有使用的另外两个 sprite 文件。它们被命名为tb.giftw.gif。这些文件名代表黑盒中的透明图像和白盒中的透明图像。这些嵌入的图像是黑色和白色的小盒子,中间是透明的图像,可以改变颜色以匹配背景。

我从一个名为 bitcons 的图标集中创建了这四个 CSS 精灵。我把所有嵌入的图像都做成了 16×16 像素,就像原始图像一样。这些图标是免费授权的,可在[somerandomdude.net/srd-projects/bitcons](http://somerandomdude.net/srd-projects/bitcons)获得。同样,您可以在项目中自由使用这四个 CSS sprite 文件。

当制作你自己的 CSS 精灵图片时,你可以在精灵中嵌入任何大小的图片。嵌入的图像不需要大小相同。你只需要知道每个嵌入图像的偏移量和大小。

CSS 雪碧账户。

Image

基本阴影图像

Image

HTML

`

Basic Shadowed Image

`

CSS

img.shadowed { padding-right:20px;   padding-bottom:20px;   background-image:url("shadow.jpg");   background-position:right bottom;   background-repeat:no-repeat; }

基本阴影图像

Image

阴影图像

Image

T2shadow.jpg

Image

shadow-rt.jpg``shadow-lb.jpg是从shadow.jpg中提取出来的。

Image

shadow-rt.jpg缩进并关闭阴影的右上边缘。

Image

shadow-lb.jpg缩进并关闭阴影的左下边缘。

阴影图像

Image

阴影图像 cont。

Image

阴影图像的合成视图

阴影图像 cont。

Image

阴影图像 cont。

Image

HTML

`

Shadowed Image

  
    
      
        Crater Lake
`

CSS

`.shrinkwrapped { float:left; }

.shadowed { background-image:url("shadow.jpg");
  background-position:right bottom; background-repeat:no-repeat; }

.shadowed-rt { background-image:url("shadow-rt.jpg");
  background-position:right -80px; background-repeat:no-repeat; }

.shadowed-lb { padding-right:20px; padding-bottom:20px;
  background-image:url("shadow-lb.jpg");
  background-position:-80px bottom; background-repeat:no-repeat; }`

阴影图像 cont。

Image

圆角

Image

HTML

`<div class="bg"><div class="tl"><div class="br pad">
  You can nest two divisions to create two opposite rounded corners.

**
**
**   You can nest two divisions to create two opposite rounded corners.
**   
**
**
**
**   You can nest four divisions to create four rounded corners.
You can have a single division with multiple backgrounds
`

CSS

`.bg { background:url("bg.gif") bottom left repeat-x white; margin-top:20px; }

.tl { background:url("rc.gif") top left no-repeat; }
.br { background:url("rc.gif") bottom right no-repeat; }
.tr { background:url("rc.gif") top right no-repeat; }
.bl { background:url("rc.gif") bottom left no-repeat; }

.trc { background:url("rc-trc.gif") top right no-repeat; }
.blc { background:url("rc-blc.gif") bottom left no-repeat; }

.pad { padding:10px; }
.mbg{ background: url("rc-trc.gif") top right no-repeat, url("rc-blc.gif") bottom left no-repeat, url("rc.gif") top left no-repeat, url("rc.gif") bottom right no-repeat, url("bg.gif")
bottom left repeat-x white; margin-top:20px; }`

圆角

Image

圆角连续。

Image

从圆角矩形图像创建圆角

创建三个圆角矩形图像

在示例中,我从一个 1600×1600 的透明画布开始。我添加了一个环绕画布边缘的圆角矩形。圆角矩形有一个透明的内部。我用外部背景色填充了每个圆角的外部像素,在我的例子中是白色。这使得它们不透明,所以每个角的外部用背景色覆盖内部背景。注意在图 14-7 中,如果第一个圆角矩形的左上角和第二个圆角矩形的右下角不是不透明的,它们将如何显示内部背景。最后,我将图像保存为rc.gif

为了创建剪切图像,我剪切掉圆角矩形图像的左下角和右上角,并将它们保存为单独的 GIF 图像,命名为tr.gifbl.gif。我确保角落的外部保持不透明,内部保持透明。否则,他们不会在外面隐藏外部方形边框,让背景在里面显示出来。我把每一个切口的尺寸都设计得足够大,可以用一个圆角盖住方形的角。

创建三个圆角矩形图像很简单:创建一个透明的圆角矩形;填充其圆角的外部;并将左下角和右上角保存为单独的图像。

圆角连续。

Image

图像示例

Image

HTML 的代表性摘录

`

Northwest USA

  

Washington
  Oregon
  Idaho


    Olympia

  
    Salem


    

      

Click a state to load information about that state.


      

Click a symbol to load information about that location.


      

`

图像示例

Image

CSS 代表性摘录

`.shadowed { padding-right:12px; padding-bottom:12px;
  background:url("shadow.jpg") right bottom no-repeat; }

.screenreader-only { position:absolute; left:-9999px; top:-9999px;
  width:1px; height:1px; overflow:hidden; }

a { text-decoration:none; color:black; }
a:hover { border-left:1px solid silver; border-right:1px solid gray; color:white;
  border-top:1px solid silver; border-bottom:1px solid gray;
  background-image:url("semi-transparent.png"); background-repeat:repeat-x; }
.overlay { padding:2px 4px; }

.bg { background:url("white2trans.png") top left repeat-x yellow;
  margin-top:20px; }
.tl { background:url("rc.gif") top left no-repeat; }
.br { background:url("rc.gif") bottom right no-repeat; }
.trc { background:url("rc-trc.gif") top right no-repeat; }
.blc { background:url("rc-blc.gif") bottom left no-repeat; }
.pad { padding:10px; }

.bang-bg { background:url("bt.gif") -48px -16px; width:16px; height:16px; }
.flag-bg { background:url("bt.gif") -64px -16px; width:16px; height:16px;
 }
.star-bg { background:url("bt.gif") -64px -32px; width:16px; height:16px; }

.bang-bg:hover { background-image:url("wt.gif"); background-color:black; }
.star-bg:hover { background-image:url("wt.gif"); background-color:black; }
.flag-bg:hover { background-image:url("wt.gif"); background-color:black; }

states

#washington { position:absolute; top:35px; left:80px; }
  #oregon { position:absolute; top:135px; left:85px; }
  #idaho { position:absolute; top:150px; left:210px; }`

十九、表格

表格是 HTML 中最有用和最复杂的结构之一。这是关于表格的两章中的第一章。本章探讨了表格的 HTML 结构以及如何设计它们的样式。下一章将探讨在表格中自动布置列的许多方法。表格的目的是识别表格数据并设置其样式。

章节大纲

  • Table 展示了如何创建和样式化一个表格的基本结构。
  • 行和列组展示了如何创建和样式化行标题、行页脚、行组、列组和列。
  • 表格选择器展示了如何从列、行和行组中选择单元格。
  • 分隔边框展示了如何分隔表格边框和单元格边框。
  • 折叠边框展示了如何组合表格和单元格边框。
  • 设计折叠边框展示了如何设计折叠边框。
  • 隐藏和删除的单元格显示如何隐藏或删除单元格。
  • 移除和隐藏行和列展示了如何移除或隐藏单元格的行、行组和列。
  • 垂直对齐数据展示了如何将数据垂直对齐到单元格的顶部、中部、底部或基线。
  • 条纹表展示了如何给行分配交替的背景。
  • 可访问的表格展示了如何创建一个对盲人用户友好的表格。
  • 展示了如何将任何元素变成表格、行或单元格。
  • 表格布局展示了如何创建四种类型的表格:收缩大小拉伸固定

Image

HTML

`

Table

Simple Table

****   ****   ****
12 3 4 5 6
7 89 10 11 12

Table with Spanned Rows and Cells

<**table>**    **1 2-6**                   8 9     12 `

CSS

`table { width:auto; height:1px; table-layout:auto; border-collapse:collapse;
  margin-left:20px; border:1px solid black; }

td, th { width:50px; height:1px; overflow:hidden; visibility:visible;
  border:1px solid black; padding:5px; background:gold;
  text-align:center; vertical-align:middle; text-indent:5px; }`

Image

行列分组

Image

HTML

`

Row and Column Groups

Row Groups

****   **** ** ** ** **   **** ** ** ** **   **** ** ** ** **
**thead**2 **3 **4
**tfoot**10**11**12
**tbody**6 **7 **8

Columns

**** **  **            

               
    

1 2-6
8 9   12
`

CSS

`table.example1 thead { background:orange; color:black; }
table.example1 tbody { background:gold; color:black; }
table.example1 tfoot { background:firebrick; color:white; }
.col1 { background:wheat; }
.col2 { background:gold; }
.col3 { background:orange; }
.col4 { background:tomato; }
.col5 { background:firebrick; }
.col6 { background:black; color:white; }

/* Nonessential styles are not shown */`

行和列组

Image

表格选择器

Image

HTML

`

Table Selectors



  
    <tr class="r1"> <td class="c1">r1 c1 <td class="c2">c2
                    <td class="c3">c3    <td class="c4">c4
                    <td class="c5">c5    <td class="c6">c6
 ** **
    <tr class="r3">
                        
                        
  
    <tr class="r2">
                        
                        

r3 c1 c2c3c4c5c6
r2 c1 c2c3c4c5c6
`

CSS

`table,td,th { border:1px solid black; }        /* Selecting all tables and cells /
td,th { background-color:white; }              /
Selecting all cells */

t1 { border-collapse:collapse; }              /* Selecting table */

t1 thead td { font-weight:bold; }             /* Selecting cells in head */

t1 tfoot td { font-style:italic; }            /* Selecting cells in foot */

t1 tbody td { font-variant:small-caps; }      /* Selecting cells in body */

t1 .b1  td { font-size:1.2em; }               /* Selecting cells in body */

t1 .c3 { display:none; }                      /* Selecting cells in column */

t1 .c4

t1 .r1 { background-color:gold; color:black; }     /* Selecting row-no effect*/

t1 .r2 td { background-color:gold; color:black; }  /* Selecting cells in row */

t1 .r2 .c6 { font-size:1.8em; font-weight:bold; } /* Selecting cell */

/* Nonessential styles are not shown */`

表格选择器

Image

分隔边框

Image

HTML

`

Separated Borders

Boxed Table

****
12-6
78 ** **11

Boxed Cells

****
12-6
78 ** **11

Boxed Table and Cells

****
12-6
78 ** **11
`

CSS

`table { border-collapse:separate; }
.boxed-table { border:1px solid black; }
.boxed-cells td { border:1px solid black; }
.boxed-cells td.x { border:none; }

/* Nonessential styles are not shown */`

分隔边框

Image

折叠边框

Image

HTML

`

Collapsed Borders

Boxed Table

****
12-6
78  11

Boxed Cells

****
12-6
78  11

Boxed Table and Cells

****
12-6
78  11
`

CSS

`table { border-collapse:collapse; }
.boxed-table { border:1px solid black; }
.boxed-cells td { border:1px solid black; }
.boxed-cells td.x { border:none; }

/* Nonessential styles are not shown */`

折叠边框

Image

样式折叠的边框

Image

HTML

`

Styled Collapsed Borders


   <td class="c1">1 <td class="c2">2
   <td class="c1">1 <td class="c2">2
`

CSS

`table { border-collapse:collapse; }             /* Table and cells borders */
table,td,th { border:5px solid red; }

t1 { border-left:1px solid black; }            /* Left table border */

t1 .c1

t1 { border-right:2px solid black; }           /* Right table border */

t1 .c2

t1 .c1 { border-right:1px dotted black; }      /* Interior column border */

t1 .c2

t1 { border-top:1px solid black; }             /* Top table border */

t1 .r1 td

t1 { border-bottom:2px solid black; }          /* Bottom table border */

t1 .r2 td

t1 .r1 td { border-bottom:1px dotted black; }  /* Interior row border */

t1 .r2 td

/* Nonessential styles are not shown */`

样式折叠的边框

Image

隐藏和删除单元格

Image

HTML

`

Hidden and Removed Cells

Cell 1 is hidden and Cell 3 is removed.
This moves cell 4   into cell 3's place and creates a missing cell at the end.


Collapsed Borders


Separated Borders

1234
1234
`

CSS

`table, td, th { border:1px solid black; }

.separated { border-collapse:separate; }
.collapsed { border-collapse:collapse; }

.x { display:none; }
.h { visibility:hidden; }

/* Nonessential styles are not shown */`

隐藏和删除单元格

Image

删除和隐藏行和列

Image

HTML

`

Removed & Hidden Rows & Columns


  
    <tr  class="r1"> <td class="c1">r1 c1  <td class="c2">2
                     <td class="c3">r1 c3  <td class="c4">4

<tr  class="r2">

  
                       


    <tr  class="r3">   
                       

<tr  class="r4">

  
                       

<tbody class="b3">
    <tr  class="r5">

  
                       

r2 c12r2 c34
r3 c12r3 c34
r4 c12r4 c34
r5 c12r5 c34
`

CSS

`#t1 .c2 { display:none; }       /* Removing column */

t1 .c3 { visibility:hidden; }  /* Hiding column */

t1 .r2 { visibility:hidden; }  /* Hiding row */

t1 .b2 { display:none; }       /* Removing row group */

/* Nonessential styles are not shown */`

删除和隐藏行和列

Image

垂直对齐的数据

Image

HTML

`

Vertical-Aligned Data

       

<td class="align-middle">These lines of text are vertically aligned
      to the middle of the cell.

<td class="align-bottom">These lines of text are vertically aligned
      to the bottom of the cell.

These lines of text are vertically aligned       to the top of the cell.
`

CSS

`.align-top    { height:200px; vertical-align:top; }
.align-middle { height:200px; vertical-align:middle; }
.align-bottom { height:200px; vertical-align:bottom; }

/* Nonessential styles are not shown */`

垂直对齐的数据

Image

条纹表

Image

HTML

`

Striped Tables

<tr class="r1 odd">


                      

     
                      

<tr class="r3 odd">


                      

     
                      

<tr class="r5 odd">


                      

r1 c1 c2   c3 c4
r2 c1 c2   c3 c4
r3 c1 c2   c3 c4
r4 c1 c2   c3 c4
r5 c1 c2   c3 c4
`

CSS

`#ts td { background:white; }                     /* Background of all cells */

t1 .odd td { background:palegreen; }            /* Alternating Row Background */

t1 td.c3 { background:darkgreen; color:white; } /* Column Background */

/* Nonessential styles are not shown */`

条纹表

Image

Image

HTML

`

Tabled, Rowed, and Celled

Before

  
    
division
    
division
       span     span

After being rendered as a table with rows and cells

  
    
division
    
division
             span         span
`

CSS

`div,span { border:1px solid black; background-color:gold; padding:5px; }

.tabled { display:table; border-collapse:collapse; }
.rowed { display:table-row; }
.celled { display:table-cell; }`

Image

表格布局

Image

HTML

`

Table Layout

Shrinkwrapped Table

autoauto

Sized Table

autoauto

Stretched Table

autoauto

Fixed Table

autoauto
`

CSS

`.auto-layout { table-layout:auto; }
.fixed-layout { table-layout:fixed; }
.shrinkwrapped { width:auto; }
.sized { width:350px; }
.stretched { width:100%; }

/* Nonessential styles are not shown */`

表格布局

Image

十六、表格列布局

浏览器有许多内置的功能来自动调整表格中列的大小。本章介绍了如何利用这些自动功能来包覆提取列、将它们调整到特定的宽度、按比例调整它们的大小、按内容比例调整它们的大小、均匀调整它们的大小、灵活调整它们的大小以及减小或增大它们的大小。

表格布局模型

有四种类型的表格:收缩表、大小表、拉伸表和固定表。每种类型的表格都有唯一的列布局,只有它可以创建。

包膜表格的主要用途是收缩列以适合其内容。调整大小或拉伸表格的主要目的是按比例划分各列的宽度。固定表格的主要用途是将其列设置为固定宽度,并加速表格的呈现。

收缩表格收缩以适应其内容。这为他们提供了收缩列以适应内容宽度的独特能力。收缩包装的表格可以比其容器更窄,并且不会扩展超过其容器的宽度。当您需要灵活的布局以适应不同的设备、屏幕分辨率和视口尺寸时,包膜表格是最佳选择。以下独特的布局适用于包膜表格:包膜列、大小列、内容大小相等的列和比例相反的列。

调整大小和拉伸的表格在它们的列之间按比例划分它们的宽度,同时确保没有列比它的内容窄。对列进行布局时,调整大小和拉伸的表格的工作方式完全相同。唯一的区别是,调整大小的表格可以比它的容器更窄或更宽,而拉伸的表格可以拉伸到它的容器的宽度。以下布局适用于拉伸表格:按内容比例的列、按大小比例的列、按百分比比例的列、等大小的列和弹性列。

固定桌子是尺寸或拉伸桌子的变体。它们可以调整大小或拉伸,但不能收缩。它们不同于调整大小和拉伸的表格,因为它们在对列进行布局时会忽略内容的宽度。这可以防止单元格内容对列宽产生任何影响。因为固定表格会忽略内容,所以它们的呈现速度比其他类型的表格快得多。对于收缩、调整大小和拉伸的表格,浏览器必须等待整个表格下载完毕,这样才能在开始呈现表格之前计算出每个单元格中内容的最小和最大宽度。一旦下载了第一行,就可以渐进地呈现固定表。固定表可以调整列的大小,使其比内容小,比表宽大。固定表对大列和小列有独特的支持。固定表格支持除按内容比例排列的列之外的所有按大小排列和拉伸的表格布局。这些布局包括大小成比例的列、百分比成比例的列、大小相等的列和伸缩列。

浏览器选择的布局算法类型取决于表格的类型和分配给其单元格的宽度的类型。换句话说,给一个单元格赋值auto100px20%会有很大的不同。不仅宽度不同,而且宽度的类型也不同:自动、固定或百分比。这些不同类型的宽度与表格类型相结合,导致浏览器使用不同的算法来调整列的大小。

分配给width的值auto创建一个自动宽度。分配给width的度量单位,如像素或 ems,创建一个固定宽度。分配给width的百分比,如 50%,创建一个百分比宽度

最后,浏览器检查分配给所有行中同一列的所有单元格的width,以确定列宽和列宽的类型。在列宽设计模式中解释了浏览器如何协调同一列中不同的单元格宽度。此外,为不同的列分配不同类型的宽度会导致浏览器在同一个表格中使用多种布局算法。混合列布局设计模式中解释了浏览器如何组合列布局。

尽管浏览器会检查非固定表格中所有单元格的宽度来确定列宽,但您只需为第一行中的单元格指定一个宽度。

以下设计模式是通过将四种类型的表格与三种类型的宽度结合起来而创建的。

使用列布局

多年来,设计人员和开发人员一直使用许多自动的强大的列布局功能来布局非表格内容。事实上,这种广泛的使用促使浏览器厂商比任何其他功能都更注重增强这些功能。这也促使主要的浏览器供应商确保栏布局工作一致并且没有错误。

尽管您可以使用列布局来展示非表格数据,但我不推荐这样做,因为这会导致内容不易访问。

本章的目的是向您展示如何编排表格数据。表格数据需要样式和布局。本章中的每个例子都展示了如何使用浏览器内置的许多强大的自动算法来自动布局列。

章节大纲

  • 列宽展示了当不同行的同一列中的单元格具有不同的宽度、不同类型的宽度、不同的最小内容宽度和不同的最大内容宽度时,浏览器如何计算列宽。这种模式适用于经过包膜、调整大小和拉伸的表格。
  • 收缩列展示了如何收缩列以适合其内容的宽度。此模式适用于包膜表格。
  • 调整列的大小展示了如何给列分配固定的宽度,同时保持表格的宽度在最小或最大值范围内。此模式适用于包络处理表或固定表。
  • 内容成比例的列展示了如何自动地将表格的宽度按比例分配到它的列中。与内容较窄的列相比,内容较宽的列被分配较宽的宽度。这种模式适用于调整大小和拉伸的表格。当内容将其拉伸到容器的宽度时,它也适用于包膜表格。
  • 大小成比例的列展示了如何自动将表格的宽度按比例分配给每一列的宽度到它的列中。在这种设计模式中,浏览器不一定要以指定的宽度呈现列。相反,它根据分配给其他列的宽度成比例地呈现一列。这种模式适用于按大小排列、拉伸和固定的表格。当指定的单元宽度将表格拉伸到其容器的宽度时,它也适用于收缩包装表格。
  • 按百分比分配的列展示了如何将表格的宽度按比例分配给每列宽度的百分比。在这种设计模式中,浏览器不一定要按照表格宽度的指定百分比来呈现列。相反,它根据分配给其他列的百分比按比例呈现一列。这种模式适用于按大小排列、拉伸和固定的表格。
    ** 反比列展示了如何根据内容的比例来调整列的大小。例如,单元格的大小可以是其内容宽度的两倍。此模式适用于包膜表格。* 相等内容大小的列展示了如何在相等地调整所有列的同时,自动将一个表格缩小到其最小宽度。换句话说,它将所有列设置为相同的宽度,同时使用最小的宽度来显示每个单元格的内容。它创建具有统一列的紧凑表。它最适用于包含数字和短文本的表格。此模式适用于包膜表格。* 大小相等的列展示了如何为每个单元格自动将表格的宽度分成相等的比例。这种模式适用于按大小排列、拉伸和固定的表格。* 尺寸过小的列展示了如何创建比其内容更窄的列。这种模式适用于固定表。* Flex Columns 展示了如何在固定宽度或百分比宽度的列旁边创建动态大小的列。这些列填充大小或百分比单元格未占据的空间。随着表格容器的增大或缩小,flex 列也会增大或缩小。这种模式在应用于拉伸的和固定的表时最有用,但也适用于调整大小的表。* 混合列布局展示了如何组合固定宽度、百分比宽度和自动宽度的列来创建额外的布局。它显示了浏览器如何根据表格是收缩、调整大小、拉伸还是固定来为固定宽度、百分比宽度和自动宽度列分配不同的优先级。*

*### 列宽

Image

HTML

`

Column Width

Percentage widths trump fixed widths, which trump auto widths.

<**td class="a i">auto**              <**td class="b i">75px**              ****                   ****               ****
autoautoautoauto
auto75px75px75px
autoauto150px150px 150px
autoautoauto10%10%
autoautoautoauto50%
`

CSS

`.i { background-color:black; color:white; font-weight:bold; }
.auto-layout { table-layout:auto; }
.sized { width:700px; }

.a { width:auto; }
.b { width:75px; }
.c { width:150px; }
.d { width:10%; }
.e { width:50%; }

/* Nonessential styles are not shown */`

列宽

Image

收缩圆柱

Image

HTML

`

Shrinkwrapped Columns

               
autoauto

          
auto (less content - less width)auto (extra content turns shrinkwrapped columns         into content-proportioned columns)
`

CSS

`table { border-collapse:collapse; }
td { overflow:hidden; }

.auto-layout { table-layout:auto; }
.shrinkwrap { width:auto; }

/* Nonessential styles are not shown */`

收缩圆柱

Image

调整大小的列

Image

HTML

`

Sized Columns

Shrinkwrapped Table

  
200px 300px

Fixed Table

  
200px 300px

Maximum-width Sized Columns

**
**   
200px300px

Minimum-width Sized Columns

  
200px 300px
`

CSS

`.auto-layout { table-layout:auto; }
.fixed-layout { table-layout:fixed; }
.shrinkwrapped { width:auto; }
.min-width1 { width:1px; } .min-width2 { width:700px; }
.sized1 { width:200px; } .sized2 { width:300px; }

/* Nonessential styles are not shown */`

调整大小的列

Image

内容比例栏

Image

HTML

`

Content-Proportioned Columns

Sized Table

          
autoauto (more content - more width)

Stretched Table

          
auto (same content - same width)auto (same content - same width)

Shrinkwrapped Table

          
auto (less content - less width)auto (extra content turns shrinkwrapped columns         into content-proportioned columns)
`

CSS

`.auto-layout { table-layout:auto; }
.fixed-layout { table-layout:fixed; }
.sized { width:700px; }
.stretched { width:100%; }
.shrinkwrapped { width:auto; }
.auto-width { width:auto; }

/* Nonessential styles are not shown */`

内容比例栏

Image

大小匀称的柱子

Image

HTML

`

Size-Proportioned Columns

Sized or Stretched Table

          
100px300px

Shrinkwrapped Table

          
1000px3000px

Fixed Table

          
100px300px
`

CSS

`.auto-layout { table-layout:auto; }
.fixed-layout { table-layout:fixed; }
.sized { width:700px; }
.stretched { width:100%; }
.shrinkwrapped { width:auto; }
.size1 { width:1000px; } .size2 { width:3000px; }
.size3 { width:100px; } .size4 { width:300px; }

/* Nonessential styles are not shown */`

大小匀称的柱子

Image

比例百分比列

Image

HTML

`

Percentage-Proportioned Columns

Sized or Stretched Table

  
50% 50%
  
20% 20%
  
80% 80%
  
80% 20%
          
80% 20%50%
`

CSS

`.auto-layout { table-layout:auto; }
.fixed-layout { table-layout:fixed; }
.sized { width:700px; }
.stretched { width:100%; }
.p1 { width:20%; } .p2 { width:80%; } .p3 { width:50%; }

/* Nonessential styles are not shown */`

比例百分比列

Image

反比列

Image

HTML

`

Inverse-proportioned Columns

Shrinkwrapped Table

  
20%
                                  
20%20%20%20%20%
          
20%50%
`

CSS

`.auto-layout { table-layout:auto; }
.shrinkwrapped { width:auto; }

.p1 { width:20%; }
.p2 { width:50%; }

/* Nonessential styles are not shown */`

反比列

Image

相等内容大小的列

Image

HTML

`

Equal Content-Sized Columns

Shrinkwrapped Table

2=50% 50%
`

CSS

`.auto-layout { table-layout:auto; }
.shrinkwrapped { width:auto; }

.p2 { width:50%; }   /* 2 columns /
.p3 { width:33.5%; } /
3 columns /
.p4 { width:25%; }   /
4 columns /
.p5 { width:20%; }   /
5 columns /
.p6 { width:16.5%; } /
6 columns /
.p7 { width:14.1%; } /
7 columns /
.p8 { width:12.3%; } /
8 columns /
.p9 { width:11%; }   /
9 columns /
.p10 { width:10%; }  /
10 columns */

/* Nonessential styles are not shown */`

相等内容大小的列

Image

大小相等的列

Image

HTML

`

Sized, Stretched, or Fixed Table


<table class="auto-layout sized">

2=50% 50% `

CSS

`.auto-layout { table-layout:auto; } .fixed-layout { table-layout:fixed; }
.sized { width:700px; } .stretched { width:100%; }

.p2 { width:50%; }   /* 2 columns /
.p3 { width:33.5%; } /
3 columns /
.p4 { width:25%; }   /
4 columns /
.p5 { width:20%; }   /
5 columns /
.p6 { width:16.5%; } /
6 columns /
.p7 { width:14.1%; } /
7 columns /
.p8 { width:12.3%; } /
8 columns /
.p9 { width:11%; }   /
9 columns /
.p10 { width:10%; }  /
10 columns */

/* Nonessential styles are not shown */`

大小相等的列

Image

过小的列

Image

HTML

`

Undersized Columns

Fixed Table

18px auto

Sized Table — cannot be undersized

18px auto
`

CSS

`td { overflow:hidden; }

.fixed-layout { table-layout:fixed; }
.auto-layout { table-layout:auto; }

.sized { width:700px; }
.stretched { width:100%; }

.undersized { width:18px; }
.flex { width:auto; }

/* Nonessential styles are not shown */`

过小的列

Image

伸缩列

Image

HTML

`

Flex Columns

Sized, Stretched, or Fixed Table

     
200px20% 100pxauto flex auto flex

Sized or Stretched — Oversized

     
200px20% 500pxauto flex auto flex

Fixed — Oversized

     
200px20% 500pxauto flex auto flex
`

CSS

`.fixed-layout { table-layout:fixed; }
.auto-layout { table-layout:auto; }
.sized { width:700px; }
.stretched { width:100%; }
.flex { width:auto; }
.sized1 { width:200px; }
.sized2 { width:100px; }
.sized3 { width:500px; }
.p1 { width:20%; } .fixed-layout .p1{ padding:0; }

/* Nonessential styles are not shown */`

伸缩列

Image

混合列布局

Image

HTML

`

Mixed Column Layouts

Shrinkwrapped, Stretched, or Sized Tables

  
500px10% auto
     
500px200px 40%10% auto
     
500px200px 80%20% auto

Fixed Table

     
500px200px 80%20% auto
`

CSS

`.fixed-layout { table-layout:fixed; } .auto-layout { table-layout:auto; }
.shrinkwrapped { width:auto; }
.stretched { width:100%; }
.flex { width:auto; }
.sized1 { width:500px; } .sized2 { width:200px; }
.p1 { width:10%; } .p2 { width:20%; }
.p3 { width:40%; } .p4 { width:80%; }
.fixed-layout .p2 { padding:0; }

/* Nonessential styles are not shown */`

混合列布局

Image*

十七、布局

本章展示了如何创建流畅的布局,它可以自动适应不同的设备、字体、宽度和缩放因子。这些设计模式是可访问的、模块化的、易于定制的。动态模式使用开源 JavaScript 库将事件处理程序附加到元素上。这允许您创建动态效果,而无需在文档中添加一行 JavaScript 代码!这些库使用 CSS 选择器来决定处理哪些元素来响应事件,它们可以修改元素的 class 属性,这样样式表就可以完全控制事件如何动态地样式化元素。

章节大纲

  • 流体布局概述探讨创建流体布局时的问题和解决方案。
  • Outside-in Box 展示了如何调整一个盒子的外宽而不是内宽的大小。
  • 浮动部分展示了如何使用流体布局来渲染列中的部分。
  • 浮动分割器展示了如何可预测地分离和整合浮动和内容。
  • 流体布局展示了如何创建自动适应任何显示的布局。
  • 反向浮动展示了如何将内容移动到容器的两侧。
  • 事件样式展示了如何将事件分配给元素,而无需在文档中添加代码。它展示了事件如何修改类来改变元素的样式。
  • Rollup 展示了如何通过鼠标点击来折叠和打开部分。
  • 标签菜单展示了如何创建一个标签界面,当点击时加载新页面。
  • Tabs 展示了如何创建一个选项卡式的界面,当用户点击一个选项卡时,该界面可以动态地将内容切换进和切换出显示屏,而无需加载新的页面。
  • 弹出菜单展示了如何创建一个点击或悬停时打开的菜单。
  • Button 展示了如何使用 JavaScript 创建按钮并处理它们的事件。
  • 布局链接展示了如何使用链接作为布局的一部分,比如面包屑。
  • 多栏展示了如何在多栏中分发内容。
  • 模板展示了如何使用字母字符和位置属性定义位置。
  • 布局示例展示了如何组合和扩展这些设计模式。

流体布局概述

Image

HTML

`

Fluid Layout Overview


    

Main


    

40% of container's width.


    

News


    

20% of container's width.

`

CSS

`body { max-width:1000px; margin-left:auto; margin-right:auto; }

div { background-color:gold; margin-right:10px; padding:5px;
  border-left:1px solid gray; border-right:2px solid black;
  border-top:1px solid gray; border-bottom:2px solid black; }

#nav  { float:left; width:20%; min-width:170px; }
#main { float:left; width:40%; min-width:170px; }
#news { float:left; width:20%; min-width:170px; }

/*  Nonessential rules are not shown. */`

流体布局概述

Image

由外向内框

Image

HTML

`

Outside-in Box

Before

Float
Absolute
Static

After

  
Float
   Absolute
  
Static
`

CSS

。{宽度:100%之前;保证金:5px 填充:5px 边框:5px 纯黑;}

`.after { width:100%; }
.after .oi { margin:5px; padding:5px; border:5px solid black; display:block; }

.float { float:left; }
.absolute { position:absolute; }
.static { position:static; }

/*  Nonessential rules are not shown. */`

由外向内框

Image

Image

HTML

`

Outside-in vs. Inside-out Design

Two floats with 50% width and no margins, borders, or padding

Float1
Float2

Two floats with 50% width and 1px border

Float1
Float2

Two floats with 45% width and 5% left margin

Float1
Float2

Two floats with 49.5% width and 5px left margin

Float1
Float2
`

CSS

`body { max-width:1200px; }
div { min-width:100px; }

.ex1 { float:left; width:50%; }
.ex2 { float:left; width:50%; border:1px solid; }
.ex3 { float:left; width:45%; margin-left:5%; }
.ex4 { float:left; width:49.5%; margin-left:5px; }

/*  Nonessential rules are not shown. */`

由外向内与由内向外设计

流体布局从外向内设计。这是因为您从视口的宽度开始,并使用百分比、最小宽度和最大宽度在元素之间划分其宽度。

问题是width属性设置了元素的内部宽度。填充、边框和边距围绕元素的内部宽度,从而增加其外部宽度。因为 CSS 没有 outer-width 属性,所以 CSS 要求你从里面的到外面的进行设计。结果是边距、边框和填充会破坏流畅的布局设计。

*例如,您可能想要将两个元素浮动到左侧,并将每个元素分配给width:50%,以便它们并排放置,并平均分配视口的宽度。示例中的前两个部分展示了这是如何工作的。无论您如何调整视口的大小,这些元素都会并排放置(直到它们的最小宽度不再允许它们适合视口的宽度)。

如果您给这两个并排的浮动分配任何边距、边框和填充,浮动将不再适合视窗的宽度。例如,如果在每个元素周围指定一个 1 像素的边框,则它们的总外部宽度会超出视口宽度 4 个像素(每个元素的左侧和右侧各 1 个像素)。当浮动不能并排放入它们的容器时,它们会换行到下一行。这不是你想要的!示例中的第二组划分显示了一个微小的 1 像素边框如何打破流体布局。无论你如何调整视窗大小,浮动将而不是并排。

要将两个元素的边距、边框和填充放入它们的容器中,必须减少每个元素的百分比宽度,但是减少多少呢?如果为边距和填充指定百分比,只需从指定给宽度的百分比中减去它们各自的百分比。例如,如果为两个元素各指定 5%的左边距,则可以为每个元素指定 45%的宽度。示例中的第三组划分证明了这一点。无论您如何调整视口的大小,这些元素都将并排放置(直到它们的最小宽度使它们无法适应视口)。

根据 CSS 规范,浏览器会忽略分配给边框的百分比,这意味着您必须使用固定的度量来创建边框。为边距和填充指定百分比也不常见,因为边距和填充不随视口调整大小时通常看起来更好。您可以调整示例的大小,以对比百分比边距和固定边距的行为。

流体布局中,给元素分配固定的边距、边框和填充与分配给其width百分比不兼容。随着视口缩小,百分比会缩小元素的宽度,但其固定的边距、边框和填充不会缩小。例如,假设视窗宽度为 1000 像素,包含两个并排的子元素,每个子元素的左边距为 5 像素,则可用宽度为 990 像素,即 99%,即(1000 px–5px–5px)/1000 px。如果你要在两个元素之间平均分配,你可以给每个元素分配width:49.5%。给定 100 像素的视口宽度,可用宽度为 90 像素,即 90%,即(100 像素–5px–5px)/100 像素。为了在两个元素之间平均分配,你可以给每个元素分配width:45%。因此,将固定的边距、边框和填充与百分比宽度混合在一起在流体布局中不起作用。在本例中,第四组分割设置为 49.5%,左边距设置为 5 个像素。这张截图是以 750 像素的宽度拍摄的,宽度不足以让它们并排放置;但是如果你把浏览器窗口放大到 1000 像素或者更多,它们就合适了。

请注意,Internet Explorer 7 和早期版本并不完全遵守规则。当浮动两个设置为width:50%的元素时,Internet Explorer 猜测您希望它们并排,所以它打破规则,将它们并排放置。所有其他主流浏览器都运行正常。此外,Internet Explorer 6 有错误,有时会导致浮动而不是被并排放置。例如,在第三组划分中,Internet Explorer 6 将第二个浮动移动到第一个之下。Internet Explorer 7 修复了这些错误。

由外向内的设计模式解决了所有这些问题(包括 Internet Explorer 的问题)。因此,这是创建流畅布局的基本设计模式。另一种方法是在百分比上努力,直到你找到在大多数浏览器上都能工作的东西,并且在大多数时候看起来接近你想要的。

浮动节

Image

HTML

`

Floating Section


**  
**
      

Main Section


      

75% of container's width minus 80-pixel left margin, 1-pixel left border,
         2-pixel left border, and 80-pixel left padding.


  

`

CSS

`.oi { background-color:gold;
  border-left:1px solid gray; border-right:2px solid black;
  border-top:1px solid gray; border-bottom:2px solid black; }

nav

nav .oi

main

main .oi

/*  Nonessential rules are not shown. */`

浮动节

Image

浮动分频器

Image

HTML

`

Float Divider

First Row of Floats

Float 1

Float 2

Float 3

Second Row of Floats

Float 4

Float 5

Float 6

`

CSS

`.float { float:left; }

.float-divider { clear:both;
  height:20px;
  margin-bottom:20px;
  border-bottom:5px solid black;
  font-size:1px; line-height:1px; }

/* Nonessential rules are not shown. */`

浮动分频器

Image

流体布局

Image

HTML

`

Fluid Layout

main - 100%

  

content - 60%


     head - 35%
     detail - 65%
    

news - 20%

`

CSS

`.float-divider { clear:both; display:block;
  height:1px; font-size:1px; line-height:1px; }
.oi1 { background-color:white; margin:0; padding:5px; }
.oi2 { background-color:gold; margin:5px; padding:5px; }
.oi3 { background-color:yellow; margin:5px; padding:5px; }

main

nav { float:left; width:20%; min-width:75px; }

content { float:left; width:60%; min-width:150px; }

news { float:left; width:20%; min-width:115px; }

nav .oi2

content .oi3

head { float:left; width:35%; min-width:75px; }

detail { float:left; width:65%; min-width:75px; }

/* Nonessential rules are not shown. */`

流体布局

Image

对立浮动

Image

HTML

`


  

  **   **

**Postheader message 1

 **
**

<p class="breadcrumbs">Home » Floating Layout


  <p class="post-msg">Postheader message 2


  

`

CSS

`.float-divider { clear:both; display:block;
  height:1px; font-size:1px; line-height:1px; }

.breadcrumbs { float:left;  max-width:350px; margin-left:10px; }
.post-msg { float:right; max-width:350px; margin-right:10px; }

title  { float:left;  min-width:280px; max-width:350px; margin-left:0; }

search { float:right; min-width:280px; max-width:350px; margin-right:0; }

/* Nonessential rules are not shown. */`

对立浮动

Image

事件造型

Image

HTML

`
  

`

页. js

$(document).ready(function(e){     $('.rollup-trigger').click(function(e){         $(this).closest('.rollup').children().not('.rollup-trigger').toggleClass('hidden');         $(this).parent().removeClass('hidden');     }); });

活动风格

Image

Image

Image

HTML

`

Rollup

  

Main

<div class="oi rollup">
    <h3 class="rollup-trigger">FAQ Don't roll me up.
    <dl class="rollup">
      <dt class="rollup-trigger">QUESTION: How do rollups work?
      <dd class="hidden">ANSWER: When the user clicks on a heading or button,
                           the content rolls up or down.

<div class="oi rollup">
    <h3 class="rollup-trigger">Info
    <div class="rollup">
      

<span class="rollup-trigger"> List


      
  • list item 1
  • list item 2

    <span class="rollup-trigger"> Roll me up
    
`

CSS

`.rollup-trigger { cursor:pointer; }
.rollup-trigger:hover { color:firebrick; }

span.rollup-trigger { font-size:0.65em; padding-left:8px;
  background:url("hide.gif") no-repeat left top; }

span.rolledup { background:url("show.gif") no-repeat left top; }

.hidden { position:absolute; top:-99999px; left:-99999px;
  width:1px; height:1px; overflow:hidden; }

/* Nonessential rules are not shown. */`

Image

HTML 标题

`
  

<script language="javascript" type="text/javascript"
    src=" https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js">

`

页. js

$(document).ready(function(e){     $('.rollup-trigger').click(function(e){         $(this).closest('.rollup').children().not('.rollup-trigger').toggleClass('hidden');         $(this).parent().removeClass('hidden');     }); });

Image

Tab 菜单

Image

HTML

`

Tab Menu

  **   

Tab 1 content: A click on one of these tabs loads a new page.

`

CSS

`ul.tabs a:link, ul.tabs a:visited, ul.tabs a:active
     { text-decoration:none; color:maroon; }
    ul.tabs a:hover { text-decoration:underline; color:black; }
    ul.tabs a { display:block; }

ul.tabs { float:left; width:100%; padding:0; margin:0;
      border-bottom:1px solid gold; margin-bottom:10px; }

ul.tabs li { float:left; width:25%; list-style-type:none; }

ul.tabs .tab-label { border:1px solid gold; margin:0; cursor:pointer;
      padding-bottom:2px; padding-top:2px;
      background:white url("g1.jpg") repeat-x left bottom;
      font-weight:normal; text-align:center; font-size:1.1em; }

ul.tabs li.selected .tab-label { position:relative; border-bottom:none;
      top:1px; padding-bottom:4px;
      padding-top:5px; border-top:2px solid gold; margin-top:-5px;
      background:white url("g2.jpg") repeat-x left top; font-weight:bold; }

main { border:1px solid gold; border-top:none; }`

Tab 菜单

Image

HTML(为方便起见,再次显示相同的代码)

`

Tab Menu

  **
    **     **
  • **       

    Tab 1

  •     
  • Tab 2

  •     
  • Tab 3

  •     
  • Tab 4

  •   
  

Tab 1 content: A click on one of these tabs loads a new page.

`

CSS(为方便起见,再次显示相同的代码)

`ul.tabs a:link, ul.tabs a:visited, ul.tabs a:active
      { text-decoration:none; color:maroon; }
    ul.tabs a:hover, ul.tabs a:focus
      { text-decoration:underline; color:black; }
    ul.tabs a { display:block; }

ul.tabs { float:left; width:100%; padding:0; margin:0;
      border-bottom:1px solid gold; margin-bottom:10px; }

ul.tabs li { float:left; width:25%; list-style-type:none; }

ul.tabs .tab-label { border: 1px solid gold; margin:0; cursor:pointer;
      padding-bottom:2px; padding-top:2px;
      background:white url("g1.jpg") repeat-x left bottom;
      font-weight:normal; text-align:center; font-size:1.1em; }

ul.tabs li.selected .tab-label { position:relative; border-bottom:none;
      top:1px; padding-bottom:4px; cursor:auto;
      padding-top:5px; border-top:2px solid gold; margin-top:-5px;
      background:white url("g2.jpg") repeat-x left top; font-weight:bold; }

main { border:1px solid gold; border-top:none; }`

Image

选项卡

Image

HTML

Tabs


       
  • Tab 1


        

         

    Tab 1 Content

    This is the message of tab 1. More message...
         

  • Tab 2


        <div id="section2" class="tab-content"><div class="oi2">
         

    Tab 2 Content

    This is the message of tab 2.
         

`

CSS

`/* All rules from the Tab Menu design pattern apply to Tabs.
   Only additional rules that apply to this design pattern are shown here. */

ul.tabs { position:relative; }

ul.tabs .tab-content { position:absolute; width:100%; height:6em;
  border:1px solid gold; border-top:none;
  left:-99999px; overflow:auto; }

ul.tabs li.selected .tab-content { left:0; }

ul.tabs li .oi2 { margin:10px; padding:10px; }

ul.tabs .tab-label a { display:block; text-decoration:none; color:black; }

ul.tabs .hover,
ul.tabs .tab-label:hover { text-decoration:underline; }

/*  Nonessential rules are not shown. */`

选项卡

Image

HTML 标题

`
 

`

页. js

$(document).ready(function(e){         $('ul.tabs li').click(function(e){                 $('ul.tabs li.selected').removeClass('selected');                 $(this).addClass('selected');         });         $('ul.tabs li .tab-label').mouseover(function(e){                 $(this).addClass('hover');         });         $('ul.tabs li .tab-label').mouseout(function(e){                 $(this).removeClass('hover');         });         $('ul.tabs .tab-label a').click(function(e){                 e.preventDefault();                 $(this).blur();         }); });

Image

弹出菜单

Image

HTML

**<div class="menu"><h3>Dropdown</h3>**   **<ul class="dropdown hidden">**     **<li><a href="#">menu item</a></li>**       <li **class="separator"**><a href="#">menu item</a></li>     <li **class="flyout-trigger"><h4>submenu</h4>**       **<ul class="submenu hidden">**         <li><img src="award.gif" alt="award" /><a href="#">menu item</a></li>         <li><a href="#">menu item</a></li></ul></li></ul></div>

CSS

`.menu { float:left; position:relative; z-index:1; cursor:pointer;
      font-size:0.8em; white-space:nowrap; }
    .menu a { text-decoration:none; color:black; }

.menu h3 { float:left; margin:0; padding:1px 5px;
      background:url("g1.jpg") repeat-x left bottom white; }
    .menu h4 { display:inline; margin:0; }
    .menu ul { position:absolute; margin:0; padding:0; padding-bottom:5px;
      background:url("g3.jpg") repeat-x left bottom white; }

.menu li { margin:0; padding:2px 25px; list-style-type:none; color:black; }
    .menu li img { margin-left:-22px; padding-right:5px; }
    .menu li.separator { margin-top:5px; border-top:1px solid gray; padding-top:5px; }
    .menu li.flyout-trigger { background:url("flyout1.gif") no-repeat right center; }
    .menu li.flyout-trigger.hover
      { background:url("flyout2.gif") no-repeat right center firebrick; }
    .menu h3.hover { background:url("g2.jpg") repeat-x left top white; }
    .menu li.hover { background-color:firebrick; color:white; }
    .menu li.hover > a  { color:white; }
.menu ul.dropdown { top:100%;  clear:left; }
.menu ul.submenu { left:100%; margin-top:-1.5em; margin-left:-0.3em; }
.menu .hidden { left:-99999px; top:-99999px; }
    .menu h3,.menu ul { border-left:1px solid yellow; border-right:1px solid orange;
      border-top:1px solid yellow; border-bottom:1px solid orange; }

/*  Nonessential rules are not shown. */`

弹出菜单

Image

HTML 标题

`
  

<script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js">

`

页. js

$(document).ready(function(e){     $('.menu').click(function(e){         $('.dropdown', $(this)).toggleClass('hidden');     });     $('.menu').mouseover(function(e){         $('.dropdown', $(this)).removeClass('hidden');     });     $('.menu').mouseout(function(e){         $('.dropdown', $(this)).addClass('hidden');     });     $('.menu li, .menu h3').mouseover(function(e){         $(this).addClass('hover');     });     $('.menu li, .menu h3').mouseout(function(e){         $(this).removeClass('hover');     });     $('.menu li.flyout-trigger').mouseover(function(e){         $('> .submenu', $(this)).removeClass('hidden');     });     $('.menu li.flyout-trigger').mouseout(function(e){         $('> .submenu', $(this)).addClass('hidden');     }); });

Image

按钮

Image

HTML

`

Button

              


Link`

CSS

`form { margin:20px 0; }
    .button { margin:0; padding:3px 10px; font-size:1em; color:black;
      cursor:pointer; background:url("g1.jpg") repeat-x left bottom;
      border-left:1px solid yellow; border-right:1px solid orange;
      border-top:1px solid yellow; border-bottom:1px solid orange; }

.button:hover, .button.hover
      { background:url("g2.jpg") repeat-x left top;
        border-left:1px solid orange; border-right:1px solid yellow;
        border-top:1px solid orange; border-bottom:1px solid yellow; }

a.button { padding:5px 10px; line-height:2em; text-decoration:none; }

#submit2 { width:32px; height:32px; border:none; cursor:pointer;
      background:url("go.jpg") no-repeat left top; }

submit2:hover, #submit2.hover { background-position:1px 1px; }`

按钮

Image

HTML 标题

`
  

<script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js">

`

页. js

$(document).ready(function(e){     $('#form1').submit(function(e){         if(!confirm('Are you sure?')){e.preventDefault();}     });     $('#message').click(function(e){         alert('Hi There');     });     $('#button').click(function(e){         alert('Hi There');     });     $('#link').click(function(e){         if(!confirm('Jump here?')){e.preventDefault();}     });     $('#change').click(function(e){         try{             var result = prompt('Enter content:',  $(this).text() );             if ( result ) $(this).text( result );         }catch(ex){ e.preventDefault(); }     });     $('#submit4').click(function(e){         $('#form1').submit();     });     $('#reset2').click(function(e){         $('#form1').reset();     }); }); }); Button (Continued)

Image

布局链接

Image

HTML

`

Layout Links

<div id="preheader"><a class="skiplink" href="#main">Skip to main content
    <div id="header">

header

Home » Layout Links   » Breadcrumbs <**span class="sequential"**>   « Previous | Next »

body

  

Main content goes here. <**a class="outlink"** href="#">External Link

  

»** More Info

`

CSS

`a:link, a:visited, a:active { text-decoration:none; color:maroon; }
a:hover { color:black; text-decoration:underline; }

.morelink { font-size:0.8em; font-weight:bold; text-align:right; }
.toplink { font-size:0.7em; font-weight:normal; vertical-align:top; }
.outlink { padding-right:15px; font-style:italic;
  background:url("external.gif") no-repeat top right; }

/* Nonessential rules are not shown. */`

布局链接

Image

多栏布局

Image

HTML

`

Multi-column Layout

Lorem ipsum dolor sit amet, consectetur adipiscing elit.   Morbi sollicitudin posuere mauris sed in ...

`

CSS

`.multi { column-count:3; -moz-column-count:3;
  -webkit-column-count:3; -ms-column-count:3; }

/* Nonessential rules are not shown. */`

多栏布局

Image

模板布局

Image

HTML

`

Template Layout

    
Apple
    
Bear
    
Castle
    
Deer
`

CSS

`#template { display: “ab” “cd” 20% * 20%; }
    #d { position: a; }
    #c { position: b; }
    #b {  position: c; }

a

/* Nonessential rules are not shown. */`

模板布局

Image

布局示例

Image

HTML 结构元素

`


    <div id="header">
      <div id="title">

Layout Example


      <div id="search">

Search:


    <div id="postheader">
    <div id="body">
      <div id="nav">
    <div id="site-map">

Site Map


    <div id="links">

Links


  <div id="main">
  <div id="extras">
    <div id="news">

News


    <div id="about-us">

About us

`

CSS 结构样式

`#preheader .part1 { float:left;  margin-left:10px; }

preheader .part2

header

title

search

postheader .breadcrumbs

postheader .sequential

body

nav

main

extras

footer { clear:both; padding-top:40px; }`

布局示例

Image

Image

在狭窄视窗中显示的布局示例,显示时没有样式表

Image*

十八、首字下沉

本章讨论创建首字下沉的设计模式。首字下沉极大地改变了文档第一个字母的样式,以表示它是文档的开始。有时它用在较长文件的主要部分的开头。有时它会设计一个单词的样式,而不仅仅是第一个字母。

通常,首字下沉会放大并降低第一个字母,以便字母的顶部与后面文本的顶部对齐,但是首字下沉的样式没有限制。

本章中的设计模式是按照从最简单到最复杂的顺序组织的。

章节大纲

  • 对齐首字下沉展示了如何通过放大和垂直对齐来创建一个简单的首字下沉。
  • 首字母首字下沉展示了如何在不插入额外标记的情况下创建首字下沉。
  • 悬挂首字下沉展示了如何使用悬挂缩进来创建首字下沉。
  • 填充的图形首字下沉展示了如何给首字下沉添加左填充,以便为显示横幅、抓图或装饰的背景图像腾出空间。
  • 浮动首字下沉展示了如何将首字下沉浮动到左侧,这样首字下沉下方的文本会在首字下沉下方换行。
  • 浮动图形首字下沉展示了如何在首字下沉文本上显示图形。它非常适合屏幕阅读器,当图像不可用时,它显示首字下沉的样式文本版本。这是允许首字下沉下方的文本在首字下沉下方换行的最佳图形首字下沉设计模式。
  • 首字下沉展示了如何使用绝对定位将首字下沉移动到块的左边界。块的所有行都缩进。
  • 显示了如何在首字下沉文本上显示一个图形。它非常适合屏幕阅读器,当图像不可用时,它显示首字下沉的样式文本版本。这是防止首字下沉下方的文本在首字下沉下方换行的最佳图形首字下沉设计模式。

对齐首字下沉

Image

HTML

`

Aligned Drop Cap Variation 1. Text is
  large, bold, and aligned at the baseline. Subsequent lines are not indented.

Aligned Drop Cap Variation 2. The
  drop cap is aligned to the middle of the text. Subsequent lines are not indented.
  The drop cap pushes down the second line a little bit.

Aligned Drop Cap Variation 3. The
  drop cap is offset to the top of the text. Subsequent lines are not indented.
  The drop cap pushes down the second line quite a bit.

`

CSS

`.aligned-dropcap1 { font-size:40px; line-height:normal; font-weight:bold;
**  vertical-align:baseline;** }

.aligned-dropcap2 { font-size:40px; line-height:0.8em; font-weight:bold;
  vertical-align:middle; background-color:gold; padding:0 2px; }

.aligned-dropcap3 { font-size:40px; line-height:normal; font-weight:bold;
  font-style:italic; vertical-align:-0.45em; color:white;
  background-color:black; background-image:url("marble.jpg");
  padding:0 4px; border:1px solid black; }`

对齐首字下沉

Image

首字母首字下沉

Image

HTML

`

first-letter can create an aligned drop cap.
  The problem is that browsers have a hard time aligning pseudo elements.

first-letter can be used to create a floating
  drop cap. The problem is that the drop cap cannot be positioned up or down.

first-letter can be used to create a hanging drop cap in the
  margin. The drop cap can even be replaced by a background image.
  The problem is that the drop cap cannot be positioned up or down.

`

CSS

`.dropcap1:first-letter { font-size:60px; vertical-align:0px; font-weight:bold; }

.dropcap2:first-letter { float:left; margin-left:-3px; margin-right:3px;
  position:relative; top:-2000px; / DOES NOT WORK /
  font-size:60px; line-height:normal; font-weight:bold; }

.dropcap3  { padding-left:105px; text-indent:-104px; margin-top:50px; }

.dropcap3:first-letter { padding:40px 50px; font-size:1px; line-height:1px;
  color:white; background-image:url("f.jpg");
  background-position:center center; }`

首字母首字下沉

Image

挂落帽

Image

HTML

**<p class="hanging-indent"><span class="hanging-dropcap">H</span>anging**   Drop Cap. This drop cap hangs in the margin. No text flows back under   the backdrop when it flows past the bottom of the drop cap.   The drop cap can be lowered and raised without affecting the line height.   Using <code>top</code> and <code>left</code>,   you can adjust the position of the drop cap and the position of the text   next to the drop cap.</p>

CSS

`.hanging-indent { padding-left:50px;
  text-indent:-50px;
  margin-top:-25px; }

.hanging-dropcap { position:relative;
  top:0.55em;
  left:-3px;
  font-size:60px;
  line-height:60px;
  font-weight:bold; }`

挂落帽

Image

带衬垫的图形首字下沉

Image

HTML

`

Padded Drop Cap

Padded Aligned Drop Cap. Text is   large, bold, and aligned at the baseline. Subsequent lines are not indented.

Padded Floating Drop Cap. The   drop cap is floated to the left and then offset to the right using   padding-left. It has a background image rendered in the   padding area. Subsequent lines are indented for as long as the drop cap is on   their left.

`

CSS

`.padded-dropcap1 { padding-left:39%; font-size:80px; line-height:normal;
  font-weight:bold; vertical-align:middle;
  background:url("rose.jpg") no-repeat -65px 0 white; }

.padded-dropcap2 { padding-left:275px; padding-right:10px; float:left;
  position:relative; top:-0.25em; margin-bottom:-0.2em;
  margin-left:-3px; margin-right:3px; color:black;
  background:url("grabber.jpg") no-repeat 5px 20px white;
  font-size:84px; line-height:normal; font-weight:bold; }`

带衬垫的图形首字下沉

Image

浮动落帽

Image

HTML

`

Floating Drop Cap

**F**loated Drop Cap Variation 1\. This   drop cap is lowered without affecting the height of the line.   Using top, margin-left, margin-right,   and margin-bottom, you can adjust the position of the drop cap   and the position of the text next to the drop cap.


**F**loated Drop Cap Variation 2.   Notice how the drop cap has been moved up and to the right, and the text   has moved to the right.

`

CSS

`.floating-dropcap1 { float:left; position:relative; top:-0.25em;
  margin-left:-3px; margin-right:3px; margin-bottom:-0.6em;
  font-size:80px; line-height:normal; font-weight:bold; }

.floating-dropcap2 { float:left; position:relative; top:-0.35em;
  margin-left:20px; margin-right:5px; margin-bottom:-0.7em;
  font-size:80px; line-height:normal; font-weight:bold;
  color:white; background-color:black; padding:0 20px;
  background-image:url("marble.jpg");
  border-left:2px groove black; border-right:2px ridge black;
  border-top:2px groove black; border-bottom:2px ridge black; }`

浮动落帽

Image

浮动图形首字下沉

Image

HTML

`

Floating Graphical Drop Cap

Floating
  Graphical Drop Cap. The letter F has been covered by the dropcap image.
  Screen readers read the text and visual users see the image.
  If the browser cannot display the dropcap image, the text becomes visible.
  The text can be styled so that it looks good if it ever becomes visible.
  Because the drop cap is floated, the text wraps around the bottom of the drop cap
  when it clears the drop cap's bottom margin.

`

CSS

`.floating-dropcap { float:left; position:relative; top:5px;
  margin-left:80px; margin-right:12px; margin-bottom:0px;
  width:100px; height:90px;
  line-height:80px; text-align:right;
  font-size:100px; font-weight:bold;
  color:black; background-color:white; }

.floating-dropcap span { position:absolute;
**  width:100px; height:90px; left:0; top:0; margin:0;**
**  background-image:url("f.jpg");**
**  background-repeat:no-repeat; }**`

浮动图形首字下沉

Image

边际落差

Image

HTML

`

Marginal Drop Cap

Marginal Drop Cap.
  The marginal drop cap indents the text to the right and uses absolute
  positioning to move the drop cap into the margin created by the indent. All
  text stays to the right of the drop cap. In other words, text does not wrap
  back under the drop cap when it extends below the drop cap.

`

CSS

`.indent { position:relative; margin-left:72px; margin-top:20px; }

.marginal-dropcap { position:absolute; left:-77px; top:-16px;
  font-size:80px; font-weight:bold;
  color:black; background-color:white; }`

边际落差

Image

边缘图形首字下沉

Image

HTML

<h1>Marginal Graphical Drop Cap</h1> **<p class="indent"><span class="graphic-dropcap">M<span>arginal**   Graphical Drop Cap. The letter M has been covered by the dropcap image.   Screen readers read the text and visual users see the image.   If the browser cannot display the dropcap image,   the text becomes visible.</p>

CSS

`.indent { position:relative; margin-left:120px; margin-top:20px; }

.graphic-dropcap { position:absolute; left:-120px; top:6px;
**  width:100px; height:90px;**
**  line-height:70px; padding-left:16px; text-align:right;**
  font-size:80px; font-weight:bold;
  color:black; background-color:white; }

.graphic-dropcap span { position:absolute;
**  width:100px; height:90px; left:0; top:0; margin:0;**
**  background-image:url("g.jpg");**
**  background-repeat:no-repeat; }**`

边缘图形首字下沉

Image

Image

当浏览器无法加载或显示图像时,边缘图形首字下沉示例是什么样子的

Image

Image

十九、标注和引用

本章讨论创建标注引用的设计模式。

标注是从文档中抽出的关键点,用来吸引读者的注意力,以便他或她阅读文档并在阅读后记住该点。标注在文档中重复两次:一次作为文档正文的一部分,另一次作为标注显示。标注会突出显示,这样读者就不会错过。因为标注是从文档的文本中提取的,所以它通常是一个行内元素,尽管它也可能是一个块元素。

我将标注和引用组合在一起,因为它们密切相关。标注也称为引用引用,因为它们是从文档中提取的引用。拉报价和报价是有区别的。引用(或标注)要求同一文本在一个文档中重复两次,而引用只出现一次。此外,一个报价通常包括引用,而拉报价没有。最后,引用在视觉上和语义上属于内容的一部分,而标注在视觉上和语义上与内容分开,并且通常被移动到文档的左侧或右侧或边缘。在本章的其余部分,我将把引用称为标注,以避免与常规引用混淆。

章节大纲

  • 左侧浮动标注展示了如何创建一个标注并将其浮动到左侧。
  • 右浮动标注展示了如何创建一个标注并将其向右浮动。
  • 居中标注展示了如何创建标注并将其居中。
  • 左边距标注展示了如何使用左边距设计模式在左边距创建标注。
  • 右边距标注展示了如何使用右边距设计模式在右边距创建标注。
  • Block Quote 展示了如何创建一个引用自动居中并带有图形背景引用样式的 Block Quote。
  • 内联块报价展示了如何将内联报价呈现为块报价。
  • 内嵌引用展示了如何创建带有引用的内嵌引用。

左浮动标注

Image

HTML

`

Left Floating Callout

A callout makes the key point stand out to the reader.

**  Makes the key point stand out**

You can float a callout to the left using float:left.
  You can use width to set the callout's width.
  You can use margin to put distance between the callout and
  text outside the callout. You can use padding to put space
  between the callout's internal text and its borders. You can use
  position:relative and top to adjust the vertical
  position of the callout.

`

CSS

**.callout-left { float:left; width:200px; padding:6px;** **  margin:10px 40px 10px 30px;** **  position:relative; top:10px;**   font-size:22px; line-height:normal; font-weight:bold;   text-align:center; color:black; background-color:gold;   border-left:1px solid black; border-right:1px solid black;   border-top:6px solid black; border-bottom:6px solid black; }

左浮动标注

Image

右浮动标注

Image

HTML

`

Right Floating Callout

The main feature of the floating callout is that text can wrap   under and over it because it is a float.

**  Wraps under and over**

You can float a callout to the right using float:right.
  You can use width to set the callout's width.
  You can use margin to put distance between the callout and
  text outside the callout. You can use padding to put space
  between the callout's internal text and its borders. You can use
  position:relative and top to adjust the vertical
  position of the callout.

`

CSS

**.callout { float:right; width:200px; padding:6px;** **  margin:10px 30px 10px 40px;** **  position:relative; top:10px;**   font-size:22px; line-height:normal; font-weight:bold;   text-align:center; color:black; background-color:gold;   border-left:1px solid black; border-right:1px solid black;   border-top:6px solid black; border-bottom:6px solid black; }

右浮动标注

Image

居中标注

Image

HTML

`

Center Callout

display:block clears text on each side of the callout.   width sets the callout's width. margin-top and   margin-bottom set the distance above and below the center callout.

**  Centered Callout!**

margin-left:auto and margin-right:auto center the
  callout in its parent terminal block element.position:relative
  and left adjust the horizontal position of the callout
  away from center.

`

CSS

**.callout { display:block; width:300px; margin:20px auto; padding:6px;** **  position:relative; left:0%;**   font-size:22px; line-height:normal; font-weight:bold;   text-align:center; color:black; background-color:gold;   border-left:1px solid black; border-right:1px solid black;   border-top:6px solid black; border-bottom:6px solid black; }

居中标注

Image

左边距标注

Image

HTML

`

Left Marginal Callout


**  Text does not wrap under...**
  The main feature of the marginal callout is that text does not wrap
  under or over the callout because the callout is in the margin.
  You can indent the block to make room for the callout on the left.
  You can use absolute positioning to pull the callout out of the text
  and move it into the left margin.

`

CSS

`.left-marginal { position:relative; width:470px; margin-left:230px; }

.callout { position:absolute; left:-220px; width:160px; margin-top:5px;
  line-height:normal; text-align:center; padding:5px 0;
  font-size:22px; font-weight:bold;
  color:black; background-color:gold;
  border-left:1px solid black; border-right:1px solid black;
  border-top:6px solid black; border-bottom:6px solid black; }`

左边距标注

Image

右边界标注

Image

HTML

`

Right Marginal Callout


**   Text does not wrap under...**

The main feature of the marginal callout is that text does not wrap
  under or over the callout because the callout is in the margin.
  You can indent the block to make room for the callout on the right.
  You can use absolute positioning to pull the callout out of the text
  and move it into the right margin.

`

CSS

`.right-marginal { position:relative; width:490px; margin-right:230px;  }

.callout { position:absolute; right:-200px; width:160px; margin-top:5px;
  line-height:normal; text-align:center; padding:5px 0;
  font-size:22px; font-weight:bold;
  color:black; background-color:gold;
  border-left:1px solid black; border-right:1px solid black;
  border-top:6px solid black; border-bottom:6px solid black; }`

右边界标注

Image

块报价

Image

HTML

`

Block Quote


**  

**A block quote contains one or more paragraphs, and a citation.
    A block quote is not repeated twice in the document like a callout.

**  

**This example includes an embedded, decorative division so it can display
    a graphical closing quote.


  Pro HTML5 and CSS3 Design Patterns
  
`

CSS

`blockquote { width:500px; margin:10px auto;
  position:relative; left:0%; text-align:justify;
  line-height:1.3em; color:black;
  padding-top:40px; padding-left:40px;
  background:url("dq1.jpg") no-repeat top left; }

blockquote div { padding-bottom:10px; padding-right:40px;
  background:url("dq2.jpg") no-repeat bottom right; }

blockquote p { margin:0; margin-bottom:10px; }

blockquote cite { display:block; text-align:right; font-size:0.9em; }`

块报价

Image

行内块引用

Image

HTML

`

Inline Block Quote

This quote is embedded in a paragraph, but looks like a block quote.


  An inline block quote is marked up with inline elements, but looks like a
  block quote because its elements are rendered using display:block.
  

I embedded a decorative span in this example to display
  a graphical closing quote.

**  **Pro HTML5 and CSS3 Design Patterns

`

CSS

`.blockquote { display:block; width:500px; margin:10px auto;
  position:relative; left:0%; text-align:justify;
  line-height:1.3em; color:black;
  padding-top:40px; padding-left:40px;
  background:url("dq1.jpg") no-repeat top left white; }

.blockquote span { display:block;
  padding-bottom:20px; padding-right:40px;
  background:url("dq2.jpg") no-repeat bottom right; }

.blockquote cite { display:block; text-align:right; font-size:0.9em; }`

行内块引用

Image

行内报价

Image

HTML

`

Inline Quote

****   "A quote should be followed by a citation."   **(**Pro HTML5 and CSS3 Design Patterns**)**

**  **   "If you embed a quote inside <q> most browsers   will automatically insert double quotes — whether or not you want them!"   **(** Pro HTML5 and CSS3 Design Patterns**)**

`

CSS

.quote { letter-spacing:0.07em; } .quote cite { font-size:0.9em; }

行内报价

Image

二十、警报

本章讨论创建警报的设计模式。警告通过将重要信息从内容中分离出来,向读者指出这些信息。警报有两种基本类型:动态静态。本章中的前三个设计模式是动态警告,它在用户与文档交互时动态显示信息。本章中的其余警报是静态警报,它们总是显示在文档中。警报设计模式是一个 HTML 模式,它基本上是一个标题,后跟警报消息。Alert 之后的设计模式将它与其他设计模式相结合,演示了如何将现有的设计模式结合起来创建新的设计模式。

章节大纲

  • JavaScript Alert 展示了如何基于事件动态弹出警报。
  • 工具提示提示展示了如何创建一个工具提示来向用户显示额外的信息。
  • 弹出警告展示了如何弹出警告,向用户显示额外的信息。
  • Alert 显示了警报的基本 HTML 结构。
  • Inline Alert 展示了如何使用 Inline 元素制作一个警告。
  • 悬挂提醒展示了如何通过使用不需要额外标记的悬挂缩进,将提醒的标题移动到左侧,将内容移动到右侧。
  • 图形警告展示了如何将警告的标题移动到左侧,将内容移动到右侧,并用图像替换标题。
  • 运行警报显示如何将警报标题运行到内容的第一行。
  • 浮动警告展示了如何将警告浮动到内容的左侧或右侧,标题在左侧,内容在右侧。
  • 左边距警告展示了如何使用绝对定位将警告移动到左边距。
  • 右边距警告展示了如何使用绝对定位将警告移动到右边距。
  • 表单验证展示了如何本地验证 HTML5 表单,并在用户输入错误时提醒用户。

JavaScript 预警

Image

HTML

`

JavaScript Alert

A JavaScript alert pops up a dialog box when the user clicks it.   Its presence can be signalled by a small image**alert**

or specially styled text, such as a
**  **
   dotted underline.

`

CSS

`*.alert-image { cursor:pointer; margin-left:3px; }

*.alert { cursor:pointer; border-bottom:1px dotted;
  font-style:normal; font-size:0.8em; }`

JavaScript 预警

Image

工具提示警告

Image

HTML

`

Tooltip Alert

A tooltip alert slips right into the flow of text. It is usually signalled   by a small image****

or some type of text decoration, such as a
  
  dotted underlineTooltip text goes here..

`

CSS

`*.tooltip-image { cursor:help; margin-left:3px; }

*.tooltip { cursor:help; border-bottom:1px dotted;
  font-style:normal; font-size:0.8em; }`

工具提示警告

Image

弹出预警

Image

HTML

`

Popup Alert

  

A pop-up can show tips and help.     tip     Pop-up help goes here.     
    A pop-up can show the definition of a     word.     Pop-up definition goes here.     
    A pop-up can preview the target of a     link       .

`

CSS

`*.popup-trigger { position:relative; }

*.popup { position:absolute; left:0; top:1em; z-index:1;
  padding:5px; text-align:center; }

*.popup-trigger *.popup { visibility:hidden; }

/* Nonessential rules are not shown */`

弹出预警

Image

弹出预警

HTML 标题

`
  

<script language="javascript" type="text/javascript" src="yahoo.js">
  <script language="javascript" type="text/javascript" src="event.js">
  <script language="javascript" type="text/javascript" src="chdp.js">
  <script language="javascript" type="text/javascript" src="cssQuery-p.js">
  <script language="javascript" type="text/javascript" src="page.js">

`

页. js

`function initPage() {
  assignEvent( 'click', '.popup-trigger',
    applyToDescendants, '
.popup', toggleVisibility );

assignEvent( 'mouseover', '.popup-trigger',
    applyToDescendants, '
.popup', showElement );

assignEvent( 'mouseout', '.popup-trigger',
    applyToDescendants, '
.popup', hideElement );
}

addEvent(window, 'unload', purgeAllEvents);
addEvent(window, 'load', initPage);

//The functions addEvent() and assignEvents() are in chdp.js.
//Full documentation for each function is found in the source code.`

弹出预警

Image

预警

Image

HTML

`

Alert

Text above the alert.


  

Alert Heading


  

This is the content of the alert. It contains important information
    you want to point out to the reader.
  

Text below the alert.

`

CSS

*.alert { margin:40px;   padding-left:20px; padding-right:20px;   border-top:1px solid black; border-bottom:1px solid black;   background-color:gold; } *.alert h3 { font-size:1.3em; } *.alert p { letter-spacing:1.5px; line-height:1.5em; } *.alert.tip h3 { text-transform:uppercase; }

预警

Image

行内预警

Image

HTML

`

Inline Alert

An inline alert slips right into the flow of text.   As such it can be broken across lines.

**  **
**    Alert:
**    
brief message.
  

You can keep the alert's message brief and you can use
  white-space:nowrap to prevent it from breaking across lines.
  It is also important to make the line height large enough to prevent the
  alert's padding and border from overlapping neighboring lines.

`

CSS

`*.alert { white-space:nowrap; line-height:2.3em;
  margin:0 20px; padding:8px 20px 5px 20px;
  border-top:1px solid black; border-bottom:1px solid black;
  background-color:gold; }

*.alert *.heading { font-weight:bold; font-size:1.3em; }

*.alert *.content { letter-spacing:1.5px; font-style:normal; }

*.alert.tip *.heading { text-transform:uppercase; }`

行内预警

Image

悬挂警戒

Image

HTML

`

Hanging Alert

Text above the alert.


**  

 Tip

**
  

The Hanging Alert uses the Hanging Indent design pattern to hang the
    heading to the left and pad the content to the right. The Inline Decoration
    design pattern optionally decorates the Alert's heading.

Text below the alert.

`

CSS

`*.alert { padding-right:20px; padding-top:10px; padding-bottom:10px;
  border-top:1px solid black; border-bottom:1px solid black; margin:40px; }

*.alert h3 { display:inline; font-size:1.3em; text-transform:uppercase; }

*.alert.tip { text-indent:-80px; padding-left:80px; }
*.alert.note { text-indent:-110px; padding-left:110px; }
*.alert.caution { text-indent:-160px; padding-left:160px; }

*.alert.tip p { display:inline; margin-left:18px; }
*.alert.note p { display:inline; margin-left:20px; }
*.alert.caution p { display:inline; margin-left:20px; }

**.alert .decoration { border-left:15px solid gold; margin-right:-10px;
  font-size:0.7em; vertical-align:2px; }`

悬挂警戒

Image

图形预警

Image

HTML

`

Graphical Alert

Text above the alert.

**  

**
    

Tip


    

The Graphical Alert design pattern combines the Left Marginal design pattern
      and the Text Replacement design pattern to display a graphic
      on top of the heading.

Text below the alert.

`

CSS

`*.alert { position:relative; margin:20px 0 20px 120px; }
*.alert h3 { margin:10px 0; font-weight:bold; font-size:1.3em;
  text-transform:uppercase; }
*.alert p { margin:10px 0; }

*.alert.tip p { color:green; border:4px ridge green; padding:20px; }

*.alert.tip h3 { position:absolute; left:-100px; top:-15px;
  width:71px; height:117px; padding:0; overflow:hidden; }

*.alert.tip h3 em { position:absolute; left:20px; top:25px; }

*.alert.tip span { position:absolute; left:0; top:0; margin:0;
  width:71px; height:117px; background:url("tip.jpg") no-repeat; }`

图形预警

Image

磨合预警

Image

HTML

`

Run-In Alert

Text above the alert.


  

 Caution


  

The Run-In Alert runs the alert's heading into the text using
    display:inline on both the heading and the paragraph.

Text below the alert.

`

CSS

`*.alert { padding-right:20px; padding-top:10px; padding-bottom:10px;
  border-top:1px solid black; border-bottom:1px solid black; margin:40px; }

*.alert h3 { display:inline; font-size:1.3em; text-transform:uppercase; }

*.alert p { display:inline; margin-left:10px; letter-spacing:-0.8px }

*.alert.caution { color:red;
  border-top:3px double red; border-bottom:3px double red; }

*.alert *.decoration { border-left:15px solid gold;
  margin-right:-11px; font-size:0.7em; vertical-align:2px; }`

磨合预警

Image

浮动预警

Image

HTML

`

Floating Alert

Text above the alert.


  

 Note


  

The Floating Alert design pattern floats the entire alert. Internally it also
    floats the alert's heading to the left and its paragraph to the right.

Text below the alert.

Notice how the alert is removed from the flow. Also notice how the browser   automatically shrinks the right margin of this text so that it does not   collide with the left margin of the floated alert.

`

CSS

`*.alert { float:right; width:350px; margin-left:20px;
  border-top:1px solid black; border-bottom:1px solid black; }

*.alert h3 { float:left; width:50px; margin:10px 0;
  font-size:1.3em; text-transform:uppercase; }

*.alert p { float:right; width:250px; margin:10px 0; }

*.alert.note { color:blue;
  border-top:2px groove blue; border-bottom:2px ridge blue; }

*.alert *.decoration { border-left:15px solid gold;
  margin-right:-11px; font-size:0.7em; vertical-align:2px; }`

浮动预警

Image

左边界警戒

Image

HTML

`

Left Marginal Alert


  

Text above the alert.


**  
**
    

 Tip


    

The Left Marginal Alert design pattern moves the entire alert into the
       left margin. Inside the alert itself, its heading is absolutely positioned
       to the left and its paragraph to the right.


  

  

Text below the alert.


  

Notice how the alert is removed from the flow and moves into the margin.
    Unlike the Floating Alert, you have to size the right or left margin
    to make room for the marginal alert.

`

CSS

***.main { position:relative; margin-left:400px; }** ***.alert { position:absolute; width:350px; left:-400px; height:190px;**   border-top:1px solid black; border-bottom:1px solid black; } ***.alert h3 { position:absolute; left:0; top:15px; margin:0;**   font-size:1.3em; text-transform:uppercase; } ***.alert p { position:absolute; left:80px; top:15px; margin:0; }** *.alert.tip { color:green;   border-top:4px groove green; border-bottom:4px ridge green; } *.alert *.decoration { border-left:15px solid gold;   margin-right:-11px; font-size:0.7em; vertical-align:2px; }

左边界警戒

Image

右旁注

Image

HTML

`


  

Text above the alert.

**  

**
    

 Tip


    

The Right Marginal Alert design pattern moves the entire alert into the
       right margin. Inside the alert itself, its heading is absolutely positioned
       to the left and its paragraph to the right.


  

Text below the alert.


  

Notice how the alert is removed from the flow and moves into the margin.
    Unlike the Floating Alert, you have to size the right or left margin
    to make room for the marginal alert.

`

CSS

`*.main { position:relative; padding-right:400px; }
*.alert { position:absolute; width:350px; right:0; height:190px;
  border-top:1px solid black; border-bottom:1px solid black; }
*.alert h3 { position:absolute; left:0; top:15px; margin:0;
  font-size:1.3em; text-transform:uppercase; }

*.alert p { position:absolute; left:80px; top:15px; margin:0; }
*.alert.tip { color:green;
  border-top:4px groove green; border-bottom:4px ridge green; }
**.alert .decoration { border-left:15px solid gold;
  margin-right:-11px; font-size:0.7em; vertical-align:2px; }`

右旁注

Image

表单验证

Image

HTML

`

Form Validation

Please fill in form:

  
                   
  `

CSS

input {margin-right: 10px;}

表单验证

Image

posted @ 2024-08-19 15:41  绝不原创的飞龙  阅读(31)  评论(0)    收藏  举报