当前位置: 首页 > news >正文

元素水平垂直居中的方法

元素水平垂直居中的方法

  • 不知道元素宽高大小仍能实现水平垂直居中的方法
    • 利用定位+margin:auto
    • 利用定位+transform
    • flex弹性布局
    • grid网格布局
  • 内联元素居中布局
  • 块级元素居中布局

不知道元素宽高大小仍能实现水平垂直居中的方法

  • 利用定位+margin:auto
  • 利用定位+transform
  • flex弹性布局
  • grid网格布局

利用定位+margin:auto

<style>
.father{width:500px;height:300px;border:1px solid #0a3b98;position: relative;
}
.son{width:100px;height:40px;background: #f0a238;position: absolute;top:0;left:0;right:0;bottom:0;margin:auto;
}
</style>
</style>
<div class="father"><div class="son"></div>
</div>

利用定位+transform

<style>
.father {position: relative;width: 200px;height: 200px;background: skyblue;
}
.son {position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);width: 100px;height: 100px;background: red;
}
</style>
<div class="father"><div class="son"></div>
</div>

flex弹性布局

<style>
.father {display: flex;justify-content: center;align-items: center;width: 200px;height: 200px;background: skyblue;
}
.son {width: 100px;height: 100px;background: red;
}
</style>
<div class="father"><div class="son"></div>
</div>

grid网格布局

<style>
.father {display: grid;align-items:center;justify-content: center;width: 200px;height: 200px;background: skyblue;
}
.son {width: 10px;height: 10px;border: 1px solid red
}
</style>
<div class="father"><div class="son"></div>
</div>

内联元素居中布局

水平居中

  • 行内元素可设置:text-align: center
  • flex布局设置父元素:display: flex; justify-content: center

垂直居中

  • 单行⽂本父元素确认⾼度:height === line-height
  • 多行⽂本父元素确认⾼度:display: table-cell; vertical-align: middle

块级元素居中布局

水平居中

  • 定宽: margin: 0 auto
  • 绝对定位+left:50%+margin:负自身⼀半

垂直居中

  • position: absolute设置left、top、margin-left、margin-top(定高)
  • display: table-cell
  • transform: translate(x, y)
  • flex(不定高,不定宽)
  • grid(不定高,不定宽),兼容性相对⽐较差
http://www.xdnf.cn/news/931789.html

相关文章:

  • Jinja2深度解析与应用指南
  • 高等数学》(同济大学·第7版)第三章第四节“函数的单调性与曲线的凹凸性“
  • 开源大模型网关:One API实现主流AI模型API的统一管理与分发
  • 【C++系列】智能指针自定义析构
  • 如何将淘宝店铺商品搬到抖店去?利用 API 实现淘宝店铺商品到抖店的高效迁移
  • 5-C#的DateTime使用
  • Web后端基础(基础知识)
  • 基于PTN传输承载的4G网络-故障未连接...(我不理解哪错了排查了几遍没发现哪错啊啊啊啊)
  • AI架构师如何创建自己的知识库
  • JS手写代码篇---手写ajax
  • 计组_导学
  • 云备份项目
  • 行为型设计模式之Mediator(中介者)
  • java面试:JAVA并发篇
  • android计算器代码
  • uni-app学习笔记二十四--showLoading和showModal的用法
  • 自然语言处理——文本表示
  • 泛型约束:用于限制泛型类型参数的范围
  • 力扣HOT100之二分查找:4. 寻找两个正序数组的中位数
  • 深入解析 Pandas 核心数据结构:Series 与 DataFrame
  • ubuntu 安装 sougou
  • c++ 头文件
  • iview组件库:当后台返回到的数据与使用官网组件指定的字段不匹配时,进行修改某个属性名再将response数据渲染到页面上的处理
  • 海思Hi3798MV310_V39_HMS DDR3_安卓9.0_外贸盒update升级包
  • ALOHA ACT算法与源码笔记
  • Keil进阶操作
  • 前沿探索:可视化助力设备运维实现跨越式发展
  • JAVA反序列化应用 : URLDNS案例
  • 前端获取接口数据流程
  • 二分答案-P1873 砍树