如何在div中垂直对齐元素?

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

其中一张图片需要absolute放在div内。

要在所有常见的浏览器上运行,需要什么CSS?

<div id="header">
    <img src=".." ></img>
    <h1>testing...</h1>
    <img src="..."></img>
</div>
JimEvaDavaid2020/03/16 14:07:22
<div id="header" style="display: table-cell; vertical-align:middle;">

...

or CSS

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

Browser Coverage

神无小小2020/03/16 14:07:22
<!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>
蛋蛋L2020/03/16 14:07:22

using display flex, first you need to wrap the container of the item that you want to align.

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

then apply the following css to wrapper div or outdiv in my example

.outdiv {
    display: flex;
    justify-content:center;
    align-items:center;
}
A达蒙2020/03/16 14:07:22

Here is just another (responsive) approach:

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/

猪猪Green2020/03/16 14:07:22

For me, it worked this way:

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

The "a" element converted to a button, using Bootstrap classes, and it is now vertically centered inside an outer "div".

小小TomNear2020/03/16 14:07:22

Just this:

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

A one-cell table inside the div handles the vertical-align and is backward compatible back to the Stone Age!

阳光逆天2020/03/16 14:07:22

I have been using the following solution (with no positioning and no line height) since over a year, it works with IE 7 and 8 as well.

<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>
神无Green2020/03/16 14:07:22

This is my personal solution for an i element inside a div

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;
}
小小TomNear2020/03/16 14:07:22

Just use a one-cell table inside the div! Just set the cell and table height and with to 100% and you can use the vertical-align.

A one-cell table inside the div handles the vertical-align and is backward compatible back to the Stone Age!

凯凯2020/03/16 14:07:22

As per today, I have found a new workaround to vertically align multiple text-lines in a div using CSS3 (and I am also using bootstrap v3 grid system to beautify the UI), which is as below:

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

As per my understanding, immediate parent of text containing element must have some height. I hope it will help you too. Thanks!

卡卡西Davaid2020/03/16 14:07:22

My new favorite way to do it is with a CSS grid:

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

逆天宝儿米亚2020/03/16 14:07:22

#3 ways to make center child div in a parent div

  • Absolute Positioning Method
  • Flexbox Method
  • Transform/Translate Method

    enter image description here

    Demo

/* 1st way */
.parent1 {
  background: darkcyan;
   width: 200px;
   height: 200px;
   position: relative;
}
.child1 {
  background: white;
  height: 30px;
  width: 30px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -15px;
}

/* 2nd way */
.parent2 {
  display: flex;
  justify-content: center;
  align-items: center;
  background: darkcyan;
  height: 200px;
  width: 200px;
}
.child2 {
  background: white;
  height: 30px;
  width: 30px;
}

/* 3rd way */
.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>

路易西门2020/03/16 14:07:22

Using CSS to vertical center, you can let the outer containers act like a table, and the content as a table cell. In this format your objects will stay centered. :)

I nested multiple objects in JSFiddle for an example, but the core idea is like this:

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

The multiple objects example:

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

Result

Result

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

TonyDavaid2020/03/16 14:07:22

By default h1 is a block element and will render on the line after the first img, and will cause the second img to appear on the line following the block.

To stop this from occurring you can set the h1 to have inline flow behaviour:

#header > h1 { display: inline; }

As for absolutely positioning the img inside the div, you need to set the containing div to have a "known size" before this will work properly. In my experience, you also need to change the position attribute away from the default - position: relative works for me:

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

If you can get that to work, you might want to try progressively removing the height, width, position attributes from div.header to get the minimal required attributes to get the effect you want.

UPDATE:

Here is a complete example that works on 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>
Gil西门2020/03/16 14:07:21

In two ways, you can align elements vertically and horizontally

  1. Bootstrap 4
  2. CSS3

enter image description here

1. Bootstrap 4.3.X

for vertical alignment: d-flex align-items-center

for horizontal alignment: d-flex justify-content-center

.container {
    height: 180px;
    width:100%;
}
<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 bg-info container">
  <div class="bg-light p-2">I am in Center</div>
</div>

2. CSS3

.container {
    display: flex;
    align-items: center;  // verticall center
    justify-content: center; // horizontally center

    background-color: #17a2b8;
    height: 180px;
    width:100%;
}

.child {
  background-color: #f8f9fa;
  padding: 0.5rem;
}
<div class="container">
  <div class="child">I am in Center</div>
</div>

古一小哥古一2020/03/16 14:07:21

Use this formula, and it will works always without cracks:

#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>

古一斯丁猴子2020/03/16 14:07:21

My trick is to put inside the div a table with 1 row and 1 column, set 100% of width and height, and the property vertical-align:middle.

<div>

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

</div>

Fiddle: http://jsfiddle.net/joan16v/sbqjnn9q/

前端猪猪GO2020/03/16 14:07:21

To position block elements to the center (works in IE9 and above), needs a wrapper div:

.vcontainer {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
}
逆天老丝2020/03/16 14:07:21
 .outer {
   display: flex;
   align-items: center; 
   justify-content: center;
 }
西里村村2020/03/16 14:07:21

它为我工作:

.vcontainer {
    min-height: 10em;
    display: table-cell;
    vertical-align: middle;
}
GOTony2020/03/16 14:07:21

我使用了以下非常简单的代码:

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

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

GreenJinJin猿2020/03/16 14:07:21

现在对flexbox的支持在增加,应用于CSS元素的CSS将使所包含的项垂直居中:

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

如果您还需要定位Explorer 10和旧的(<4.4)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;
}
神乐猪猪2020/03/16 14:07:21

哇,这个问题很流行。这是基于对vertical-align物业的误解这篇出色的文章对此进行了解释:

Understanding vertical-align, or "How (Not) To Vertically Center Content" by Gavin Kistner.

“How to center in CSS” is a great web tool which helps to find the necessary CSS centering attributes for different situations.


In a nutshell (and to prevent link rot):

  • Inline elements (and only inline elements) can be vertically aligned in their context via vertical-align: middle. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in. jsfiddle example
  • For block elements, vertical alignment is harder and strongly depends on the specific situation:
    • If the inner element can have a fixed height, you can make its position absolute and specify its height, margin-top and top position. jsfiddle example
    • If the centered element consists of a single line and its parent height is fixed you can simply set the container’s line-height to fill its height. This method is quite versatile in my experience. jsfiddle example
    • … there are more such special cases.