CSS 垂直水平居中总结(全)

以下面的代码为例

<div class="container">
  <div class="item"></div>
</div>

1,不需要知道元素的宽高

1.1,flex(2种)

最常用的,没有任何限制。

.container{
   
  display: flex;
  justify-content: center;
  align-items: center;
}

.container{
   
  display: flex;
}
.item {
   
  margin: auto;
}

1.2,grid(2种)

.container {
   
  display: grid;
  align-content: center;
  justify-content: center;
}
.container{
   
  display: grid;
}
.item {
   
  margin: auto;
}

1.3,verticle-align:middle

限制:

  1. 元素 display: inline-block
  2. 需要有一个兄弟元素作为参照物,并且会以最高的兄弟元素为作为参考,垂直于兄弟元素的中心点。所以可以利用伪元素。
.container {
   
  text-align: center;
}
.container::before {
   
  content : '';
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}
.item {
   
  display: inline-block;
  width: 100px;
  height: 100px;
  vertical-align: middle;
}

1.4,绝对定位

.container {
   
   position: relative;
}
.item {
   
   width: 100px;
   height: 100px;
   position: absolute;
   left: 0;
   top: 0;
   bottom: 0;
   right: 0;
   margin: auto;
}

上下左右为 0 可以替换为 inset: 0,不过注意可能会有兼容性问题,参考

1.5,table-cell

限制:元素 display: inline-block

.container {
   
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.item {
   
  display: inline-block;
  width: 100px;
  height: 100px;
}

2,需要知道元素的宽高

2.1,绝对定位

.container {
   
   position: relative;
}
.item {
   
   width: 100px;
   height: 100px;
   position: absolute;
   left: 50%;
   top: 50%;
   margin: -50px 0 0 -50px;
   /* 或 */
   transform: translateX(-50px) translateY(-50px);
}

阮一峰-网格布局

以上。

相关推荐

  1. CSS 垂直水平居中总结

    2023-12-08 13:58:04       49 阅读
  2. CSS水平垂直居中

    2023-12-08 13:58:04       37 阅读
  3. 总结css水平居中

    2023-12-08 13:58:04       19 阅读
  4. CSS中的水平垂直居中元素的多种方式

    2023-12-08 13:58:04       46 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-08 13:58:04       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-08 13:58:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-08 13:58:04       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-08 13:58:04       20 阅读

热门阅读

  1. 使用kubeadm搭建高可用的K8s集群

    2023-12-08 13:58:04       36 阅读
  2. 香港商标注册申请所需资料及办理流程

    2023-12-08 13:58:04       37 阅读
  3. 快应用组件通信

    2023-12-08 13:58:04       36 阅读
  4. Docker load 命令

    2023-12-08 13:58:04       40 阅读
  5. ubuntu 安装Nvidia驱动

    2023-12-08 13:58:04       49 阅读
  6. Vue.js深度解析:前端开发的生产力引擎

    2023-12-08 13:58:04       35 阅读
  7. facebook广告和谷歌广告的区别

    2023-12-08 13:58:04       42 阅读