div水平居中+垂直居中

初始状态

<!DOCTYPE html>
<html lang="">
  <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>垂直居中</title>
  </head>
  <body>
    <div id="app" style="border: 1px solid red;width: 100px;height: 100px;margin: auto;"></div>
  </body>
</html>

在这里插入图片描述

水平居中

添加margin:auto

<div id="app" style="margin: auto;border: 1px solid red;width: 100px;height: 100px;"></div>

在这里插入图片描述
或者是
绝对布局 + left 50% + transform向左平移宽度的50%

垂直居中

绝对布局 + top 50% + transform向上平移高度的50%

<style>
      #app{
     
     
        position: absolute;
        top: 50%;
        transform: translate(0,-50%);
      }
</style>
<div id="app" style="border: 1px solid red;width: 100px;height: 100px;"></div>

在这里插入图片描述

垂直居中+水平居中

方法一

绝对布局 + margin:auto + top/right/bottom/left值相等

<style>
	#app{
     
     
        position: absolute;
        margin: auto;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
    }
</style>

<div id="app" style="border: 1px solid red;width: 100px;height: 100px;"></div>

在这里插入图片描述

方法二

绝对布局 + left 50% + top 50% + transform向左和上平移50%,效果图同上

<style>
      #app{
     
     
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
      }
</style>

<div id="app" style="border: 1px solid red;width: 100px;height: 100px;"></div>

猜你喜欢

转载自blog.csdn.net/weixin_39333120/article/details/115188269