[CSS]中子元素在父元素中居中

元素居中

对于当行文字居中,比较简单,设置text-align:center和text-height为盒子高度即可

对于父元素中子元素居中,要实现的话有以下几个方法

方法1:利用定位+margin:auto

html 复制代码
<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>
<div class="father">
  <div class="son"></div>
</div>

父元素中relative相对定位,子元素absolute绝对定位,并设置top,left,right,bottom为0,并设置margin:auto

方法2:利用定位+margin:负值

html 复制代码
<style>
 .father {
 position: relative;
 width: 200px;
 height: 200px;
 background: skyblue;
 }
 .son {
 position: absolute;
 top: 50%;
 left: 50%;
 margin-left:-50px;
 margin-top:-50px;
 width: 100px;
 height: 100px;
 background: red;
 }
</style>
<div class="father">
 <div class="son"></div>
</div>

父元素中relative相对定位,子元素absolute绝对定位,并设置top,left为50%,并设置margin-left和margin-top为盒子大小的一半-50px(这种情况需要知道盒子大小)

方法3:利用定位+transform

html 复制代码
<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>

父元素中relative相对定位,子元素absolute绝对定位,并设置top,left为50%,并使用transform移动-50%,transform: translate(-50%,-50%); 此方法不需要知道盒子大小

方法4:利用flex

html 复制代码
<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>

使用flex布局,设置justify-content: center; 水平居中 align-items: center;设置垂直居中

相关推荐
杨航 AI11 分钟前
JEV的用法
java·前端·数据库
Amos_Web11 分钟前
Rspack 源码解析(三十五):rspack_error 如何用 miette 渲染带源码定位的错误链
前端
修炼的dance16 分钟前
OCR预处理测了108组,纠斜去噪有用,坑在顺序和力度
前端
不可能片场25 分钟前
AI视频成片 帧间差分把拼接缝照出来
前端·electron
写的都是BUG25 分钟前
APK 里的钥匙,一直就放在门口:聊聊加固真正该做什么
前端·算法
dpharness28 分钟前
我踩过的四个记忆坑,从预算到换机
前端·后端
用户77833661321136 分钟前
SerpBase驱动:用原生JS实现搜索意图分流浮层
前端
阿明的小蝴蝶36 分钟前
设备出厂横竖屏修改 & 默认手势导航修改(按键导航)
前端
SameX39 分钟前
ArkTS 做应用内"快捷胶囊" —— 续航日记踩过的两个鸿蒙声明式 UI workaround
前端
用户114818678948439 分钟前
水印的实现方式逻辑
前端·python