中线定位巧解

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6 
 7     <style>
 8 
 9     body{
10         position: relative;
11         height: 2000px;
12     }
13 
14         .a{
15             width: 1226px;
16             height: 700px;
17             background-color: #bfa;
18             margin:0 auto;
19 
20         }
21 
22         .b{
23             width: 20px;
24             height: 300px;
25             background-color: red;
26             position: fixed;
27             top: 0;
28             left: 0;
29             margin-top: 100px;
30             left: 50%;
31             margin-left:613px;
32 
33         }
34 </style>
35 </head>
36 <body>
37     
38     <div class="a"></div>
39     <div class="b"></div>
40 </body>
41 </html>

要想将某块元素b固定在已水平居中的右侧元素a,

1.将要固定的块元素b开启定位,相对初始包含块定位,也可以给body开启定位

2.然后利用left: 50%;将a元素定位在视口的水平中间

3.然后利用margin-left,取a的width二分之一的值,即可固定在右侧

4.该方法缩放浏览器,b永远贴着a的右侧。

5.不可给b设置right,然后在margin-right,贴着a,因为缩放浏览器,right值会变,也就不会一直贴着a了。

原文地址:https://www.cnblogs.com/fsg6/p/12676783.html