Blog
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)

HiuZing

🍑
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)
  • 前端面试题

  • JavaScript

  • Vue2

  • port

  • CSS

    • flex

    • Scss

    • CSS常见问题

      • CSS行内块之间的缝隙
      • CSS命名规范
      • CSS实现单行、多行文本溢出隐藏
      • CSS工具
      • CSS宽高比
      • CSS图片之间的缝隙
      • CSS渐变边框
      • CSS样式-动态绑定
      • CSS样式穿透
      • CSS实现两栏布局
      • CSS实现三栏布局
      • CSS实现双飞翼(圣杯)布局
      • CSS实现水平垂直居中
        • CSS实现水平垂直居中
          • 利用绝对定位
          • 利用绝对定位
          • 利用绝对定位
          • 使用flex布局
      • CSS-BFC
      • CSS-Position
      • CSS-定义使用变量
      • CSS-display
      • CSS-盒模型
      • transform
      • Animate.css
    • less

  • Node.js

  • JavaScript优化

  • uniapp

  • Mini Program

  • TypeScript

  • 面向对象编程

  • UI组件

  • Plugin

  • Vue3

  • 性能优化

  • Axios

  • 状态管理

  • React

  • Mock

  • Icon

  • Template

  • 构建工具

  • 项目规范配置

  • Taro

  • SVG

  • React Native

  • 前端
  • CSS
  • CSS常见问题
HiuZing
2022-11-09
目录

CSS实现水平垂直居中

# CSS实现水平垂直居中

# 利用绝对定位

先将元素的左上角通过top:50%和left:50%定位到页面的中心,然后再通过translate来调整元素的中心点到页面的中心。

该方法需要考虑浏览器兼容问题

.parent {   
    position: relative;
} 
.child {    
    position: absolute;    
    left: 50%;    
    top: 50%;    
    transform: translate(-50%,-50%);
}
1
2
3
4
5
6
7
8
9

为什么有时候⽤translate来改变位置⽽不是定位?

translate 是 transform 属性的⼀个值。改变transform或opacity不会触发浏览器重排(reflow)或重绘(repaint),只会触发复合(compositions)。⽽改变绝对定位会触发重排,进⽽触发重绘和复合。

transform使浏览器为元素创建⼀个 GPU 图层,但改变绝对定位会使⽤到 CPU。 因此translate()更⾼效,可以缩短平滑动画的绘制时间。 ⽽translate改变位置时,元素依然会占据其原始空间,绝对定位就不会发⽣这种情况。

# 利用绝对定位

设置四个方向的值都为0,并将margin设置为auto,由于宽高固定,因此对应方向实现平分,可以实现水平和垂直方向上的居中。

该方法适用于盒子有宽高的情况

.parent {
    position: relative;
}
 
.child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}
1
2
3
4
5
6
7
8
9
10
11
12

# 利用绝对定位

先将元素的左上角通过top:50%和left:50%定位到页面的中心,然后再通过margin负值来调整元素的中心点到页面的中心。

该方法适用于盒子宽高已知的情况

.parent {
    position: relative;
}
 
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;     /* 自身 height 的一半 */
    margin-left: -50px;    /* 自身 width 的一半 */
}
1
2
3
4
5
6
7
8
9
10
11

# 使用flex布局

通过align-items:center和justify-content:center设置容器的垂直和水平方向上为居中对齐,然后它的子元素也可以实现垂直和水平的居中。

该方法要考虑兼容的问题,该方法在移动端用的较多

.parent {
    display: flex;
    justify-content:center;
    align-items:center;
}
1
2
3
4
5
上次更新: 2024/08/14, 04:14:33
CSS实现双飞翼(圣杯)布局
CSS-BFC

← CSS实现双飞翼(圣杯)布局 CSS-BFC→

最近更新
01
React Native 使用SVG
08-13
02
Docker基础命令
08-04
03
算数逻辑单元
07-30
更多文章>
Theme by Vdoing | Copyright © 2021-2024 WeiXiaojing | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式