CSS中定位position的使用

2011-01-24 阅读 58

毋庸置疑的是,pisition是css中是最重要的属性之一。尽管如此,对于初学者来说布局还是会有些混淆的。

首先,什么是定位?

当一个页面打开的时候,开始在html页面上布置元素(div、图像等)。定位可以帮你显示元素以及解决元素的重叠问题。有四种定位方式,static、relative、absolute、fixed。

默认的定位方式static

页面中所有的元素默认都是static的。静态定位意味着所有的元素都以代码顺序定位在页面上。块元素显示在块元素下面,行元素显示在行元素后面。

Relative positioning

设置定位为relative并不会在页面的现实上有太大的不同。但可以区别于普通定位方式,使用top、left、bottom、right的CSS属性。需要偏移、相对定位而不是固定在某个位置的时候,relative定位是非常有用的。

<pre class="brush:css;">    .relativeDiv{

	/*
		Moving the div to the top-left
		from where it would normally show:
	 */

	position:relative;
	top:-50px;
	left:-100px;
}

```
<h1>
	Fixed positioning</h1>
<p>
	给一个元素增加fixed定位,元素将相对浏览器窗口定位。fixed可以用来制作toolbars、button以及导航菜单menu,这些可以在一个固定的位置,随着页面一起滚动。</p>
<p>
	问题是,ie6等老的浏览器不支持。</p>
<pre class="brush:css;">    .fixedDiv{

	/*
		Fixing the div 20 px from the bottom
		of the browser window:
	 */

	position:fixed;
	right:20px;
	bottom:20px;
}

```
<h1>
	Absolute positioning</h1>
<p>
	一个absolutely的元素,在页面上相对于document或者一个非static的父元素。可以使用top、left、bottom和right这些css属性,可以精确定位元素。它支持水平和垂直居中。</p>
<pre class="brush:css;">    .parentDiv{

	/* Absolute and Fixed positioning would work as well: */

	position:relative;
}
.absoluteDiv{

	/*
		Displaying the div 50px from the right and 90px from
		the top of its parent because of the explicit positioning
	 */

	position:absolute;
	right:50px;
	top:90px;
}

```
<h1>
	总结</h1>
<p>
	使用定位,可以制作出各类高级布局的页面,这可以让你的页面设计上一个台阶。结合z-index的使用,可以改变默认的布局方式。代码中个,在后面的元素可以显示在前面元素的上方。</p>
<p>
	原文地址:http://tutorialzine.com/2010/06/microtut-how-css-position-works/</p>

css 布局 网页 positioning static relative fixed absolute

更新于 2023年03月28日
CSS