CSS实现完美垂直居中

之前看到很多人一直都问这个问题,不过当时我没当一回事,因为在 CSS
中要垂直居中,多数是在有高度的情况下,或者容器高度不定的情况下才用,看上去比较舒服,而且实现的方法也不少,不一定要拘泥于和 table
布局一样。不过最近有人问了几个例子,看来对此的需求还不少。现在就把我经验拿出来分享一下,希望大家鼓鼓掌。


首先,要有一个概念:凡是 table 布局可以实现的,CSS 一定可以实现。CSS 可以实现的,table 未必能做到。



现在来几个例子:


一、单行内容的居中

只考虑单行是最简单的,无论是否给容器固定高度,只要给容器设置 line-height 和 height,并使两值相等,再加上 over-flow: hidden 就可以了


  1. .middle-demo-1{
  2. height: 4em;
  3. line-height: 4em;
  4. overflow: hidden;
  5. }

优点:

1. 同时支持块级和内联极元素

2. 支持所有浏览器

缺点:

1. 只能显示一行

2. IE中不支持等的居中

要注意的是:

1. 使用相对高度定义你的 height 和 line-height

2. 不想毁了你的布局的话,overflow: hidden 一定要

为什么?

请比较以下两个例子:



  1. style="background: #900; color: #00f; font: bold 12px/24px
    Helvertica,Arial,sans-serif; height:24px; width:370px;">Lorem ipsum
    dolor sit amet, consectetuer adipiscing elit.



  2. Lorem ipsum dolor sit amet, consectetuer adipiscing
    elit.


上一个高度是用的绝对单位px,并且没有隐藏溢出,下一个高度用的单位是相对单位em,并且隐藏了溢出。如果你的浏览器支持放大字体,那么尽情地放大字体,看看会出现什么效果。


二、多行内容居中,且容器高度可变

也很简单,给出一致的 padding-bottom 和 padding-top 就行


  1. .middle-demo-2{
  2. padding-top: 24px;
  3. padding-bottom: 24px;
  4. }

优点:

1. 同时支持块级和内联极元素

2. 支持非文本内容

3. 支持所有浏览器

缺点:

容器不能固定高度


三、把容器当作表格单元

CSS 提供一系列diplay属性值,包括 display: table, display: table-row, display:
table-cell 等,能把元素当作表格单元来显示。这是再加上 vertical-align: middle, 就和表格中的
valign=”center” 一样了。


  1. .middle-demo-3{
  2. display: table-cell;
  3. height: 300px;
  4. vertical-align: middle;
  5. }

可惜IE不支持这些属性,不过在其他浏览器上显示效果非常完美。

要注意的是:和一个合法的元素必须在里一样,display: table-cell 元素必须作为 display: table 的元素的子孙出现。


优点:

不用说了吧,就是表格,效果和表格一模一样

缺点:

IE下无效


四、以毒攻毒!用 IE 的 bug 解决 IE 中的绝对居中

先不得不说一句,IE 真的是个很烂的浏览器,CSS1中的定义都不支持,害得要我们转个大圈子来造居中。不过就像我说的,凡是 table
布局可以实现的,CSS 一定可以实现,即使在 IE 里也不例外。我研究 IE layout 模式多年,还是找出了一个可以在 IE
中绝对居中的方法。这个方法就是基于 IE layout 的
bug,也可以算以毒攻毒。至于原理,不要问我,这是独门秘学,何况三言两语也讲不清楚,只要好用就行


  1. .middle-demo-4{
  2. height: 300px;
  3. position: relative;
  4. }
  5. .middle-demo-4 div{
  6. position: absolute;
  7. top: 50%;
  8. left: 0;
  9. }
  10. .middle-demo-4 div div{
  11. position: relative;
  12. top: -50%;
  13. left: 0;
  14. }

五、整合三和四,写出支持所有浏览器的垂直居中容器!

思路是利用 IE 和 非IE 浏览器的 CSS hack, 整合三和四的CSS,写出兼容主流浏览器的垂直居中容器。具体代码就不给出了,大家权当作练习练习。例子可以在下面的附录中找到。

最终实测支持的浏览器:IE6+, Mozilla 1.7, Netscape Navigator 8, Opera 8.0+, Firefox 1.0+ 和 Safari 1.0+IE5 下需要加上对合适模型的补正。

推测支持的浏览器:Mozilla 1.5+, Netscape Navigator 7+, Opera 7+

