【问题标题】:How can I vertically align elements in a div?如何垂直对齐 div 中的元素?
【发布时间】:2010-09-09 22:00:59
【问题描述】:

我有一个div,有两张图片和一个h1。它们都需要在 div 内垂直对齐,彼此相邻。

其中一张图片需要位于 div 内。

在所有常见浏览器上都需要什么 CSS?

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

【问题讨论】:

  • 我列出了所有垂直对齐方式。我将把它留在这里:jsfiddle.net/techsin/FAwku/1
  • 这里有两种简单的方法可以让一个 div 中的元素居中,垂直居中,水平居中或两者兼而有之(纯 CSS):stackoverflow.com/a/31977476/3597276
  • margin-top: auto 和 margin-bottom: auto (适用于很多情况)。

标签: html css vertical-alignment


【解决方案1】:

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

  • 绝对定位方式
  • 弹性盒方法
  • 转换/翻译方法

Demo

/* 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>

【讨论】:

    【解决方案2】:

    仅使用 Bootstrap 类:

    • 分区: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>

    【讨论】:

      【解决方案3】:

      使用display flex,首先你需要包裹你想要对齐的item的容器:

      <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;
      }
      

      【讨论】:

      • 不鼓励仅使用代码的答案。请添加一些解释,说明这如何解决问题,或者这与现有答案有何不同。 From Review
      【解决方案4】:

      垂直和水平对齐元素

      使用其中任何一个。结果是一样的:

      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>

      【讨论】:

      • 两种方式基本相同,因为 Bootstrap 在其类中使用相同的 flex 属性。
      • 引导程序并不神奇。它受到影响每个人的相同 CSS 限制。它只是隐藏了它对平均值的作用。用户。
      【解决方案5】:

      我找到了一种新的解决方法,可以使用 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%;
      }
      

      根据我的理解,包含元素的文本的直接父级必须有一定的高度。

      【讨论】:

        【解决方案6】:

        我们可以使用 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 函数未测试与旧浏览器的兼容性。

        【讨论】:

          【解决方案7】:

          使用 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/

          【讨论】:

            【解决方案8】:

            现在对 Flexbox 的支持正在增加,这个应用于包含元素的 CSS 将垂直居中包含的项目:

            .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;
            }
            

            【讨论】:

            • 一个不错的解决方案,谢谢。您能否建议如何使 flexbox 显示水平滚动条,以防内部元素大于容器? (我正在尝试使容器内的内部元素可缩放/可滚动,例如 powerpoint 中的画布)?有可能吗?
            • @YazidErman 这个解决方案依赖于 flexbox,所以不,只有 IE 10 及更高版本支持或任何其他现代浏览器caniuse.com/#search=flexbox Flexbox 在受支持的地方很棒,但并非无处不在。显示表格和表格单元格可能是最好的解决方案,容器只需要是表格,居中的元素用显示表格单元格包裹一个元素,然后可以像这里的其他答案指出的那样居中。
            • 为什么我这么难找>.
            • 有用的CSS tricks guide on flexbox 然后看看align-items 部分
            【解决方案9】:

            我的窍门是在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/sbqjnn9q/

            【讨论】:

            • 这似乎是避免头疼的最好方法。我仍然对为什么 CSS 没有垂直对齐标准感到困惑。
            【解决方案10】:

            要将块元素定位到中心(在Internet Explorer 9 及更高版本中工作),它需要一个包装器div

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

            【讨论】:

            • 此方法可能会导致元素模糊,因为元素被放置在“半像素”上。一个解决方案是设置元素的透视图。变换:透视(1px)translateY(-50%);
            【解决方案11】:

            这是div 中的i 元素的个人解决方案。

            JSFiddle Example

            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;
            }
            

            【讨论】:

              【解决方案12】:

              一年多以来,我一直在使用以下解决方案(没有定位和行高),它也适用于 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>
              

              【讨论】:

                【解决方案13】:

                几乎所有方法都需要指定高度,但通常我们没有任何高度。

                所以这是一个不需要知道高度的 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%);
                }
                

                来源:Vertical align anything with just 3 lines of CSS

                【讨论】:

                • 但这似乎只在元素父级的高度固定时才有效。具有百分比值的属性“顶部”仅适用于具有固定高度的容器,对吗?
                • 是的,它只适用于某些情况,我后来在使用这种方法时遇到了问题......问题是尽可能多地提供可能性,一旦你需要一个,你就可以测试所有这些,直到你得到好的,因为所有方法都得到了在特定情况下不起作用的东西......
                【解决方案14】:

                使用这个公式,它会一直工作而不会出现裂缝:

                #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 中从未见过这种选择器“#outer[id]”。那该怎么办?如果我有class而不是id怎么办?
                【解决方案15】:
                 .outer {
                   display: flex;
                   align-items: center; 
                   justify-content: center;
                 }
                

                【讨论】:

                • 我认为这个解决方案是最快最容易理解的。也许是因为我没有足够的耐心去摸索选定的答案。 Flexbox 所有的东西!
                • justify-content: center 的添加修复了我缺乏水平居中的问题
                • 为什么我们需要两种样式的组合才能使垂直对齐适用于所有屏幕尺寸?如果我只使用 display:flex 并调整屏幕大小,则垂直对齐会丢失,但是如果同时使用 display 和 align-items 则它可以工作。
                【解决方案16】:

                它对我有用:

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

                【讨论】:

                • 所以它不再是“块”元素了?
                • 那么如果你想水平对齐margin : 0 auto,因为display: table-cell是行不通的
                【解决方案17】:

                我使用了这个非常简单的代码:

                HTML:

                <div class="ext-box">
                    <div class="int-box">
                        <h2>Some txt</h2>
                        <p>bla bla bla</p>
                    </div>
                </div>
                

                CSS:

                div.ext-box { display: table; width:100%;}
                div.int-box { display: table-cell; vertical-align: middle; }
                

                显然,无论您使用.class 还是#id,结果都不会改变。

                【讨论】:

                【解决方案18】:

                我最喜欢的新方法是使用 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>

                【讨论】:

                  【解决方案19】:

                  哇,这个问题很受欢迎。这是基于对vertical-align 属性的误解。这篇优秀的文章解释了它:

                  Understanding vertical-align, or "How (Not) To Vertically Center Content" 来自 Gavin Kistner。

                  “How to center in CSS” 是一个很棒的网络工具,可以帮助找到不同情况下必要的 CSS 居中属性。


                  简而言之(并防止链接失效)

                  • 内联元素(和内联元素)可以通过vertical-align: middle 在其上下文中垂直对齐。然而,“上下文”并不是整个父容器的高度,而是它们所在的文本行的高度。jsfiddle example
                  • 对于块元素,垂直对齐更难,很大程度上取决于具体情况:
                    • 如果内部元素可以有固定高度,您可以将其位置设为absolute,并指定其heightmargin-toptop 位置。 jsfiddle example
                    • 如果居中元素由单行组成 并且 其父高度是固定的,您可以简单地将容器的line-height 设置为填充它的高度。根据我的经验,这种方法非常通用。 jsfiddle example
                    • ……还有更多这样的特殊情况。

                  【讨论】:

                  • “有效”解决方案(所以不是vertical-align: middle)的问题是您必须指定一个固定的高度。 响应式网页设计不太可能。
                  • 我有这个结构:
                    我的文本
                    为我工作设置属性 lineHeight 使用与 div height 属性中使用的值相同的值:'## px'(## 因为在我的情况下这个值是动态的)谢谢
                  • 这也适用于inline-blocktable-cell 元素。如果您对此有疑问,请尝试调整容器元素(即上下文)的line-height,因为它用于vertical-align 行框计算。
                  • 这个工具 (howtocenterincsss.com) 非常棒,因为它开箱即用我现有的 CSS 中工作!那是超级罕见的。记住过去你必须从一些示例中复制整个样式表,有时甚至是示例 HTML,然后一个接一个地删除和重命名元素,直到它是我需要的。本网站并非如此!
                  【解决方案20】:

                  对我来说,它是这样工作的:

                  <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”内垂直居中。

                  【讨论】:

                    【解决方案21】:
                    <!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>
                    

                    【讨论】:

                      【解决方案22】:

                      这只是另一种(响应式)方法:

                      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/

                      【讨论】:

                        【解决方案23】:

                        只需在 div 中使用单格表格!只需将单元格和表格高度设置为 100% 即可使用垂直对齐。

                        div 内的单单元表格处理垂直对齐,并且向后兼容回石器时代!

                        【讨论】:

                          【解决方案24】:

                          就这个:

                          <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 内的单单元表格处理垂直对齐,并且向后兼容回石器时代!

                          【讨论】:

                            【解决方案25】:

                            我朋友的一个技巧:

                            HTML:

                            <div style="height:100px; border:1px solid;">
                                <p style="border:1px dotted;">I'm vertically centered.</p>
                            </div>
                            

                            CSS:

                            div:before {content:" "; display:inline-block; height:100%; vertical-align:middle;}
                            div p {display:inline-block;}
                            

                            DEMO这里

                            【讨论】:

                            【解决方案26】:
                            <div id="header" style="display: table-cell; vertical-align:middle;">
                            

                            ...

                            或 CSS

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

                            Browser Coverage

                            【讨论】:

                            • vertical-align 属性不适用,因为 div 默认为 display: block,似乎没有进行任何更改。
                            • 显然显示已更新为table-cell,这使得vertical-align: middle; 工作。更好的是,它不需要嵌套的包装器/缓冲区 div,它适用于文本和图像(或两者),并且您不需要更改位置属性。
                            • 这个有效。它将显示更改为采用垂直对齐属性的表格单元格。不知道为什么人们对此投反对票。
                            • 是的,据我所知,这是在 div 中垂直居中任何东西的侵入性最小的方式。 +1
                            • 好吧,也许我的结论太快了...添加 display:table-cell 会破坏 div 边距,并且额外的边框显示在 div 之外,边框结合边框半径显示圆角在div 而不是外面
                            【解决方案27】:

                            默认情况下,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>
                            

                            【讨论】:

                            • 我应该注意到,拥有正确的 DOCTYPE 有时会对 CSS 的呈现方式产生很大的影响,尤其是在 Internet Explorer 上。我建议您选择一个已知与严格标准模式一致的 DOCTYPE,这样您就可以期望浏览器之间的行为更加一致。
                            • 我不会'期望'浏览器之间的任何一致性。唯一可以确定的方法是测试:/
                            【解决方案28】:

                            它们都需要在div内垂直对齐

                            对齐如何?图像的顶部与文本的顶部对齐?

                            其中一张图片需要绝对定位在 div 中。

                            相对于 DIV 绝对定位?也许你可以勾勒出你要找的东西……?

                            fd has described 绝对定位的步骤,以及调整H1 元素的显示以使图像与其内联显示。为此,我要补充一点,您可以使用 vertical-align 样式对齐图像:

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

                            ...这会将标题和图像放在一起,顶部边缘对齐。存在其他对齐选项; see the documentation。您可能还会发现删除 DIV 并将图像移动到 H1 元素内是有益的——这为容器提供了语义价值,并且无需调整 H1 的显示:

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

                            【讨论】:

                              猜你喜欢
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 2016-10-02
                              • 2015-12-14
                              • 1970-01-01
                              相关资源
                              最近更新 更多