水平垂直居中的几种方案

  1. 相对定位实现
  position: relative;/*设置相对定位*/
  width:100px;
  height:200px;
  top: 50%;
  left: 50%;
  margin-top: -100px;/*值为高度的一半*/ 
  margin-right:-50px;/*值为宽度的一半*/

  1. 绝对定位实现
  position: absolute;/*设置绝对定位*/
  margin: auto;/*对齐方式平均*/
  /*上右下左值设为0,也就是默认*/
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  1. 定位与变换实现居中
  position: absolute;/*绝对定位*/
  left: 50%;/*左边距离50%*/
  top: 50%;/*上边距离50%*/
  transform: translate(-50%,-50%);/*分别向左和上平移自身宽高的50%*/

  1. flex布局实现
display: flex;/*设置flex属性*/
align-items: center;/*垂直居中*/
justify-content: center;/*水平居中*/

posted @ 2022-05-10 09:45  见信  阅读(37)  评论(0)    收藏  举报