CSS:实现垂直水平居中的方法

1、水平居中

  1. text-align :center;  适用于行内元素
  2. margin:0 auto;  适用于块级元素
  3. dispaly:flex; justify-content:center;  适用于行内元素和块级元素
  4. margin-left:50%;transform:translateX(-50%);  适用于行内元素和块级元素
  5. 先给要居中的元素设置display:table,然后设置margin:0 auto

 

2、垂直居中

  1. line-height:行高;
  2. margin-top:50%;transform:translateY(-50%);
  3. display:flex;align-items:center;
  4. 父元素设置(relative),子元素(absolute);left:0;right:0;top:0;bottom:0;margin:auto;
  5. position:fixed;left:50%;top:50%;transform:translateX(-50%) translateY(-50%);
  6. 居中元素position:absolute,父元素position:relative;居中元素设置top:50%;margin-top:值为自身height一半的负数

3、水平垂直居中

  1. display: flex; justify-content: center; align-items: center;
  2. 父元素设置(relative),子元素(absolute);left:0;right:0;top:0;bottom:0;margin:auto;
  3. 绝对定位+left/top:50%+负margin-top/-left(需知自身宽高)
  4. 父元素设置(relative),子元素(absolute);top: calc(50% - 50px); left: calc(50% - 50px);
  5. 绝对定位+transform:
.parent {
  position: relative;    
}

.child {
  position:absolute;
  top: 50%;
  left: 50%;
  transform:translate(-50%,-50%)
}

 

posted on 2022-07-16 21:24  香香鲲  阅读(176)  评论(0)    收藏  举报