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

【CSS】div 盒子居中的常用方法

<body><div class="main"><div class="box"></div></div>
</body>
  1. 绝对定位加 margin: auto;
<style>* {padding: 0;margin: 0;}.main {width: 400px;height: 400px;border: 2px solid #000;position: relative;margin: 30px auto;}.box {width: 100px;height: 100px;background-color: #f00;position: absolute;top: 0;left: 0;right: 0;bottom: 0;margin: auto;}
</style>
  1. 绝对定位加负 margin:
<style>* {padding: 0;margin: 0;}.main {width: 400px;height: 400px;border: 2px solid #000;position: relative;margin: 30px auto;}.box {width: 100px;height: 100px;background-color: #f00;position: absolute;top: 50%;left: 50%;margin-top: -50px;margin-left: -50px;}
</style>
  1. margin 推动:
<style>* {padding: 0;margin: 0;}.main {width: 400px;height: 400px;border: 2px solid #000;margin: 30px auto;}.box {width: 100px;height: 100px;background-color: #f00;margin: 150px 150px;}
</style>
  1. flex 居中:
<style>* {padding: 0;margin: 0;}.main {width: 400px;height: 400px;border: 2px solid #000;margin: 30px auto;display: flex;justify-content: center;align-items: center;}.box {width: 100px;height: 100px;background-color: #f00;}
</style>
  1. transform:
<style>* {padding: 0;margin: 0;}.main {width: 400px;height: 400px;border: 2px solid #000;margin: 30px auto;position: relative;}.box {width: 100px;height: 100px;background-color: #f00;position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);}
</style>
  1. 子盒子宽高不确定(需要保证left和right的百分数一样,top和bottom的百分数一样):
<style>* {padding: 0;margin: 0;}.main {width: 400px;height: 400px;border: 2px solid #000;margin: 30px auto;position: relative;}.box {background-color: #f00;position: absolute;left: 25%;top: 25%;right: 25%;bottom: 25%;}
</style><body><div class="main"><div class="box"></div></div>
</body>

在这里插入图片描述

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

相关文章:

  • Pytorch网络模型训练
  • webgoat-Path traversal
  • P8976 「DTOI-4」排列,贪心
  • 使用 Python 进行自然语言处理第 5 部分:文本分类
  • uni-app---- 点击按钮拨打电话功能点击按钮调用高德地图进行导航的功能【安卓app端】
  • 通讯录详解(静态版,动态版,文件版)
  • 在windows中搭建vue开发环境
  • 数字化转型:云表低代码开发助力制造业腾飞
  • Linux学习之vim跳转到特定行数
  • 详解基于Android的Appium+Python自动化脚本编写
  • 【马蹄集】—— 百度之星 2023
  • 大数据毕业设计选题推荐-无线网络大数据平台-Hadoop-Spark-Hive
  • 【jvm】虚拟机之本地方法接口与本地方法库
  • HDFS系统操作命令大全
  • 雷尼绍探头编程 9810
  • el-table 列分页
  • APP攻防--ADB基础
  • 【Linux】第十站:git和gdb的基本使用
  • Single Image Haze Removal Using Dark Channel Prior(暗通道先验)
  • 力扣382.链表随机节点(java利用数组随机返回节点值)
  • 在jupyter中使用R
  • 2023(第四届)江西开放数据创新应用大赛等你来挑战!
  • 2023-mac rz sz 安装
  • 使用Matplotlib绘画3D图时运行不出结果,也不报错,图片是空白 !!
  • Matlab函数——find
  • mac安装python3
  • 【星海出品】VUE(一)
  • Stable Diffusion 的提示词使用技巧
  • Hook函数
  • USB简介系列-01