美文网首页
12、根据定位和transform来设置元素居中

12、根据定位和transform来设置元素居中

作者: flyjar | 来源:发表于2022-04-01 00:01 被阅读0次
  <!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>Document</title>
    <style type="text/css">
      .main{
        width:500px;
        height:500px;
        position: relative;
      }
      .center {
        width: 100px;
        height: 100px;
        background-color: #000000;
        position: absolute;
        left: 50%; /* 相对于的是当前div左侧边线,距离父级div的距离。这个50%的是指父级的div宽度的50%;如果外层没有设置position: relative,那就是body的50% */
        margin-left: -50px; /* 为什么需要再向左侧移回去一半呢。是因为left是相对于当前div的左侧边线开始计算的。并不是以当前div的中心点来计算的,所以移回去一半正好就居中了 */
        bottom: 50%; /*和left一样*/
        margin-top: -50px;  /*和margin-left一样*/
      }


     <!--transform的方式-->
     .center {
        width: 100px;
        height: 100px;
        background-color: #000000;
        position: absolute;
        left: 50%; /* 相对于的是当前div左侧边线,距离父级div的距离。这个50%的是指父级的div宽度的50%;如果外层没有设置position: relative,那就是body的50% */
        bottom: 50%; /*和left一样*/
       transform:translate(-50%)  /*translate的百分比是当前div的宽高来比对的*/
     /* 
      为什么需要再向左侧移回去一半呢。是因为left是相对于当前div的左侧边线开始计算的。并不是以当前div的中心点来计算的,所以移回去一半正好就居中了 */
      }
    </style>
  </head>
  <body>
    <div class="main">
      <div class="center"></div>
    </div>
  </body>
</html>

相关文章

网友评论

      本文标题:12、根据定位和transform来设置元素居中

      本文链接:https://www.haomeiwen.com/subject/gleojrtx.html