学习CSS布局 - position

时间:2023-03-09 06:48:55
学习CSS布局 - position

position

为了制作更多复杂的布局,我们需要讨论下 position 属性。

它有一大堆的值,名字还都特抽象,别提有多难记了。

让我们先一个个的过一遍,不过你最好还是把这页放到书签里。

先看下运行结果,在看下源码,最后解释一下position的各个属性。

结果:

学习CSS布局 - position

源码看一下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>position</title>
<style>
.static {
border: 1px solid red;
max-width: 400px;
margin: 20px auto; position: static;
} .relative1 {
border: 1px solid pink;
max-width: 400px;
margin: 20px auto; position: relative;
} .relative2 {
border: 1px solid green;
max-width: 400px;
margin: 20px auto; position: relative;
left: 30px;
top: -30px;
} .relative3 {
border: 1px solid hotpink;
max-width: 400px;
margin: 20px auto; position: relative;
} .relative {
border: 1px solid hotpink;
max-width: 500px;
height: 300px;
margin: 20px auto; position: relative;
}
.position {
border: 1px solid lime;
width: 300px;
height: 200px; position: absolute;
left: 0;
bottom: 0; } .fixed {
border: 1px solid #e3d2d2;
max-width: 200px; position: fixed;
right: 0;
bottom: 0;
}
</style>
</head>
<body>
<div class="static">
static 是默认值。<br />
任意 position: static; 的元素不会被特殊的定位。<br />
一个 static 元素表示它不会被“positioned”,<br />
一个 position 属性被设置为其他值的元素表示它会被“positioned”。<br />
</div> <div class="relative1">
relative 表现的和 static 一样,<br />
除非你添加了一些额外的属性。<br />
</div>
<div class="relative2">
在一个相对定位(position属性的值为relative)的元素上<br />
设置 top 、 right 、 bottom 和 left 属性会使其偏离其正常位置。<br />
其他的元素的位置则不会受该元素的影响发生位置改变来弥补它偏离后剩下的空隙。<br />
</div>
<div class="relative3">
随意改变relative2的div的位置,是不会影响<br />
relative1和relative3的<br />
</div> <div class="relative">
这个元素是相对定位的。如果它是 position: static; <br />
那么它的绝对定位子元素会跳过它直接相对于body元素定位。<br />
<div class="position">
这个元素是绝对定位的。它相对于它的父元素定位。
</div>
</div> <div class="fixed">
一个固定定位(position属性的值为fixed)元素会相对于视窗来定位,<br />
这意味着即便页面滚动,它还是会停留在相同的位置。<br />
和 relative 一样, top 、 right 、 bottom 和 left 属性都可用。<br />
一个固定定位元素不会保留它原本在页面应有的空隙(脱离文档流)。
</div>
</body>
</html>

接下来看一下属性解释:

static

static 是默认值。

任意 position: static; 的元素不会被特殊的定位。

一个 static 元素表示它不会被“positioned”,一个 position 属性被设置为其他值的元素表示它会被“positioned”

relative

relative 表现的和 static 一样,除非你添加了一些额外的属性。

在一个相对定位(position属性的值为relative)的元素上设置 top、 right 、 bottom 和 left 属性会使其偏离其正常位置。

其他的元素的位置则不会受该元素的影响发生位置改变来弥补它偏离后剩下的空隙。

fixed

一个固定定位(position属性的值为fixed)元素会相对于视窗来定位,这意味着即便页面滚动,它还是会停留在相同的位置。

和 relative 一样, top 、 right 、 bottom和 left 属性都可用。

一个固定定位元素不会保留它原本在页面应有的空隙(脱离文档流)。

令人惊讶地是移动浏览器对 fixed 的支持很差。这里有相应的解决方案.

absolute

absolute 是最棘手的position值。

absolute 与 fixed 的表现类似,但是它不是相对于视窗而是相对于最近的“positioned”祖先元素

如果绝对定位(position属性的值为absolute)的元素没有“positioned”祖先元素,

那么它是相对于文档的 body 元素,并且它会随着页面滚动而移动。

记住一个“positioned”元素是指 position 值不是 static的元素。

原文地址: http://zh.learnlayout.com/position.html