CSS定位

大纲

定位

何为定位?

定位就是将元素定在网页中的任意位置

为何用定位?

因为有时候需要对某些元素进行定位

相对定位

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>相对定位</title>
    <link rel="stylesheet" href="reset.css">
    <style>
        .box1{
            width: 200px;
            height: 200px;
            background-color: blue;
            /*给第一个盒子相对定位 相对整个body的定位*/
            position: relative;
            top: 120px;
            left: 200px;
    </style>
</head>
<body>
    <div class="box1">我是div1盒子</div>
    <div class="box2">我是div2盒子</div>
</body>
</html>

绝对定位

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>绝对定位</title>
    <link rel="stylesheet" href="reset.css">
    <style>
        .box1{
            width: 200px;
            height: 200px;
            background-color: blue;
            /*给第一个盒子绝对定位 会脱离文档流,原先的位置会被填充*/
            position: absolute;
            top: 120px;
            left: 200px;
        }
        .box2{
            width: 200px;
            height: 200px;
            background-color: hotpink;
        }
    </style>
</head>
<body>
    <div class="box1">我是div1盒子</div>
    <div class="box2">我是div2盒子</div>
</body>
</html>

固定定位

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>固定定位</title>
    <link rel="stylesheet" href="reset.css">
    <style>
        body{
            height: 2500px;
        }
        div{
            width: 300px;
            height: 300px;
        }
        /*固定定位*/
        .box2{
            background-color: hotpink;
            position: fixed;
            right: 50px;
        }
    </style>
</head>
<body>
    <div class="box1">我是div1盒子</div>
    <div class="box2">我是div2盒子</div>
</body>
</html>

定位补充

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>固定定位</title>
    <link rel="stylesheet" href="reset.css">
    <style>
        li{
            /*去除无序列表前的点*/
            list-style: none;
            width: 50px;
            height: 50px;
            /*绝对定位*/
            position: absolute;
        }
        .box1{
            background-color: red;
            /*权重值 值越大,则显示*/
            z-index: 2;
        }
        .box2{
            background-color: cyan;
            z-index: 1;
        }
        .box3{
            background-color: purple;
            z-index: 1;
        }
        .box4{
            background-color: hotpink;
            z-index: 1;
        }
    </style>
</head>
<body>
<!--多行同时编辑,按住alt键,鼠标点击-->
    <ul>
        <li class="box1">列表1</li>
        <li class="box2">列表2</li>
        <li class="box3">列表3</li>
        <li class="box4">列表4</li>
    </ul>
</body>
</html>
posted @ 2022-04-26 11:37  猪腩飞了天  阅读(23)  评论(0编辑  收藏  举报