web居中佈局-水平居中
阿新 • • 發佈:2018-12-30
居中佈局
水平居中
要求:兩個容器巢狀,且寬度不一定,滿足小容器在大容器的水平居中位置
<!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低版本不相容