未测试浏览器:Konqueror


  1. Demo:: vertical align: middle
  2. html,body,div,h1,h2,pre,dd,ol{margin: 0;padding: 0;border: 0}
  3. html{min-width: 779px}
  4. body{background: #fff;color: #596480;text-align: center}
  5. div#main-wrapper{padding: 12px 5px;width: 769px;margin: 0 auto}
  6. div,code,p,h1,h2,address,dt,dd,li{font: normal 12px/1.5em
    Tahoma,"Lucida Grande",Helvetica,Verdana,Lucida,Arial,"Arial
    Unicode",sans-serif,serif}
  7. h1{font-size: 22px;font-weight: bold;border-left: 12px solid
    #324f96;background: #e0eaf4;color: #4868a9;height: 4em;line-height:
    4em;padding: 0 12px;overflow: hidden; text-align: left}
  8. h2{font-size: 12px;font-weight: bold;background: #c0014e;color:
    #fff;height: 2.5em;line-height: 2.5em;padding: 0 24px;overflow:
    hidden;margin: 12px 0;text-align: left}
  9. h2 a{color: #fff;background: transparent}
  10. h2 a:hover{text-decoration: none}
  11. p{margin: 6px 0;padding: 0 12px 0 24px;text-indent: 2em;text-align: left}
  12. p.snap-back{text-align: right}
  13. code{display: block;font-family: "Courier New", Courier, monospace,
    mono, serif;margin: 12px auto;padding: 12px;border: 1px solid
    #596480;color: inherit;background: #f6f6f6;text-align:
    left;white-space: pre;width: 350px}
  14. strong{font-weight: bold}
  15. em{font-style: italic}
  16. address{display: block;padding: 0 12px;margin: 12px 0;text-align: right}
  17. dl{margin: 6px 0;padding: 0 12px 0 24px;text-align: left}
  18. dt{margin: 0;text-indent: 2em;font-weight: bold}
  19. dd{margin-left: 24px;text-indent: 2em}
  20. li{list-style: square inside none;text-align: left}
  21. ol#table-of-content{padding-left: 24px}
  22. a{color: #c0014e;background: transparent;text-decoration: none}
  23. a:hover{text-decoration: underline}
  24. div.demo{width: 400px;margin: 12px auto;border: 1px solid #596480;color: inherit;background: #ffc}
  25. div.demo p{text-align: left;margin: 24px;text-indent: 0}
  26. p#demo-1{margin: 12px auto;padding: 0 12px;width:
    400px;text-indent: 0;border: 1px solid #596480;color:
    inherit;background: #ffc;line-height: 4em;height: 4em;overflow: hidden}
  27. div#demo-2{padding: 50px 0}
  28. div#demo-4, div#demo-5{height: 300px;position: relative}
  29. div#demo-4 div, div#demo-5 div{position: absolute;top: 50%;left: 0}
  30. div#demo-4 p, div#demo-5 p{position: relative;top: -50%}
  31. div#demo-3{display: table;height: 300px;border-collapse: collapse}
  32. div#main-wrapper>div#demo-5{position: static;display:table}
  33. div#main-wrapper>div#demo-5>div{display:table-cell;vertical-align:middle;position:static}
  34. div#demo-3>div{display: table-row}
  35. div#demo-3>div>div{display: table-cell;vertical-align: middle}
  36. span.property{font-family: "Courier New", Courier, monospace, mono,
    serif;border-bottom: 1px dotted #596480;background: #ffc;color: #c0014e}
  37. p.copyright{line-height: 3em;text-align: center;border-top: 1px dotted #596480}
  38. Demo of middled vertical align

  39. Author: Spenser Lee, Liberty Studio
  40. Originally posted on BlueIdea Forum
  41. Table of centents:

    1. Single line countainer with/without a
      fixed height
    2. Align multi-line container which
      does not have a fixed height
    3. Simulating table layout in container
      with a fixed height
    4. IE's solution
    5. A perfect compounded sample
  42. Case One: Single line countainer with/without a fixed height

  43. If you only want to display a container which only holds a
    single line of text, you can set
    class="property">line-height property to
    class="property">height property, then set
    class="property">overflow to hidden.

  44. Sample:

  45. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

  46. Core code:

  47. .middle-demo-1{
  48. height: 4em;
  49. line-height: 4em;
  50. overflow: hidden;
  51. }
  52. Notes:
    1. I strongly recommend you use relative size in
      height and
      class="property">line-height property.
      Why? You can simply set the font size larger if
      your browser support it. When it gets large enough, you will see the
      countainer is stretched and the
      class="property">height is no longer equal to
      class="property">line-height property, thus, the layout
      is messed up. Using relative size as em,
      ex
      or % will let
      your countainer stretch with the content.
    2. overflow:
      hidden
      is a must. Why? Same as above.
      Just ensure height and
      line-height are always
      equal.
  53. Pros:
    1. Fits in both
      class="property">block elements and
      class="property">inline elements.
    2. Capable of all 5th-gen browsers.
  54. Cons:
    1. Text length is limited. Max with only one line.
    2. Does not work well on none text contents such as images and objects.
  55. Back

  56. Case Two: Align multi-line container which does not have a fixed height

  57. In this case, we should simply set a pair of fixed
    equivalences to padding-top and padding-bottom attribute. It works on
    both IE and non-IE browsers.

  58. Sample:

  59. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    Maecenas dignissim diam eu sem. Proin nunc ante, accumsan sollicitudin,
    sodales at, semper sed, ipsum. Etiam orci. Vestibulum magna lectus,
    venenatis nec, tempus ac, dictum vel, lorem.

Core code:

.middle-demo-2{
padding-top: 24px;padding-bottom: 24px;}Pros:
  1. Fits in both
    class="property">block elements and
    class="property">inline elements.
  2. Works on none text contents as fine as text contents.
  3. Capable of all 5th-gen browsers. Might need a little tune-up for the box model bug of IE5 though.
Cons:
  1. You can not assign height in this solution.

Back

Case Three: Simulating table layout in container with a fixed height

CSS offers a set of very convenient display atrribute
values called display: table,
display: table-row,
class="property">display: table-cell and other display
values begin with table-. It
offers a way to simulate table layout in all elements. As a result, any
element with display:
table-cell
, vertical-align:
middle
and a fixed height will display exactly like a
table cell.

Sample: (You may not be able to view the effect on IE)

Lorem ipsum dolor sit amet,
consectetuer adipiscing elit. Maecenas dignissim diam eu sem. Proin
nunc ante, accumsan sollicitudin, sodales at, semper sed, ipsum. Etiam
orci. Vestibulum magna lectus, venenatis nec, tempus ac, dictum vel,
lorem.

Core code:

.middle-demo-3{
display: table-cell;height: 300px;vertical-align: middle;}Notes:
  1. display:
    table-cell
    must work with other elements with
    class="property">display: table value sets in order to
    form a literal table. Or it might cause unexceptable bugs.
  2. Sadly IE series (including the latest IE 7 beta)
    does not support any of display:
    table
    values, so it won't work in IE.
Pros:
  1. It has the most perfect render for
    class="property">vertical-align: middle
    align.
Cons:
  1. It only works in latest versions of non-IE
    browsers, such as Mozilla, Firefox, Netscape 8, Opera 8, and
    Safari.

Back

Case Four: IE's solution

Since IE is a lame browser when it comes to ANYTHING, so
you can't use the solution above simply because IE does not recognize
it at all. However, there has been nothing yet you can
not code with CSS if you have already coded it with
table
. It even offers you possibility to layout your
page that tables can not do!

So what's the solution for IE? Like what we always do: Hit IE's back with the BUGS it offers!

Sample: (You are able to view the correct result only on IE)

Lorem ipsum dolor sit amet, consectetuer
adipiscing elit. Maecenas dignissim diam eu sem. Proin nunc ante,
accumsan sollicitudin, sodales at, semper sed, ipsum. Etiam orci.
Vestibulum magna lectus, venenatis nec, tempus ac, dictum vel,
lorem.

.middle-demo-4{
height: 300px;position: relative;}.middle-demo-4 div{position: absolute;top: 50%;left: 0;}.middle-demo-4 div div{position: relative;top: -50%;left: 0;}

See? Don't ask me why it worked. This hack is based on
years of study in IE's own stupid layout model and it works very well,
even in IE5 given the box width hack. I won't tell you the theory
behind all these. It's my top secret, with which I solved a lot of
other cross browser layout problems, and I'm not going to share it with
you. But you are free to use this IE hack It's kinda handful in most
occassions.

Pros:
  1. The only perfect vertical align method in IE. It
    works even better then add automatic
    class="property">paddings.
Cons:
  1. After all it's a CSS hack. We can avoid it if not for IE.

Back

Case Five: A perfect compounded sample

Here's the perfect compounded solution on vertical centering that works on almost all latest browsers.

Sample: (This works on almost all browsers)

Lorem ipsum dolor sit amet, consectetuer
adipiscing elit. Maecenas dignissim diam eu sem. Proin nunc ante,
accumsan sollicitudin, sodales at, semper sed, ipsum. Etiam orci.
Vestibulum magna lectus, venenatis nec, tempus ac, dictum vel,
lorem.

I'm not going to give you the full code of this one. But
it's not difficult to write it yourself, with the solution of case 3
and 4, and a little knowledge in IE/non-IE CSS hackers. And actually
the hacking style is not limited, so I don't want to force you to use
my hacking style neither. Stop being lazy, and write the code
yourself!

Browser capability:
  1. Works on: IE6+, Mozilla 1.5+, Netscape Navigator 7+, Opera 7+, Firefox 1.0+ and Safari 1.0+
  2. On IE5, you might need to apply the box model hacker to make the height correct.
  3. Untested: WebOmini, Konqueror.
  4. Fails on: Other browsers not reffered in the list above.

Back

转载于:https://www.cnblogs.com/hacker84/archive/2008/03/21/1116518.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值