如何在较大的div内垂直和水平居中div?

时间:2010-08-15 23:58:45

标签: html css

How to horizontally center a <div> in another <div>?我设法从接受的答案中使用样式水平居中。我怎样才能将它垂直居中?内部div的高度未知。

2 个答案:

答案 0 :(得分:7)

来自:http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
  <title>Universal vertical center with CSS</title>
  <style>
    .greenBorder {border: 1px solid green;} /* just borders to see it */
  </style>
</head>

<body>
  <div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;">
    <div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
      <div class="greenBorder" style=" #position: relative; #top: -50%">
        any text<br>
        any height<br>
        any content, for example generated from DB<br>
        everything is vertically centered
      </div>
    </div>
  </div>
</body>
</html>

答案 1 :(得分:0)

这是一种很酷的技术,可以垂直和水平对齐盒子:

外部容器

  • 应该有display: table;

内部容器

  • 应该有display: table-cell;
  • 应该有vertical-align: middle;
  • 应该有text-align: center;

内容框

  • 应该有display: inline-block;
  • 应重新调整水平文本对齐方式,例如。 text-align: left;text-align: right;,除非您希望文字居中

这项技术的优雅之处在于您可以将内容添加到内容框中,而无需担心其高度或宽度!

只需将您的内容添加到内容框中即可。

演示

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        <p>You can put anything here</p>
        <p>Yes, really anything!</p>
     </div>
   </div>
</div>

另见this Fiddle