多语言展示
当前在线:1522今日阅读:142今日分享:25

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

在网站开发过程中,经常会碰到这样的需求,例如:DIV盒子等等模块设置成左右上下居中,可见掌握这一技能是非常有必要的!那么如何操作呢?接着往下看↓↓↓
工具/原料
1

网站开发工具

2

浏览器

实现方法
1

方法一:绝对定位,确认宽高设置margin属性为宽高的负一半代码:width: 200px; height: 100px; background-color: crimson; position: absolute; left: 50%; top: 50%; margin-left: -100px; margin-top: -50px;

2

方法二:绝对定位:不确定宽高,使用transform: translate属性代码:width: 200px; height: 100px; background-color: crimson; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);

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;

4

方法四:在父层设置flex布局属性(高度根据自己需求设定)代码:父层:width: 100%; height: 200px; display: flex; justify-content: center; align-items: center;子层:width: 200px; height: 100px; background-color: crimson;

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;

6

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

注意事项

开发工具根据个人喜好!建议使用最新浏览器

推荐信息