首页 > 开发 > CSS > 正文

如何让一个div居于页面正中间【实现方法】

2024-07-11 08:25:37
字体:
来源:转载
供稿:网友

如何让一个div居于页面中间,我今天说的是让一个div水平居中同时垂直居中,而不是简单的top:50%,left:50%。当然,我们就按一开始的思路写一下:top,left属性都设为50%,看一下效果。

JavaScript Code复制内容到剪贴板
  1. <!DOCTYPE html>    <html lang="en">   
  2. <head>        <meta charset="UTF-8">   
  3.     <title>div居于页面正中间</title>        <style type="text/css">   
  4.         *{                margin: 0;   
  5.             padding: 0;                background-color: #EAEAEA;   
  6.         }            div{   
  7.             width: 200px;                height: 200px;   
  8.             background-color: #1E90FF;            }   
  9.         .center-in-center{                position: absolute;   
  10.             top: 50%;                left: 50%;   
  11.         }        </style>   
  12. </head>    <body>   
  13.     <div class="center-in-center"></div>    </body>   
  14. </html>  

从我的截图可以看出,div的左顶点刚好在页面的中心点处。现在的思路是,如何移动div然后让div的中心和页面中心重合,即可达到我们一开始想要的结果。在这里我要介绍一种方法,使用css的transform属性。由于这个属性的值很多,我这里就不一一介绍,只是说一下它的translate。我们给刚才的center-in-center类加上translate(0,-50%)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表