请问老师我有疑问

来源:2-14 编程练习

一年前我是个个性少年

2018-05-25 19:20:19

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding:0;
    }
    .test{
     width: 800px;
     height: 100px;
     background: red;
     /*此处写代码*/
     position: fixed;
     top: 0;
     left: 0;
     right: 0;
     margin: 0 auto;
     
   
   }
   .out{
    width: 100%;
    height: 2000px;
    background-color: #abcdef;
  }
</style>
</head>
<body>
  <div class="out">
    <div class="test"></div>
  </div>
</body>
</html>
这是我的代码,效果能够剧中,但是我看别的同学的都是left:50%,margin-left:-400px.我的这样写对吗,需要改进吗?

写回答

1回答

樱桃小胖子

2018-05-25

你的代码是没有问题的,实现居中的方法是不唯一的,可以使用设置定位位移量50%,再使用margin-left:-宽度的一半,即left:50%,margin-left:-400px;也可以使用你的这种方法,你的这种方法叫做拔河效应,即设置left为0,right为0实现水平居中(相当于拔河,如果绳子两侧拉力一样,那么绳子中间的裁判标记就会处于中间状态)。

希望可以帮到你~

0

0 学习 · 36712 问题

查看课程