首页 > 代码库 > 多种方式垂直水平居中
多种方式垂直水平居中
1. 不需要知道父容器和子容器的具体尺寸
(1)方法一:margin
<div class="wrapper"> <div class="content"></div> </div>
.wrapper { display: table-cell; width: 500px; height: 500px; text-align: center; /*水平居中*/ border: 1px solid #eee; vertical-align: middle; /*图片垂直居中*/ position: relative; } .content { width: 200px; height: 200px; background-color: red; margin: auto;}
(2)方法二:绝对定位 + transform, 应用到了css3知识,需要注意兼容性问题
<div class="wrapper"> <div class="content"></div> </div>
.wrapper { display: table-cell; width: 500px; height: 500px; text-align: center; /*水平居中*/ border: 1px solid #eee; vertical-align: middle; /*图片垂直居中*/ position: relative; } .content { width: 200px; height: 200px; background-color: red; position: absolute; left: 50%; right: 50%; transform: translate(-50%, -50%);}
(3)flex弹性盒子,应用到了css3知识,需要注意兼容性问题
<div class="wrapper"> <div class="content"></div> </div>
.wrapper { width: 500px; height: 500px; border: 1px solid #eee; display:flex; justify-content:center; align-items: center; } .content { width: 200px; height: 200px; background-color: red;}
2.已知宽高尺寸
<div class="wrapper"> <div class="content"></div> </div>
.wrapper { width: 500px; height: 500px; border: 1px solid #eee; position: relative;} .content { width: 200px; height: 200px; background-color: red; position: absolute; left: 50%; top: 50%; /*自身宽高一半的负值*/ margin-left: -100px; margin-top: -100px;}
多种方式垂直水平居中
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。