头闻号

广州市白云区三元里伊彩琳化妆品商行

面膜|护肤膏霜|化妆品包装|美容材料及用具|综合性公司

首页 > 新闻中心 > 科技常识:绝对定位元素的水平垂直居中的方法(3种任选)
科技常识:绝对定位元素的水平垂直居中的方法(3种任选)
发布时间:2023-02-01 10:10:06        浏览次数:3        返回列表

今天小编跟大家讲解下有关绝对定位元素的水平垂直居中的方法(3种任选) ,相信小伙伴们对这个话题应该有所关注吧,小编也收集到了有关绝对定位元素的水平垂直居中的方法(3种任选) 的相关资料,希望小伙伴们看了有所帮助。

1.css实现居中

缺点:需要提前知道元素的宽度和高度。

<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>document</title> <style> .box{ width: 600px; height: 400px; position: absolute; left: 50%; top: 50%; border:1px solid #000; background:red; margin-top: -200px; margin-left: -300px; } </style></head><body> <div class="box"> </div></body></html>

2、css3实现水平垂直居中

注意:无论元素的尺寸是多少 都可以居中。不过IE8以上才兼容这种写法 移动端可忽略。

<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>document</title> <style> .box{ width: 600px; height: 400px; position: absolute; left: 50%; top: 50%; border:1px solid #000; background:red; transform: translate(-50%, -50%); } </style></head><body> <div class="box"> </div></body></html>

3、margin:auto实现居中

<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>document</title> <style> .box{ width: 600px; height: 400px; position: absolute; left: 0; top: 0; right: 0; bottom: 0; border:1px solid #000; background:red; margin: auto; } </style></head><body> <div class="box"> </div></body></html>

以上就是本文的全部内容 希望本文的内容对大家的学习或者工作能带来一定的帮助 同时也希望多多支持爱蒂网!

来源:爱蒂网