繁体   English   中英

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

[英]How can I vertically and horizontally center a div within a larger div?

如何在另一个<div>中水平居中<div>? 我设法从接受的答案中使用样式水平居中。 我怎样才能将它垂直居中? 内部div的高度未知。

来自: 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>

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

外层容器

  • 应该有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> 

另见这个小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM