簡體   English   中英

如何垂直對齊 div 中的元素?

[英]How can I vertically align elements in a div?

我有一個帶有兩個圖像和一個h1div 所有這些都需要在 div 內垂直對齊,彼此相鄰。 其中一張圖像需要absolute定位在div內。

在所有常見瀏覽器上運行所需的 CSS 是什么?

<div id="header">
  <img src=".." ></img>
  <h1>testing...</h1>
  <img src="..."></img>
</div>

哇,這個問題很流行。 它是基於對vertical-align屬性的誤解。 這篇優秀的文章解釋了它:

理解vertical-align或 Gavin Kistner 的“如何(不)垂直居中內容”

“如何在 CSS 中居中”是一個很棒的網絡工具,可以幫助找到不同情況下必要的 CSS 居中屬性。


簡而言之(並防止鏈接腐爛)

  • 內聯元素(並且只有內聯元素)可以通過vertical-align: middle在其上下文中垂直對齊。 但是,“上下文”不是整個父容器的高度,而是它們所在的文本行的高度。jsfiddle 示例
  • 對於塊元素,垂直對齊更難,很大程度上取決於具體情況:
    • 如果內部元素可以有一個固定的高度,你可以將它的位置absolute並指定它的heightmargin-toptop位置。 jsfiddle 示例
    • 如果居中元素由單行組成並且其父高度是固定的,您可以簡單地設置容器的line-height來填充其高度。 根據我的經驗,這種方法非常通用。 jsfiddle 示例
    • ……還有更多這樣的特殊情況。

