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

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

元素居中

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

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

方法1:利用定位+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>
<div class="father"><div class="son"></div>
</div>

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

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

<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

<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

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

http://www.lryc.cn/news/330113.html

相关文章:

  • 电脑突然死机怎么办?
  • Kyligence 正式加入华为“同舟共济”行动计划,成为行业数智化“联盟级伙伴”
  • 大模型推理框架——text-generation-inference
  • 电梯四种事故检测YOLOV8
  • 构建docker环境下的thunder迅雷插件
  • Django开发复盘
  • 第6章 数据存储操作
  • 接口自动化框架搭建(八):pytest+allure+jenkins接入
  • linux监控命令全
  • 【GenAI】使用GenAI堆栈构建视频分析和转录字幕聊天机器人
  • 全国产数据采集卡定制,24位八通道以太网数据采集卡 labview 100K采样
  • JavaEE初阶-线程3
  • C++递归(2)
  • 算法训练营第27天|LeetCode 39.组合总和 40.组合总和2 131.分割回文串
  • 【Web】NSSCTF Round#20 Basic 两道0解题的赛后谈
  • memcached缓存数据库简介
  • C# WPF编程-Application类(生命周期、程序集资源、本地化)
  • fpga_hdmi
  • 鸿蒙(HarmonyOS)ArkTs语言基础教程开发准备
  • 【C++杂货铺】详解list容器
  • 使用filezilla连接Ubuntu22.04虚拟机
  • Verilog基础【二】
  • 定时推送任务 Apache HttpClient/okhttp3
  • centos7 安装 mysql
  • src挖掘技巧总结分享
  • 【面试八股总结】传输控制协议TCP(一)
  • 【系统架构师】-第13章-层次式架构设计
  • 【操作系统】想要更好的学习计算机,操作系统的知识必不可少!!!
  • AtCoder Grand Contest 066 B. Decreasing Digit Sums(构造 打表找规律)
  • Hadoop系列总结