如何在一个较大的div中使一个小div水平垂直居中?

3

JavaScript 是一个选项吗? - mhitza
2个回答

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>

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>

请参见这个Fiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接