簡體   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