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

2026-01-05 14:20:25

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、小编目前发现了这五种方法可以实现,大家可以参考,还有很多种实现方法大家多尝试!

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