2012-09-29 319 views
0

在以下文档中,是否可以水平居中内部div,或以其他方式使文本V和H都以outer class div为中心?垂直和水平居中文本

一些限制(抱歉在开始时没有指定): 1.不应指定固定宽度,因为否则解决方案是微不足道的; 2.没有JavaScript,只是纯粹的CSS和HTML。

<!DOCTYPE html> 
<html> 
    <head> 
    <title>the title</title> 
    <style> 

     div.outer { 
      /* ? */ 
     } 

     div.inner { 
      display: table-cell; 
      min-height: 100px; 
      vertical-align: middle; 
     } 

    </style> 
    </head> 
    <body> 
    <div class="outer"> 
     <div class="inner"> 
      <p>Vertically centered text. How to center it horizontally?</p> 
     </div> 
    <div> 
    </body> 
</html> 

回答

3

试试这个:

.outer { 
    display: table; 
    width: 100%; 
} 
.inner { 
    display: table-cell; 
    text-align: center; 
    vertical-align: middle; 
} 

demo

它不使用JavaScript和它不需要你修复width/height/line-height

+0

似乎它的工作完美!非常感谢! –

0

看看this教程。您需要将line-heightwidth 添加到您的CSS以使其工作。

1

如果是单个文本行,你可以使用:

div.inner { 
    line-height: 100px; 
} 

多行是棘手的,因为浏览器支持的用武之地。虽然我发现使用jQuery来检测div.outer的大小&,然后创建pad是最可靠的方法。

$(document).ready(function() { 
    var whitespace = $("div.outer").innerHeight() - $("div.inner").innerHeight(); 
    var padding = Math.round(whitespace/2); 
    $("div.inner").css({ 
    "padding-top": padding + "px"; 
    }); 
}); 
+0

感谢行高选项,它在一行文本情况下当然是有用的。 –

0

在搜索了几个小时后,我终于找到了一个解决方案,用于在另一个div的水平和垂直方向上集中div。

 div.parent { 
      display: block; 
      text-align: center; 
      line-height: 300px; /* the height of parent div */ 
     } 
     div.child { 
      display: inline-block; 
      vertical-align: middle; 
     } 
  • 它不使用绝对定位,所以你不需要FIX儿童宽度/高度。
  • 它不使用display:table/tablecell,这在某些版本的IE中不受支持。
  • 这是一个纯粹的CSS解决方案,即使动态加载子div,也无需编写javascript。

希望这可以帮助为此受苦的人。