[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;设置垂直居中

相关推荐
小村儿3 分钟前
Harness Engineering:为什么你用 AI 越用越累?
前端·后端·ai编程
enoughisenough26 分钟前
浏览器判断控制台是否开启
前端
Moment34 分钟前
当前端开始做 Agent 后,我才知道 LangGraph 有多重要❗❗❗
前端·后端·面试
竹林81838 分钟前
RainbowKit 快速集成多链钱包连接:从“连不上”到丝滑切换的踩坑实录
前端·javascript
小蜜蜂dry1 小时前
nestjs实战-登录、鉴权(一)
前端·后端·nestjs
农夫山泉不太甜1 小时前
WebSocket与SSE技术方案选型对比分析
前端
重阳微噪1 小时前
受够了空格翻页?我写了一个 Chrome 自动滚动插件,让你真正沉浸式阅读
前端
Awu12271 小时前
🍎用 pretext 搞定输入框动态宽度:一个困扰了我三天的 CSS 问题
前端
萑澈1 小时前
我用 Cloudflare 搭了一个 FlashInbox 临时邮箱
前端·next.js
慕斯fuafua1 小时前
CSS——盒模型
前端·css