随笔 - 312  文章 - 0  评论 - 2  阅读 - 11万

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   香香鲲  阅读(173)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示