在網頁制作中,有很多種水準、垂直居中方法,本文就歸納如下幾種:
水準居中
1.
不建議用了。
2. text-align:center 在父容器裡水準居中 inline 文字,或 inline 元素
3.margin:0 auto;
4.用 position 加 translate translate(-50%,-50%) 比較奇特,百分比計算不是以父元素為基準,而是以自己為基準。
Hello World
樣式
#ex3_container{
width:200px;
height:200px;
background-color:yellow;
position:relative;
}
#ex3_content{
left:50%; top:50%;
transform:translate(-50%,-50%);
-webkit-transform:translate(-50%,-50%);
background-color:gray; color:white; position:absolute;
這個技巧相當嚣張,适用于沒固定大小的内容,min-width,max-height,overflow:scroll等。
5.絕對定位居中
父容器元素:position: relative
.Absolute-Center {
width: 50%;
height: 50%;
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
注意:高度必須定義,建議加 overflow: auto,防止内容溢出。
6.視口居中
内容元素:position: fixed,z-index: 999,記住父容器元素 position: relative
.Absolute-Center.is-Fixed {
position: fixed;
z-index: 999;
垂直居中
Content goes here
.wrapper{display:table;}
cell{display:table;
vertical-align:middle;
2.這個方法使用絕對定位div,把它的top設定為50%,top margin 設定為負的content高度,這意味着對象必須在css種指定用
域名轉讓固定的高度
因為有固定高度,或許你想給content指定overflow:auto,這樣如果content太多的話,就會出現滾動條,以免content溢出
content goes here
.content {
position:absolute;
top:50%;height:240px;
margin-top:-120px;/ negative half of the height /
3.content元素外插入一個div
content here
.floater{
float:left;
height:50%;
margin-bottom:-120px;
.content{
clear:both;
height:240px;
4.會計元素垂直居中是很簡單的
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
widthZ:70%;
5.line-height
height:100px;
line-height:100px;