Skip to content

Instantly share code, notes, and snippets.

@zikkeung
Created August 26, 2013 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zikkeung/6338424 to your computer and use it in GitHub Desktop.
Save zikkeung/6338424 to your computer and use it in GitHub Desktop.
CSS 居中大全
<center>
不建议用了。
text-align:center
在父容器里水平居中 inline 文字,或 inline 元素
vertical-align:middle
垂直居中 inline 文字,inline 元素,配合 display:table ,display:table-cell,有奇效。
line-height
与 height 联手,垂直居中文字
margin:auto
translate(-50%,-50%)
用 position 加 translate translate(-50%,-50%) 比较奇特,百分比计算不是以父元素为基准,而是以自己为基准。
参考文章:居中百分比宽高的元素 http://jinlong.github.io/blog/2013/07/08/centering-percentage-widthheight-elements/
用于没固定大小的内容,min-width,max-height,overflow:scroll 等。
绝对定位居中
注意:高度必须定义,建议加 overflow: auto,防止内容溢出。
视口居中
.Absolute-Center.is-Fixed {
width: 50%;
height: 50%;
overflow: auto;
margin: auto;
position: fixed;
top: 0; left: 0; bottom: 0; right: 0;
z-index: 999;
}
响应式
百分比宽高,最大、最小宽度均可以,加 padding 也可以
.Absolute-Center.is-Responsive {
width: 60%;
height: 60%;
min-width: 400px;
max-width: 500px;
padding: 40px;
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
偏移
只要 margin: auto; 在,内容块将垂直居中,top, left, bottom, right 可以设置偏移。
.Absolute-Center.is-Right {
width: 50%;
height: 50%;
margin: auto;
overflow: auto;
position: absolute;
top: 0; left: auto; bottom: 0; right: 20px;
text-align: right;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment