语法格式
position:static|absolute|fixed|relative;
先上图
<style>
body{
margin: 0;
padding: 0;
}
.one{
width: 200px;
height: 200px;
border: solid 1px red;
}
.two{
width: 200px;
height: 200px;
border: solid 1px red;
}
</style>
图一
static属性值
表示无特殊定位,元素定位的默认值,遵循HTML元素定位规则,不能通过z-index属性进行层次分级
absolute
表示绝对定位,相对于其父级元素进行定位,元素的位置可以通过top、right、bottom和left等属性进行设置。
请看主要代码
<style>
body{
margin: 0;
padding: 0;
}
.one{
position: absolute;
top: 200px;
left: 200px;
width: 200px;
height: 200px;
border: solid 1px red;
}
.two{
/* position: absolute;
top: 200px;
left: 200px; */
width: 200px;
height: 200px;
border: solid 1px red;
}
</style>
</head>
<body>
<div class="one">1</div>
<div class="two">2</div>
</body>
图2
图2的div2,不在原来的位置了,跑到了一的位置。
relative
表示相对定位,对象不可以重叠,可以通过top、right、bottom和left等属性在页面中偏移位置,可以通过z-index属性进行层次分级。
<style>
body{
margin: 0;
padding: 0;
}
.one{
position: relative;
top: 200px;
left: 200px;
width: 200px;
height: 200px;
border: solid 1px red;
}
.two{
/* position: absolute;
top: 200px;
left: 200px; */
width: 200px;
height: 200px;
border: solid 1px red;
}
</style>
图3
这里的div2,还在原来的位置(相对于图1)。
使用俩个relative,证明不能重叠
<style>
body{
margin: 0;
padding: 0;
}
.one{
position: relative;
top: 200px;
left: 200px;
width: 200px;
height: 200px;
border: solid 1px red;
}
.two{
position: relative;
top: 200px;
left: 200px;
width: 200px;
height: 200px;
border: solid 1px red;
}
</style>
但是使用absolute,两个div是可以重叠的。
fixed
表示悬浮,使元素固定在屏幕的某个位置,其包含块使可视区域本身,它不随滚动条的滚动而滚动
<style>
body{
margin: 0;
padding: 0;
}
.one{
position: absolute;
top: 200px;
left: 200px;
width: 200px;
height: 200px;
border: solid 1px red;
}
.two{
position: fixed;
top: 200px;
left: 200px;
width: 200px;
height: 200px;
border: solid 1px red;
}
</style>
Z-index
- 所有主流浏览器都支持 z-index 属性。
- z-index 属性设置元素的堆叠顺序。拥有更高堆叠顺序的元素总是会处于堆叠顺序较低的元素的前面。
- 元素可拥有负的 z-index 属性值。
- Z-index 仅能在定位元素上奏效(例如 position:absolute;)
<style type="text/css">
img.x
{
position:absolute;
left:0px;
top:0px;
z-index:-1
}
</style>
</head>
<body>
<h1>这是一个标题</h1>
<img class="x" src="/i/eg_mouse.jpg" />
<p>默认的 z-index 是 0。Z-index -1 拥有更低的优先级。</p>
</body>
推荐
推荐一个博客,这个人写的不错,我也学到不少东西
https://www.cnblogs.com/qianguyihao/p/8296748.html
总结
- 相对定位不脱标(不脱离标准流文档),相对定位的真实位置还在
- 绝对定位的盒子脱离了标准文档流。
- 绝对定位之后,标签就不区分所谓的行内元素、块级元素了,不需要display:block就可以设置宽、高了。
- top属性,参考点就是页面的左上角,而不是浏览器的左上角
- bottom属性,参考点,对应的页面的左下角