HTML/CSS_如何让DIV水平垂直居中

 时间:2026-02-15 07:15:07

1、方法一:绝对定位,确认宽高设置margin属性为宽高的负一半

代码:

width: 200px; height: 100px;

background-color: crimson;

position: absolute; left: 50%; top: 50%;

margin-left: -100px; margin-top: -50px;

HTML/CSS_如何让DIV水平垂直居中

2、方法二:绝对定位:不确定宽高,使用transform: translate属性

代码:

width: 200px; height: 100px;

background-color: crimson;

position: absolute; left: 50%; top: 50%;

transform: translate(-50%, -50%);

HTML/CSS_如何让DIV水平垂直居中

3、方法三:绝对定位,设置left right top bottom属性值设置为0;margin设置成默认auto

代码:

width: 200px; height: 100px;

background-color: crimson;

position: absolute; left: 0; top: 0; right: 0; bottom: 0;

margin: auto;

HTML/CSS_如何让DIV水平垂直居中

4、方法四:在父层设置flex布局属性(高度根据自己需求设定)

代码:

父层:width: 100%; height: 200px;

display: flex; justify-content: center; align-items: center;

子层:

width: 200px; height: 100px; background-color: crimson;

HTML/CSS_如何让DIV水平垂直居中

5、方法五:将父盒子设置为table-cell元素

代码:

父层:

display:table-cell;

width: 200px; height: 200px; background: #ddd;

vertical-align: middle; text-align: center;

子层:

background-color: brown; 

width: 100px; height: 100px; display: 

inline-block;

HTML/CSS_如何让DIV水平垂直居中

6、小编目前发现了这五种方法可以实现,大家可以参考,还有很多种实现方法大家多尝试!

  • 腾讯会议不想听怎么关声音
  • eclipse怎么更改工作空间或目录?
  • 腾讯会议声音怎么关
  • 斯隆与马克贝尔的迷之物语第四幕隐藏关键词攻略
  • VS2010下VC++实现新窗体的显示
  • 热门搜索
    什么聊天软件好 怏怏不乐的意思 沮丧的意思 什么是二套房 荆芥的作用与功效 眉清目秀的意思 截然不同的意思 雅思是什么意思 测脸型适合什么发型 大蒜的作用