現在對 Flexbox 的支持正在增加,這個應用於包含元素的 CSS 將垂直居中所有包含的項目(除了那些自己指定對齊方式的項目,例如align-self:start

.container {
    display: flex;
    align-items: center;
}

如果您還需要針對Internet Explorer 10和更早的 (< 4.4 (KitKat)) Android 瀏覽器,請使用前綴版本:

.container {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
}

我使用了這個非常簡單的代碼:

 div.ext-box { display: table; width:100%;} div.int-box { display: table-cell; vertical-align: middle; }
 <div class="ext-box"> <div class="int-box"> <h2>Some txt</h2> <p>bla bla bla</p> </div> </div>

顯然,無論您使用.class還是#id ,結果都不會改變。

 .outer {
   display: flex;
   align-items: center; 
   justify-content: center;
 }

它對我有用:

.vcontainer {
    min-height: 10em;
    display: table-cell;
    vertical-align: middle;
}

垂直和水平對齊元素

使用其中任何一個。 結果將是相同的:

  1. 引導程序 4
  2. CSS3

在此處輸入圖像描述

1.引導4.3+

對於垂直對齊: d-flex align-items-center

對於水平對齊: d-flex justify-content-center

對於垂直和水平對齊: d-flex align-items-center justify-content-center

 .container { height: 180px; width:100%; background-color: blueviolet; } .container > div { background-color: white; padding: 1rem; }
 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/> <div class="d-flex align-items-center justify-content-center container"> <div>I am in Center</div> </div>

2.CSS 3

 .container { height: 180px; width:100%; background-color: blueviolet; } .container > div { background-color: white; padding: 1rem; } .center { display: flex; align-items: center; justify-content: center; }
 <div class="container center"> <div>I am in Center</div> </div>

我朋友的一個技巧:

 div:before {content:" "; display:inline-block; height:100%; vertical-align:middle;} div p {display:inline-block;}
 <div style="height:100px; border:1px solid;"> <p style="border:1px dotted;">I'm vertically centered.</p> </div>

演示在這里

要將塊元素定位到中心(適用於Internet Explorer 9及更高版本),它需要一個包裝器div

.vcontainer {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
}

使用這個公式,它會一直工作而不會出現裂縫:

 #outer {height: 400px; overflow: hidden; position: relative;} #outer[id] {display: table; position: static;} #middle {position: absolute; top: 50%;} /* For explorer only*/ #middle[id] {display: table-cell; vertical-align: middle; width: 100%;} #inner {position: relative; top: -50%} /* For explorer only */ /* Optional: #inner[id] {position: static;} */
 <div id="outer"> <div id="middle"> <div id="inner"> any text any height any content, for example generated from DB everything is vertically centered </div> </div> </div>

幾乎所有方法都需要指定高度,但通常我們沒有任何高度。

所以這是一個不需要知道高度的 CSS 3 三行技巧。

.element {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

它甚至在 IE9 中也受支持。

及其供應商前綴:

.element {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

來源: 只需 3 行 CSS 即可垂直對齊任何內容

所有這些都需要在 div 內垂直對齊

怎么對齊? 圖像的頂部與文本的頂部對齊?

其中一張圖像需要絕對定位在 div 內。

相對於 DIV 絕對定位? 也許你可以勾勒出你正在尋找的東西......?

fd 描述了絕對定位的步驟,以及調整H1元素的顯示以使圖像與其內聯顯示。 為此,我將補充一點,您可以使用vertical-align樣式對齊圖像:

#header h1 { display: inline; }
#header img { vertical-align: middle; }

...這會將標題和圖像放在一起,頂部邊緣對齊。 存在其他對齊選項; 請參閱文檔 您可能還會發現刪除 DIV 並將圖像移動到H1元素內是有益的——這為容器提供了語義價值,並且無需調整H1的顯示:

<h1 id=header">
   <img src=".." ></img>
   testing...
   <img src="..."></img>
</h1>

在父 div 中制作中心子 div 的三種方法

  • 絕對定位方式
  • 彈性盒方法
  • 變換/翻譯方法

在此處輸入圖像描述

演示

 /* Absolute Positioning Method */ .parent1 { background: darkcyan; width: 200px; height: 200px; position: relative; } .child1 { background: white; height: 30px; width: 30px; position: absolute; top: 50%; left: 50%; margin: -15px; } /* Flexbox Method */ .parent2 { display: flex; justify-content: center; align-items: center; background: darkcyan; height: 200px; width: 200px; } .child2 { background: white; height: 30px; width: 30px; } /* Transform/Translate Method */ .parent3 { position: relative; height: 200px; width: 200px; background: darkcyan; } .child3 { background: white; height: 30px; width: 30px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
 <div class="parent1"> <div class="child1"></div> </div> <hr /> <div class="parent2"> <div class="child2"></div> </div> <hr /> <div class="parent3"> <div class="child3"></div> </div>

我的訣竅是在 div 中放置一個表格,其中包含一行和一列,設置 100% 的寬度和高度,以及屬性vertical-align:middle

<div>

    <table style="width:100%; height:100%;">
        <tr>
            <td style="vertical-align:middle;">
                BUTTON TEXT
            </td>
        </tr>
    </table>

</div>

小提琴:http: //jsfiddle.net/joan16v/sbq​​jnn9q /

使用 display flex,首先你需要包裝你想要對齊的項目的容器:

<div class="outdiv">
    <div class="indiv">
        <span>test1</span>
        <span>test2</span>
    </div>
</div>

然后在我的示例中應用以下 CSS 內容來包裝divoutdiv

.outdiv {
    display: flex;
    justify-content: center;
    align-items: center;
}

使用 CSS 垂直居中,您可以讓外部容器像表格一樣,而內容像表格單元格一樣。 在這種格式中,您的對象將保持居中。 :)

我以在 JSFiddle 中嵌套多個對象為例,但核心思想是這樣的:

HTML

<div class="circle">
  <div class="content">
    Some text
  </div>
</div>

CSS

.circle {
  /* Act as a table so we can center vertically its child */
  display: table;
  /* Set dimensions */
  height: 200px;
  width: 200px;
  /* Horizontal center text */
  text-align: center;
  /* Create a red circle */
  border-radius: 100%;
  background: red;
}

.content {
  /* Act as a table cell */
  display: table-cell;
  /* And now we can vertically center! */
  vertical-align: middle;
  /* Some basic markup */
  font-size: 30px;
  font-weight: bold;
  color: white;
}

多對象示例:

HTML

<div class="container">
  <div class="content">

    <div class="centerhoriz">

      <div class="circle">
        <div class="content">
          Some text
        </div><!-- content -->
      </div><!-- circle -->

      <div class="square">
        <div class="content">
          <div id="smallcircle"></div>
        </div><!-- content -->
      </div><!-- square -->

    </div><!-- center-horiz -->

  </div><!-- content -->
</div><!-- container -->

CSS

.container {
  display: table;
  height: 500px;
  width: 300px;
  text-align: center;
  background: lightblue;
}

.centerhoriz {
  display: inline-block;
}

.circle {
  display: table;
  height: 200px;
  width: 200px;
  text-align: center;
  background: red;
  border-radius: 100%;
  margin: 10px;
}

.square {
  display: table;
  height: 200px;
  width: 200px;
  text-align: center;
  background: blue;
  margin: 10px;
}

.content {
  display: table-cell;
  vertical-align: middle;
  font-size: 30px;
  font-weight: bold;
  color: white;
}

#smallcircle {
  display: inline-block;
  height: 50px;
  width: 50px;
  background: green;
  border-radius: 100%;
}

結果

結果

https://jsfiddle.net/martjemeyer/ybs032uc/1/

我找到了一種新的解決方法,可以使用 CSS 3 垂直對齊 div 中的多個文本行(我還使用 bootstrap v3 網格系統來美化 UI),如下所示:

.immediate-parent-of-text-containing-div {
    height: 50px;         /* Or any fixed height that suits you. */
}

.text-containing-div {
    display: inline-grid;
    align-items: center;
    text-align: center;
    height: 100%;
}

根據我的理解,包含元素的文本的直接父級必須具有一定的高度。

我們可以使用 CSS 函數計算來計算元素的大小,然后相應地定位子元素。

示例 HTML:

<div class="box">
    <span><a href="#">Some Text</a></span>
</div>

和 CSS:

.box {
    display: block;
    background: #60D3E8;
    position: relative;
    width: 300px;
    height: 200px;
    text-align: center;
}

.box span {
    font: bold 20px/20px 'source code pro', sans-serif;
    position: absolute;
    left: 0;
    right: 0;
    top: calc(50% - 10px);
}

a {
    color: white;
    text-decoration: none;
}

此處創建的演示: https ://jsfiddle.net/xnjq1t22/

此解決方案也適用於響應div heightwidth

注意: calc函數未測試與舊瀏覽器的兼容性。

默認情況下,h1 是一個塊元素,將在第一個 img 之后的行上渲染,並將導致第二個 img 出現在該塊之后的行上。

要阻止這種情況發生,您可以將 h1 設置為具有內聯流行為:

#header > h1 { display: inline; }

至於將 img 絕對定位在 div 內,您需要將包含的 div 設置為“已知大小”,然后才能正常工作。 根據我的經驗,您還需要將 position 屬性從默認值更改 - position: relative 對我有用:

#header { position: relative; width: 20em; height: 20em; }
#img-for-abs-positioning { position: absolute; top: 0; left: 0; }

如果你可以讓它工作,你可能想嘗試從 div.header 逐步刪除高度、寬度、位置屬性,以獲得所需的最少屬性來獲得你想要的效果。

更新:

這是一個適用於 Firefox 3 的完整示例:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>Example of vertical positioning inside a div</title> <style type="text/css"> #header > h1 { display: inline; } #header { border: solid 1px red; position: relative; } #img-for-abs-positioning { position: absolute; bottom: -1em; right: 2em; } </style> </head> <body> <div id="header"> <img src="#" alt="Image 1" width="40" height="40" /> <h1>Header</h1> <img src="#" alt="Image 2" width="40" height="40" id="img-for-abs-positioning" /> </div> </body> </html>

我最喜歡的新方法是使用 CSS 網格:

 /* technique */ .wrapper { display: inline-grid; grid-auto-flow: column; align-items: center; justify-content: center; } /* visual emphasis */ .wrapper { border: 1px solid red; height: 180px; width: 400px; } img { width: 100px; height: 80px; background: #fafafa; } img:nth-child(2) { height: 120px; }
 <div class="wrapper"> <img src="https://source.unsplash.com/random/100x80/?bear"> <img src="https://source.unsplash.com/random/100x120/?lion"> <img src="https://source.unsplash.com/random/100x80/?tiger"> </div>

僅使用 Bootstrap 類:

  • div: class="container d-flex"
  • div 內的元素: class="m-auto"

 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" crossorigin="anonymous"> <div class="container d-flex mt-5" style="height:110px; background-color: #333;"> <h2 class="m-auto"><a href="https://hovermind.com/">H➲VER➾M⇡ND</a></h2> </div>

只需在 div 中使用一個單元格表格! 只需將單元格和表格高度設置為 100%,您就可以使用垂直對齊。

div 內的一個單元格表處理垂直對齊,並且向后兼容回石器時代!

一年多以來,我一直在使用以下解決方案(沒有定位和行高),它也適用於Internet Explorer 7Internet Explorer 8

<style>
.outer {
    font-size: 0;
    width: 400px;
    height: 400px;
    background: orange;
    text-align: center;
    display: inline-block;
}

.outer .emptyDiv {
    height: 100%;
    background: orange;
    visibility: collapse;
}

.outer .inner {
    padding: 10px;
    background: red;
    font: bold 12px Arial;
}

.verticalCenter {
    display: inline-block;
    *display: inline;
    zoom: 1;
    vertical-align: middle;
}
</style>

<div class="outer">
    <div class="emptyDiv verticalCenter"></div>
    <div class="inner verticalCenter">
        <p>Line 1</p>
        <p>Line 2</p>
    </div>
</div>

這是我對div中的i元素的個人解決方案。

JSFiddle 示例

HTML

<div class="circle">
    <i class="fa fa-plus icon">
</i></div>

CSS

.circle {
   border-radius: 50%;
   color: blue;
   background-color: red;
   height:100px;
   width:100px;
   text-align: center;
   line-height: 100px;
}

.icon {
  font-size: 50px;
  vertical-align: middle;
}

對我來說,它是這樣工作的:

<div style="width:70px; height:68px; float:right; display: table-cell; line-height: 68px">
    <a href="javascript:void(0)" style="margin-left: 4px; line-height: 2" class="btn btn-primary">Login</a>
</div>

使用 Bootstrap 類將“a”元素轉換為按鈕,現在它在外部“div”內垂直居中。

只是這個:

<div>
    <table style="width: 100%; height: 100%">
        <tr>
            <td style="width: 100%; height: 100%; vertical-align: middle;">
               What ever you want vertically-aligned
            </td>
        </tr>
    </table>
</div>

div 內的一個單元格表處理垂直對齊,並且向后兼容回石器時代!

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
    <head>
        <style type="text/css">
            #style_center { position:relative; top:50%; left:50%; }
            #style_center_absolute { position:absolute; top:50px; left:50px; }
            <!--#style_center { position:relative; top:50%; left:50%; height:50px; margin-top:-25px; }-->
        </style>
    </head>

    <body>
        <div style="height:200px; width:200px; background:#00FF00">
            <div id="style_center">+</div>
        </div>
    </body>
</html>

這只是另一種(響應式)方法:

html,
    body {
        height: 100%;
    }
    body {
        margin: 0;
    }

    .table {
        display: table;
        width:  auto;
        table-layout:auto;
        height: 100%;
    }
        .table:nth-child(even) {
            background: #a9edc3;
        }
        .table:nth-child(odd) {
            background: #eda9ce;
        }

    .tr {
        display: table-row;
    }
    .td {
        display: table-cell;
        width: 50%;
        vertical-align: middle;
    }

http://jsfiddle.net/herrfischerhamburg/JcVxz/

我是一個剛接觸Web編程的.NET專家。 我沒有使用CSS(好一點)。 我使用了一些JavaScript來完成垂直居中以及jQuery的.css函數。

我只是發布測試中的所有內容。 它可能不會過分優雅,但到目前為止已經可以使用。

script.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

        <script type="application/javascript">
            function centerElementVertically(id) {
                var btnDivHeight = $(id).outerHeight();
                var prnt = $(id).parent();
                var parentHeight = prnt.outerHeight();

                var newTop = ((parentHeight - btnDivHeight) / 2) + 'px';
                var newPct = newTop / parentHeight+'%;';

                $(id).css({top: newTop});
            }

            function showAlert(){
                alert("alert");
            }

            $(window).load(()=>{
                centerElementVertically('#buttonRight');
                centerElementVertically('#buttonLeft');
                centerElementVertically('#testerbtn')
            });

            $(window).resize(()=>{
                centerElementVertically('#buttonRight');
                centerElementVertically('#buttonLeft');
                centerElementVertically('#testerbtn')
            })
        </script>

        <style>
            #div1 {
                position:relative;
                height: 33%;
                background-color: red;
                overflow: hidden;
            }
            #buttonLeft {
                position: relative;
                float:left;
                width:50%;
                height:20%;
                background-color: cornsilk;
            }
            #buttonRight {
                position: relative;
                float:right;
                width:50%;
                height:50%;
                background-color: darkorchid;
            }
            #testerbtn {
                position: absolute;
            }
            body {
                background-color: aqua;
            }
        </style>

        <body>
            <div id="div1">
                <div id="buttonLeft">
                    <button id="testerbtn">tester</button>
                </div>
                <div id="buttonRight"></div>
            </div>
        </body>
    </head>
</html>
<div id="header" style="display: table-cell; vertical-align:middle;">

...

或 CSS

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

瀏覽器覆蓋率

暫無
暫無

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

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