元素居中屏幕的几种方法

来源:互联网 发布:数据抓包工具 编辑:程序博客网 时间:2024/05/21 06:41

直接上代码:

方法一:

<body>  <div class="tooltip"></div></body><style>.tooltip{      width:100px;      height:100px;      background:yellow;      position: absolute;      top:0;      right:0;      bottom:0;      left:0;      margin:auto;    }

方法二:

<body>  <div class="tooltip"></div></body><style>.tooltip{      width:100px;      height:100px;      background:yellow;      position: absolute;      top:50%;      left:50%;      transform:translateX(-50%);      transform:translateY(-50%);    }

效果:
这里写图片描述

当然还有更简单的方法,css3有一种flex布局,参考:阮一峰老师的文档

方法三:

<body>  <div class="tooltip"></div></body><style>    html,body{      margin:0;      padding: 0;      width: 100%;      height: 100%;    }    body{      display:flex;      align-items: center; /*垂直居中*/      justify-content: center;  /* 水平居中*/    }    .tooltip{      width:100px;      height:100px;      background:yellow;    }  </style>

效果是一样的。

0 0
原创粉丝点击