CSS绝对定位水平垂直居中

当已知父子元素高宽时,可以利用绝对定位让子元素在父元素中居中,该写法的思路是

1:先使用绝对定位

top: 50%;
left: 50%;

让子元素的左上顶点处于父元素的绝对中心点,如下图所示,此时,红圈处于当前容器的绝对中心点,如下图所示

 

要让整个子元素在整个父级元素中居中,则需要将子元素的中心点移动到红圈位置,需要做如下图的平移,所以,向左,向上偏移子元素宽高的50%

  margin-left: -100px;
  margin-top: -100px; 

 

 

 

 

 完整代码如下

<!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>
        form{
            width: 15%;
            height: 20%;            
            background-color: aqua;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -100px; 
            margin-top: -100px; 
            /* left: calc(50% - 100px);
            top: calc(50% - 100px); */
        }
        body{
            padding: 0;
            margin: 0;
            width: 100%;
            /* calc(100vh)获取视窗高度的100%。同理,使用calc(100vw可以计算视窗宽度的100%) */
            height: calc(100vh);  
            position: relative;
        }
    </style>
</head>
<body>
    <form>
        <input type="text" name="username" id="username" placeholder="用户名">
        <input type="password" name="password" id="password" placeholder="密码"><br>
        <input type="checkbox" name="aggrement" id="aggrement"> 同意协议<br>
        <input type="button" value="登录">
    </form>
</body>
</html>

 

posted @ 2022-09-02 16:08  wuther  阅读(917)  评论(0编辑  收藏  举报