简体   繁体   English

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

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

How to horizontally center a <div> in another <div>? 如何在另一个<div>中水平居中<div>? I managed to center horizontally using styling from the accepted answer. 我设法从接受的答案中使用样式水平居中。 How can I also center it vertically? 我怎样才能将它垂直居中? The inner div is of an unknown height. 内部div的高度未知。

From: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html 来自: 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>

Here's a cool technique for centering a box both vertically and horizontally : 这是一种很酷的技术,可以垂直和水平对齐盒子:

The outher container 外层容器

  • should have display: table; 应该有display: table;

The inner container 内部容器

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

The content box 内容框

  • should have display: inline-block; 应该有display: inline-block;
  • should re-adjust the horizontal text-alignment to eg. 应该重新调整水平文本对齐,例如。 text-align: left; or text-align: right; text-align: right; , unless you want text to be centered ,除非您希望文本居中

The elegance of this technique, is that you can add your content to the content box without worrying about its height or width! 这种技术的优雅之处在于, 您可以将内容添加到内容框中,而无需担心其高度或宽度!

Just add your content to the content box. 只需将您的内容添加到内容框即可。

Demo 演示

 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> 

See also this Fiddle ! 另见这个小提琴

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

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