標籤:style http color io os 使用 ar for sp
上次面試面試官問到了,問了個定寬局中和不定寬局中,下來我把所有有關CSS置中都總結了一下
原文摘自我的前端部落格,歡迎大家來訪問
http://www.hacke2.cn水平置中行內元素
把行內元素嵌套在一個DIV中,並且在DIV中設定以下樣式
a{text-align: center;}
區塊層級元素
對於定寬的區塊層級元素,我們要設定起margin-top,margin-right 為auto
.center{margin: 0 auto;}
多個區塊層級元素(inline-block)
多個區塊層級元素,我們將其display設定為inline-block;然後將父級元素設定一下屬性
div{text-align: center;}
多個區塊層級元素(flex)
設定需要水平置中的塊狀元素的父元素display為flex ,並且justify-content屬性為center即可
body{ display: flex; justify-content: center;}
垂直置中單行 行內元素
將行內元素的height和line-height設定為一致即可
a{ height: 200px; line-height:200px; }
多行 行內元素
如果行內元素文字過多產生多行,則在父級元素設定display: table-cell;vertical-align:middle;
.container{width: 300px;height: 300px;display: table-cell;vertical-align:middle;}
已知高度的區塊層級元素
將區塊層級元素設定絕對位置,top為50%,margin-top:-height/2
div{ height: 100px; position: absolute; top: 50%; margin-top: -50px; padding:0; }
未知高度的區塊層級元素
使用CSS translate,將區塊層級元素設定絕對位置,top為50%,transform: translateY(-50%);
div{ position: absolute; top: 50%; transform: translateY(-50%); padding:0; }
水平垂直置中已知高度、寬度的元素
將區塊層級元素設定絕對位置,top為50%,left:50%;margin-top:-height/2;margin-left:-width/2
div{width: 150px;height: 150px;position: absolute;top: 50%;left: 50%;margin-top: -75px;margin-left: -75px;}
已知高度、寬度的元素(flex)
給父級使用flex布局
div{display: flex;justify-content:center;align-items: center;}
未知高度、寬度的元素
使用CSS translate
div{ position:absolute;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);-moz-transform:translate(-50%,-50%);transform:translate(-50%,-50%);}
CSS置中完全解決方案