CSS中使用inline-block来进行居中的示例


迫切需要的方法:inline-block法居中。基本方法是使用 display: inline-block, vertical-align: middle样式和伪元素让内容块在容器中居中。我的实现用到了几个在其他地方见不到的新技巧解决了一些问题。

  内容区声明的宽度不能大于容器的100% 减去0.25em的宽度。就像一段带有长文本的区域。不然,内容区域会被推到顶端,这就是使用:after伪类的原因。使用:before伪类则会让元素有100%的大小!

如果内容块需要尽可能大地占用水平空间,可以为大容器加上max-width: 99%;样式,或者考虑浏览器和容器宽度的情况下使用max-width: calc(100% – 0.25em) 样式。

  这种方法和table-cell的大多数好处相同,不过最初我放弃了这个方法,因为它更像是hack。不管这一点的话,浏览器支持很不错,而且也被证实是很流行的方法。

  HTML:
 

XML/HTML Code复制内容到剪贴板
  1. <div class="Center-Container is-Inline">  
  2.   <div class="Center-Block">  
  3.     <!-- CONTENT -->  
  4.   </div>  
  5. </div>  

  CSS:
 

CSS Code复制内容到剪贴板
  1. .Center-Container.is-Inline {    
  2.   text-aligncenter;   
  3.   overflow: <span style="width: auto; height: auto; float: none;" id="7_nwp"><a style="text-decoration: none;" mpid="7" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=2d6719abf210fdd5&k=auto&k0=auto&kdi0=0&luki=9&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=d5fd10f2ab19672d&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F3058%2Ehtml&urlid=0" id="7_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">auto</span></a></span>;   
  4. }   
  5.     
  6. .Center-Container.is-Inline:after,   
  7. .is-Inline .Center-Block {   
  8.   displayinline-<span style="width: auto; height: auto; float: none;" id="8_nwp"><a style="text-decoration: none;" mpid="8" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=2d6719abf210fdd5&k=block&k0=block&kdi0=0&luki=7&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=d5fd10f2ab19672d&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F3058%2Ehtml&urlid=0" id="8_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">block</span></a></span>;   
  9.   vertical-alignmiddle;   
  10. }   
  11.     
  12. .Center-Container.is-Inline:after {   
  13.   content'';   
  14.   height: 100%;   
  15.   margin-left: -0.25em; /* To offset spacing. May vary by font */  
  16. }   
  17.     
  18. .is-Inline .Center-Block {   
  19.   max-width: 99%; /* Prevents issues with long content causes the content block to be pushed to the top */  
  20.   /* max-width: calc(100% - 0.25em) /* Only for IE9+ */  
  21. }  

  好处:

    内容高度可变
    内容溢出则能自动撑开父元素高度
    浏览器兼容性好,甚至可以调整支持IE7

  同时注意:

    需要额外容器
    依赖于margin-left: -0.25em的样式,做到水平居中,需要为不同的字体大小作调整
    内容区声明的宽度不能大于容器的100% 减去0.25em的宽度


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3