css定位属性

306 阅读1分钟

定位属性position :


一、position :static; 标准流布局展示(默认值)

相当于没有设置 二、position :relative; 相对自身原来的位置进行偏移(相对定位)
直接使用使用left right top bottom来移动开启相对定位的标签(属性) 例:使用相对定位position: relative做出下图效果:

1.png

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>定位</title>
<style>
     *{margin0;padding:0;}
    .a{
        width: 300px;
        height: 300px;
        border: 1px solid red;
        padding: 10px;
        margin: 10px auto;
    }
    .b{
        display: block;
        width: 100px;
        height: 100px;
        background-color: #FF88FC;
        position: relative;
        text-align: center;
        line-height: 100px;
        text-decoration: none;
        color: white;
    }
    .b:nth-child(2){
        left: 100px;
    }
    .b:nth-child(3){
        left: 200px;
    }
    .b:nth-child(4){
        left: 200px;
        bottom: 300px;
    }
    .b:nth-child(5){
        bottom: 200px;
    }
</style>
</head>
<body>
<div class="a">
    <a href="#" class="b">链接</a>
    <a href="#" class="b">链接</a>
    <a href="#" class="b">链接</a>
    <a href="#" class="b">链接</a>
    <a href="#" class="b">链接</a>
</div>
</body>
</html>

三、position : absolute; (绝对定位)

如果要固定位置,需要放在开启相对定位(relative)的先祖元素里进行使用。如果没有在设置定位的先祖元素那么会以浏览器窗口作为基准进行定位

使用绝对定位和相对定位实现下图的效果:

2.png 代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>定位</title>
<style>
    *{margin: 0;padding: 0;}
    .a{
        width: 300px;
        height: 300px;
        background-color: tomato;
        position: relative;
        margin: 10px auto;
        padding: 10px;
    }
    .b{
        width: 100px;
        height: 100px;
        background-color: blue;
        position: absolute;
    }
    .a div:nth-child(2){
        left: 210px;
    }
    .a div:nth-child(3){
        left: 210px;
        top: 210px
    }
    .a div:nth-child(4){
        top: 210px
    }
    .a div:nth-child(5){
        left: 110px;
        top: 110px
    }

</style>
</head>
<body>
        <div class="a">
            <div class="b"></div>
            <div class="b"></div>
            <div class="b"></div>
            <div class="b"></div>
            <div class="b"></div>
        </div>
</body>
</html>

四、position:fixed; 固定在网页的一个位置(固定定位)

相对于视口定位的,这意味着即使滚动页面,它也始终位于同一位置。

五、z-index 属性

使用定位属性设置z-index:;就可以让设置relative、absolute、dixed定位属性的层级提高,它的值用阿拉伯数字表示