理解 CSS 坐标

2007年08月20日 Web开发

CSS 用于 Web 页面的布局,布局涉及元素的位置,元素位置必须参照坐标系来确定。CSS 坐标系与数学坐标系不同,它的坐标原点在浏览器可视窗口或元素的左上角,x 轴正方向向右,而 y 轴正方向则向下,如下图所示。CSS 坐标单位包括数值、百分比和相对单位。

CSS 坐标

一个 Web 页面中,不止一个坐标系,而是有多个元素就有多少个体系。以水平选项卡式的导航条为例,下图的效果:

css_coordinate3.gif

使用了下面一张背景图像:

css_coordinate2.gif

使用一张背景图像的好处在于浏览器同时下载三个状态的背景,而不用等到需要时(如鼠标悬停时)再下载,从而避免了延迟。

这张背景图由三个 127 像素宽的选项卡组成,在定义 CSS 规则时,正常、悬停和当前状态的相应规则如下:

background:url(images/nav.gif)  no-repeat;

第一条规则表明,背景图像的左上角位置(坐标原点)要和选项卡元素(上例中的 Joumal 所在元素)的左上角位置(坐标原点)重合。如下图所示:

css_coordinate4.gif

background:url(images/nav.gif) -127px 0  no-repeat;

第二条规则表明,背景图像的左上角位置要和选项卡元素(上例中的 Home 所在元素)左上角位置(坐标原点)左侧(负值表示向左) 127 像素处的点重合。如下图所示:

css_coordinate5.gif

background:url(images/nav.gif) -254px 0  no-repeat;

第三条规则表明,背景图像的左上角位置要和选项卡元素(上例中的 Maps 所在元素)左上角左侧 254 像素处的点重合。如下图所示:

css_coordinate6.gif

通过下面这幅图可以进一步加深对两个元素(选项卡和背景图像)坐标系相对位置关系的理解:

css_coordinate7.gif



朋友们的留言

  1. UGG Sheepskin Boots Australia | 09月 19th, 2011 at 09:20

    I’m really happy I found it thank you very much

    Reply to this comment
  2. Ed Hardy T Shirts | 10月 5th, 2011 at 15:38

    Who has deceiv'd thee so oft as thy self?

    Reply to this comment
  3. new era hats | 10月 11th, 2011 at 16:37

    This really answered my problem, thank you!

    Reply to this comment
  4. cheap nike shoes | 10月 14th, 2011 at 12:13

    Thanks for your sharing!

    Reply to this comment
  5. new era hats | 11月 16th, 2011 at 14:58

    I just required some information and was searching on Google for it. I visited each page that came on first page

    and didn’t got any relevant result then I thought to check out the second one and got your blog. This is what I

    wanted!

    http://www.discounthatsshop.com/

    Reply to this comment
  6. bridal wedding dresses | 12月 14th, 2011 at 10:29

    nice post , i like it , thanks for sharing it . have a nice day.

    Reply to this comment
  7. one shoulder wedding dresses | 01月 5th, 2012 at 13:11

    thanks for sharing it and please keep doing this good job .

    Reply to this comment

我来说两句儿

可以在留言中使用以下标签 :<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam Protection by WP-SpamFree