CSS 定位属性允许你对元素进行定位。
CSS 为定位和浮动提供了一些属性,可以建立列式布局,将布局的一部分与另一部分重叠。
定位允许你定义元素框相对于其正常位置、父元素、另一个元素甚至浏览器窗口本身的位置。
另一方面,CSS1 中首次提出了浮动,浮动不完全是定位,不过,它当然也不是正常流布局。
一切皆为框
div、h1 或 p 元素常常被称为块级元素。这意味着这些元素显示为一块内容,即“块框”。
而 span 和 strong 等元素称为“行内元素”,因为它们的内容显示在行中,即“行内框”。
您可以使用 display 属性改变生成的框的类型。
通过将 display 设置为 block,可以让行内元素(比如 <a>)表现得像块级元素一样。
通过把 display 设置为 none,让该框及其所有内容都不再显示,不占用文档中的空间。
但是在一种情况下,即使没有进行显式定义,也会创建块级元素,例如 div 的开头:
<div> some text <p>Some more text.</p> </div>注释:即使没有把这些文本定义为段落,它也会被当作段落(块级元素)对待。
<html> <head> <style type="text/css"> h2.pos_left { position: relative; left: -20px } h2.pos_right { position: relative; left: 20px } </style> </head> <body> <h2>这是位于正常位置的标题</h2> <h2 class="pos_left">这个标题相对于其正常位置向左移动</h2> <h2 class="pos_right">这个标题相对于其正常位置向右移动</h2> <p>相对定位会按照元素的原始位置对该元素进行移动。</p> <p>样式 "left:-20px" 从元素的原始左侧位置减去 20 像素。</p> <p>样式 "left:20px" 向元素的原始左侧位置增加 20 像素。</p> </body> </html>注释:本例演示如何相对于一个元素的正常位置来对其定位。
h2.pos_abs { position: absolute; left: 100px; top: 150px }注释:本例演示如何使用绝对值来对元素进行定位。
p.pos_fix { position: fixed; left: 5px; top: 5px; }注释:本例演示如何相对于浏览器窗口来对元素进行定位。
<html> <head> <style type="text/css"> div { background-color: #00FFFF; width: 150px; height: 150px; overflow: scroll; } </style> </head> <body> <div> overflow 属性可以确定是否显示滚动条等行为。 这个属性定义溢出元素内容区的内容会如何处理,默认值是 visible。 如果值为 scroll,不论是否需要,用户代理都会提供一种滚动机制。 因此,有可能即使元素框中可以放下所有内容也会出现滚动条。 </div> </body> </html>
<html> <head> <style type="text/css"> img { position: absolute; clip: rect(0px 50px 200px 0px) } </style> </head> <body> <p>clip 属性剪切了一幅图像:</p> <p><img border="0" src="../book.gif" width="120" height="151"></p> </body> </html>注释:本例演示如何设置元素的形状。此元素被剪裁到这个形状内,并显示出来。
<html> <head> <style type="text/css"> img.top {vertical-align: text-top} img.bottom {vertical-align: text-bottom} </style> </head> <body> <p>图像<img class="top" border="0" src="../cute.gif" />位于段落中。</p> <p>图像<img class="bottom" border="0" src="../cute.gif" />位于段落中。</p> </body> </html>注释:本例演示如何在文本中垂直排列图象(顶部对齐、底部对齐)。
<html> <head> <style type="text/css"> img.x { position: absolute; left: 0px; top: 0px; z-index: -1 } </style> </head> <body> <h1>这是一个标题</h1> <img class="x" src="../mouse.jpg" /> <p>默认的 z-index 是 0。Z-index -1 拥有更低的优先级。</p> </body> </html>注释:Z-index可被用于将在一个元素放置于另一元素之后。
<html> <head> <style type="text/css"> img.x { position: absolute; left: 0px; top: 0px; z-index: 1 } </style> </head> <body> <h1>这是一个标题</h1> <img class="x" src="../mouse.jpg" /> <p>默认的 z-index 是 0。Z-index 1 拥有更高的优先级。</p> </body> </html>
评论