发新话题
打印

CSS 居中大全(一)

CSS 居中大全(一)

我看最近微博流行 CSS 居中技术,老外码农争相写相关的文章,一篇赛一篇的长啊,我把几篇归纳总结了一下,算是笔记。
孔乙己曾说:“茴香豆的回字有四种写法”,万一哪天有个面试官问你:“居中一共有几种写法”呢,哈哈,先备着吧~~
各种方法各有利弊,大家自己权衡吧,至少在需要居中时多个思路。
<center>
不建议用了。
text-align:center
在父容器里水平居中 inline 文字,或 inline 元素
vertical-align:middle
垂直居中 inline 文字,inline 元素,配合 display:table ,display:table-cell,有奇效。
line-height
与 height 联手,垂直居中文字
margin:auto
<style>
  #ex2_container { width:200px; background-color:yellow; }
  #ex2_content { margin:0px auto; background-color:gray; color:white; display:table; }
</style>
<div id="ex2_container"><div id="ex2_content">Hello World</div></div>
hacks, hacks(小技巧)
有许多 hacks ,负 margin,影子元素 ::before 等。如果你的内容不是固定大小的话,它们大部分是很脆弱的。
translate(-50%,-50%)
用 position 加 translate translate(-50%,-50%) 比较奇特,百分比计算不是以父元素为基准,而是以自己为基准。
示例:
<style>
#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;
}
</style>
<div id="ex3_container"><div id="ex3_content">Hello World</div></div>
这个技巧相当嚣张,同样适用于没固定大小的内容,min-width,max-height,overflow:scroll等。

绝对定位居中
父容器元素:position: relative
.Absolute-Center {
  width: 50%;
  height: 50%;
  overflow: auto;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}
注意:高度必须定义,建议加 overflow: auto,防止内容溢出。

视口居中
内容元素:position: fixed,z-index: 999,记住父容器元素 position: relative
.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;
}
以上资料由http://www.pingzhujiqiao.net/提供,转载请注明
http://www.pingzhujiqiao.net/
http://www.pingzhu.net/

TOP

发新话题