固定定位常用的2种形式(小技巧)

1.固定到浏览器

效果

效果图

样式:

 .fixed-box{
    
    
            position: fixed;
            top: 300px;
            /* 1.浏览器宽度的一半 */
            right: 0px;
            /* 2.版心盒子宽度的一半 */
            width: 30px;
            background: skyblue;
        }

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
    
    
            margin: 0;
            padding: 0;
        }
        .fixed-box{
    
    
            position: fixed;
            top: 300px;
            /* 1.浏览器宽度的一半 */
            right: 0px;
            /* 2.版心盒子宽度的一半 */
            width: 30px;
            background: skyblue;
        }
    </style>
</head>
<body>
    <div class="fixed-box">固定定位的盒子</div>
</body>
</html>

2.固定到版心

效果:

效果图

原理:

原理图

分析:

1.浏览器宽度的一半 left: 50%;
2.版心盒子宽度的一半 margin-left: 300px;
一半 + 一半 = 固定盒子的宽度

样式:

	.container{
    
    
            width: 600px;
            height: 1300px;
            margin: 0 auto;
            border: 1px solid #eee;
            background-color: orange;
        }
        .fixed-box{
    
    
            position: fixed;
            top: 300px;
            /* 1.浏览器宽度的一半 */
            left: 50%;
            /* 2.版心盒子宽度的一半 */
            margin-left: 300px;
            width: 30px;
            background: skyblue;
        }

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
    
    
            margin: 0;
            padding: 0;
        }
        .container{
    
    
            width: 600px;
            height: 1300px;
            margin: 0 auto;
            border: 1px solid #eee;
            background-color: orange;
        }
        .fixed-box{
    
    
            position: fixed;
            top: 300px;
            /* 1.浏览器宽度的一半 */
            left: 50%;
            /* 2.版心盒子宽度的一半 */
            margin-left: 300px;
            width: 30px;
            background: skyblue;
        }
    </style>
</head>
<body>
    <div class="container">版心盒子</div>
    <div class="fixed-box">固定定位的盒子</div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/yrfjygb/article/details/113664071