一、position的属性
1.static(默认值)
HTML 元素的默认值,即没有定位,遵循正常的文档流对象。静态定位的元素不会受到 top, bottom, left, right影响。
2.偏移量方向
3.relative(相对定位)
相对定位元素的定位是相对其正常位置,移动相对定位元素,但它原本所占的空间不会改变。相对定位元素经常被用来作为绝对定位元素的容器块。下面举例说明:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>相对定位</title>
<style>
.c1
{
position:relative;
left:200px;
}
</style>
</head>
<body>
<h2>这是位于正常位置的标题</h2>
<h2 class="c1">这个标题相对于其正常位置向右移动</h2>
</body>
</html>
4.absolute(绝对定位)
绝对定位的元素的位置相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于浏览器基准。绝对定位使元素的位置与文档流无关,因此不占据空间。元素位置发生偏移后。它原来的位置不会被保留下来。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>绝对定位</title>
<style>
h2
{
position:absolute;
left:100px;
top:150px;
}
</style>
</head>
<body>
<h2>绝对定位</h2>
</body>
</html>
5.fixed(固定定位)
元素的位置相对于浏览器窗口是固定位置。即使窗口是滚动的它也不会移动。固定定位使元素的位置与文档流无关,因此不占据空间。
.box{
height: 100px;
width: 100px;
background: red;
position: fixed;
bottom: 100px;
right: 100px;
}
二、z-index属性(设置堆叠顺序)
z-index 属性指定一个元素的堆叠顺序。拥有更高堆叠顺序的元素总是会处于堆叠顺序较低的元素的前面。设置了position属性时,z-index属性值可以设置各元素之间的重叠高低。z-index值大的位于值小的层上方。<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>z-index</title>
<style>
img
{
position:absolute;
left:0px;
top:0px;
z-index:-1;
}
</style>
</head>
<body>
<h1>图片在文字下方</h1>
<img src="w3css.gif" width="100" height="140" />
</body>
</html>
三、设置元素透明度的两种方法
1.opacity属性
值:从0到1(完全透明到不透明)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>opacity属性</title>
<style>
.bg{
width: 200px;
height: 100px;
margin: 20px auto;
}
.bg1,.bg2{
width: 100px;
height: 100px;
margin: 20px;
background:#0000fa;
}
.bg1{
opacity:1;
}
.bg2{
opacity:0.5;
}
</style>
</head>
<body>
<div class="bg">
<div class="bg1">
<p>背景1</p>
</div>
<div class="bg2">
<p>背景2</p>
</div>
</div>
</body>
</html>
2.rgba属性
值:从0到1(完全透明到不透明),且值位于rgba第四位。
例如:rgba(145,232,178,0.5)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>opacity属性</title>
<style>
.bg{
width: 200px;
height: 100px;
margin: 20px auto;
}
.bg1,.bg2{
width: 100px;
height: 100px;
margin: 20px;
}
.bg1{
background:rgba(0,0,250);
}
.bg2{
background:rgba(0,0,250,0.5);
}
</style>
</head>
<body>
<div class="bg">
<div class="bg1">
<p>背景1</p>
</div>
<div class="bg2">
<p>背景2</p>
</div>
</div>
</body>
</html>
3.两者的区别
有opacity属性的所有后代元素都会继承 opacity 属性,而rhba后代元素不会继承透明属性。就是说opacity属性内的所有内容都会被改变透明度。而rgba只作用于背景。