簡體   English   中英

將“div”垂直居中在 % 高度“div”中

[英]Center a 'div' vertically in a % height 'div'

是否可以將div垂直居中 % 高度div

這已經在這里以及整個互聯網上被問到了足夠多的時間。

快速搜索將為您帶來大量結果。 無論如何,我的首選方法是使用display: table-cell; vertical-align: middle; . 有關示例,請參閱此頁面 (請注意,這不適用於Internet Explorer 6 。)

如果您的內部div具有絕對高度(假設為 100 像素),您可以這樣做:

.outerdiv{
  position: relative; // Or absolute, or fixed
  height: 80%;
}

.innerdiv{
  position: absolute;
  width: 100px;
  height: 100px;
  top: 50%;  // It's at 50%, but not really centered
  margin-top: -50px; // So just move it up by the half of its height :D
}

我不太喜歡這個解決方案,我相信還有很多其他的可能性(也許使用表格或display: table-cell; ) - 但這是我想到的第一個......

.outerdiv {
  display: table-cell;
  vertical-align: middle;
}

警告 - 它不適用於所有瀏覽器!

不需要 px 單位。

更改topbottomrightleft或使用百分比:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Insert title here</title>
    </head>

    <body>
        <div style="position: absolute;
                    top: 0;
                    bottom: 0;
                    right: 0;
                    left: 0;
                    text-align: center;
                    white-space: nowrap;
                    overflow: hidden;">
            <div style="position: relative;
                        display: inline-block;
                        height: 100%;
                        vertical-align: middle;"></div>
            <div style="background-color: #FEEF88;
                        position: relative;
                        display: inline-block;
                        vertical-align: middle;">Hola todo el mundo :D</div>
        </div>
    </body>
</html>

我更喜歡使用以下技術,它涉及兩個容器:

外容器:

  • 應該有display: table;

內膽:

  • 應該有display: table-cell;
  • 應該有vertical-align: middle;

內容框:

  • 應該有display: inline-block;

您可以將任何您想要的內容添加到內容框中,而無需關心其寬度或高度!

此外,您可以通過添加text-align: center;輕松添加水平居中text-align: center; 到您的內部容器。

演示:

 body { margin : 0; } .outer-container { position : absolute; display: table; width: 100%; height: 100%; background: #ccc; } .inner-container { display: table-cell; vertical-align: middle; } .centered-content { display: inline-block; background: #fff; padding : 20px; border : 1px solid #000; }
 <div class="outer-container"> <div class="inner-container"> <div class="centered-content"> Malcolm in the Middle </div> </div> </div>

另見這個小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM