CSS基础(9.position深入)

来源:互联网 发布:淘宝拍卖鸡血石假 编辑:程序博客网 时间:2024/06/05 04:42

继续讲解position:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>    <div style="width: 50px;height: 50px;background-color: black;    position: absolute;right: 0;bottom: 0;">asdf</div>    <div style="height: 5000px;background-color: #dddddd;">        asdfasdf    </div></body></html>

这里可以看出,和刚才的fixed不一样,这里定好之后就不会再改变了。

但是,单独用absolute没有什么意义,它要结合relative使用,将在下面介绍。


<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>    <div style="position: relative;width: 500px;height: 200px;border: 1px solid red;margin: 0 auto;">        <div style="position: absolute;left:0;bottom:0;width: 50px;height: 50px;background-color: black;"></div>    </div>    <div style="position: relative;width: 500px;height: 200px;border: 1px solid red;margin: 0 auto;">        <div style="position: absolute;right:0;bottom:0;width: 50px;height: 50px;background-color: black;"></div>    </div>    <div style="position: relative;width: 500px;height: 200px;border: 1px solid red;margin: 0 auto;">        <div style="position: absolute;right:0;top:0;width: 50px;height: 50px;background-color: black;"></div>    </div></body></html>



这里可以发现,子标签定位是依据父标签来定位,也可以为负值

我们继续:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><div style="position: fixed;background-color: black;    top:0;    bottom: 0;    right: 0;    left: 0;    opacity: 0.5;    "></div><!--opacity是透明度--><div style="height: 5000px;background-color: green;">    asdfasdf</div></body></html>

这种已经做的有点模样了。

这里的opacity是透明度,大于1会全黑。


当有三层的时候就会面临一个问题,谁再最上层?

所以,这里再引入一个z-index,谁的值大,谁再最上层。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><div style="z-index: 10; position: fixed; top: 50px; left: 100px; background-color: gold;height: 400px;width: 300px;"></div><div style="z-index:9; position: fixed;background-color: black;    top:0;    bottom: 0;    right: 0;    left: 0;    opacity: 0.5;    "></div><!--opacity是透明度--><div style="height: 5000px;background-color: green;">    asdfasdf</div></body></html>


如果我还想让最上一层在最中间,实验发现用了position的不能再用margin: 0 auto;

再引入一个新的方法:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><div style="z-index: 10; position: fixed; top: 50%; left: 50%;margin-left: -250px; margin-top: -200px;background-color: gold;height: 400px;width: 300px;"></div><div style="z-index:9; position: fixed;background-color: black;    top:0;    bottom: 0;    right: 0;    left: 0;    opacity: 0.5;    "></div><!--opacity是透明度--><div style="height: 5000px;background-color: green;">    asdfasdf</div></body></html>

原创粉丝点击