4、css之position

一、position

position属性:指定一个元素(静态的,相对的,绝对或固定)的定位方法的类型。

1、fixed值

fixed值:生成固定定位的元素,相对于浏览器窗口进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。

############################
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div onclick="GoTop();" style="height: 50px; width: 50px; background-color: black; color: white;
    position: fixed;
    bottom:20px;
    right: 20px;
    ">返回顶部</div>

    <div style="height: 5000px; background-color: #dddddd"></div>

    <script>
        function GoTop() {
            document.body.scrollTop = 0;
        }
    </script>
</body>
</html>


###############################
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .pg-header{
            height: 48px;
            background-color: black;
            color: #dddddd;
            position: fixed;
            top: 0px;
            right: 0;
            left: 0px;
        }

        .pg-body{
            background-color: #dddddd;
            height: 5000px;
            margin-top: 50px;
        }
    </style>
</head>
<body>
    <div class="pg-header">头部</div>
    <div class="pg-body">内容</div>
</body>
</html>


2、absolute、relative组合使用

absolute:
生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。
元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。

relative:    
生成相对定位的元素,相对于其正常位置进行定位。
因此,"left:20" 会向元素的 LEFT 位置添加 20 像素。

#############################
##relative在父标签中,absolute在子标签中;
##absolute是相对于父标签来定位的;
<!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>

</body>
</html>

image


3、层级显示

##代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div style="z-index: 2; position: fixed; top: 50%; left: 50%;
    margin-left: -250px; margin-top: -200px; background-color: white; height: 400px; width: 500px;">
        <input type="text">
    </div>

    <div style="z-index: 1; position: fixed; background-color: black;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    opacity: 0.4;"></div>

    <div style="height: 5000px; background-color: green;">最底层页面</div>
</body>
</html>




##
opacity: 0.4;    //透明度
z-index: 1;    //层级顺序,值小的层在下面

猜你喜欢

转载自www.cnblogs.com/weiyiming007/p/10891033.html
今日推荐