居中布局
水平居中
要求:两个容器嵌套,且宽度不一定,满足小容器在大容器的水平居中位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试专用</title>
<style type="text/css">
.parent{background-color: gray;width: 100%; height: 100px;}
.child{background-color:orange; height:100%;}
</style>
</head>
<body>
<div class="parent">
<div class="child">子容器</div>
</div>
</body>
</html>
解决方案1:inline-block + text-align
原理:将子容器设置为inline-block之后,宽度由内容决定;父容器的text-align就可以生效
.parent{text-align: center;}
.child{display: inline-block;}
- 优点:兼容性好,我们可以在ie6/7,可以通过
display:inline;zoom:1;
兼容 - 缺点:子容器中的内容会继承到居中属性,那么就需要在子容器中额外进行设置
解决方案2:table + margin
原理:display:table;后,容器的宽度也是由内容决定;margin:auto;可以居中;
.child{display:table;margin:auto;}
优点:只对子容器进行设置,在ie8+支持,兼容更低版本直接用
替换掉解决方案3:absolute + transform
.parent{position: relative;}
.child{position: absolute;left: 50%;transform: translateX(-50%);}
- 优点:脱离文档流,对其他元素不影响
- 缺点:不兼容ie低版本
解决方案4:flex + justify—content
原理:当设置父元素是flex,子元素就变成了flex-item,宽度由内容决定;在flex模式下justify—content:center;
可以居中。
.parent{display:flex;justify—content:center;}
- 优点:只对父元素进行设置,并且,如果设置justify—content,也可以对子元素设置margin
- 缺点:ie低版本不兼容