如何在 div 中垂直对齐文本?

如何在 div 中垂直对齐文本?

问题描述:

I am trying to find the most effective way to align text with a div. I have tried a few things and none seem to work.

.testimonialText {
  position: absolute;
  left: 15px;
  top: 15px;
  width: 150px;
  height: 309px;
  vertical-align: middle;
  text-align: center;
  font-family: Georgia, "Times New Roman", Times, serif;
  font-style: italic;
  padding: 1em 0 1em 0;
}
<div class="testimonialText">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

</div>

转载于:https://stackoverflow.com/questions/2939914/how-do-i-vertically-align-text-in-a-div

Vertical Centering in CSS
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

Article summary:

For CSS2 browser one can use display:table/display:table-cell to center content.

Sample also available at JSFiddle:

div { border:1px solid green;}
<div style="display: table; height: 400px; overflow: hidden;">
  <div style="display: table-cell; vertical-align: middle;">
    <div>
      everything is vertically centered in modern IE8+ and others.
    </div>
  </div>
</div>

It is possible to merge hacks for old browser (IE6/7) into styles with using # to hide styles from newer browsers:

div { border:1px solid green;}
<div style="display: table; height: 400px; #position: relative; overflow: hidden;">
  <div style=
    "#position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
    <div style=" #position: relative; #top: -50%">
      everything is vertically centered
    </div>
  </div>
</div>

</div>

You need to add the line-height attribute and that attribute must match the height of the div. In your case:

.center {
  height: 309px;
  line-height: 309px; /* same as height! */
}
<div class="center">
  A single line.
</div>

In fact, you could probably remove the height attribute altogether.

This only works for one line of text though, so be careful.

</div>

You can do this by setting the display to 'table-cell' and applying a vertical-align:middle;

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

This is however not supported by all versions of Internet Explorer according to this excerpt i copied from http://www.w3schools.com/cssref/pr_class_display.asp without permission.

Note: The values "inline-table", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-row", "table-row-group", and "inherit" are not supported by IE7 and earlier. IE8 requires a !DOCTYPE. IE9 supports the values.

The following table shows the allowed display values also from http://www.w3schools.com/cssref/pr_class_display.asp. I Hope this helps

enter image description here

If you need to use with the min-height property you must add this CSS on:

.outerContainer .innerContainer {
    height: 0;
    min-height: 100px;
}

Try to embed a table element.

<div>
    <table style='width:200px; height:100px;'>
        <td style='vertical-align:middle;'>
            copenhagen
        </td>
    </table>
</div>

I use the following to vertically center random elements easily:

HTML:

<div style="height: 200px">
    <div id="mytext">This is vertically aligned text within a div</div>
</div>

CSS:

#mytext {
    position: relative;
    top: 50%; 
    transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}

This centers the text in my div to the exact vertical middle of a 200px-high outer div. Note that you may need to use a browser prefix (like -webkit- in my case) to make this work for your browser.

This works not only for text, but also for other elements.

Hmm, there're obviously many ways to solve this.

But I have a <div> that's positioned absolutely, height:100% (actually, top:0;bottom:0 and fixed width) and display:table-cell just didn't work to center text vertically. My solution did require an inner span element, but I see many of the other solutions do also, so I might as well add it:

My container is a .label and I want the number vertically centered in it. I did it by positioning absolutely at top:50% and setting line-height:0

<div class="label"><span>1.</span></div>

And the CSS is as follows:

.label {
    position:absolute;
    top:0;
    bottom:0;
    width:30px;
}

.label>span {
    position:absolute;
    top:50%;
    line-height:0;
}

See it in action: http://jsfiddle.net/jcward/7gMLx/

There's a simpler way to vertically align the content without resorting to table/table-cell:

http://jsfiddle.net/bBW5w/1/

In it I have added an invisible (width=0) div that assumes the entire height of the container.

It seems to work in IE and FF (latest versions), didn't check with other browsers

  <div class="t">
     <div>
         everything is vertically centered in modern IE8+ and others.
     </div>
      <div></div>
   </div>

And of course the CSS:

.t, .t > div:first-child
{ 
    border:1px solid green;
}
.t
{
    height:400px;
}
.t > div 
{ 
    display:inline-block; 
    vertical-align:middle  
}
.t > div:last-child
{
    height:100%;    
}

Check this simple solution:

HTML

<div class="block-title"><h3>I'm a vertically centered element</h3></div>

CSS

.block-title {
    float:left;
    display:block;
    width:100%;
    height:88px
}

.block-title h3 {
   display:table-cell;
   vertical-align:middle;
   height:inherit
}

JSFiddle

This is another variation of the div in a div pattern using calc() in CSS.

<div style="height:300px; border:1px solid green;">
  Text in outer div.
  <div style="position:absolute; height:20px; top:calc(50% - 10px); border:1px solid red;)">
    Text in inner div.
  </div>
</div>

This works, because:

  • position:absolute for precise placement of the div within a div
  • we know the height of the inner div because we set it to 20px.
  • calc(50% - 10px) for 50% - half the height for centering the inner div

HTML

<div class="relative"><!--used as a container-->
    <!-- add content here to to make some height and width
    example:<img src="" alt=""> -->
    <div class="absolute">
        <div class="table">
            <div class="table-cell">
                Vertical contents goes here
            </div>
        </div>
    </div>
</div>

CSS

 .relative{
    position:relative;
 }
 .absolute{
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:rgba(0,0,0,0.5);
 }
 .table{
    display:table;
    height:100%;
    width:100%;
    text-align:center;
    color:#fff;
 }
 .table-cell{
    display:table-cell;
    vertical-align:middle;
 }

This is my favorite solution for this issue (simple and very well browser supported):

div{
    margin:5px;
    text-align:center;
    display:inline-block;
}

.vcenter{
    background:#eee;
    width: 150px;
    height: 150px;
}
.vcenter:before {
    content: " ";
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    max-width: 0.001%; /* Just in case the text wrapps, you shouldn't notice it */
}
    
.vcenter :first-child {
    display:inline-block;
    vertical-align:middle;
    max-width: 99.999%;
}
<div class="vcenter">
  <p>This is my Text</p>
</div>
<div class="vcenter">
  <h4>This is my Text<br />Text<br />Text</h4>
</div>
<div class="vcenter">
  <div>
   <p>This is my</p>
   <p>Text</p>
  </div>
</div>

-EDIT-

This days (we don't need IE6-7-8 no more) i would just use css display: table for this issue

.vcenter{
    display: table;
    background:#eee;
    width: 150px;
    height: 150px;
    text-align: center;
}
    
.vcenter :first-child {
    display: table-cell;
    vertical-align: middle;
}
<div class="vcenter">
  <p>This is my Text</p>
</div>
   

</div>

There are several Tricks to display content/image in center of Div. Some of answers are really nice and I am fully agree with these too.

Absolute Horizontal And Vertical Centering In CSS

http://www.css-jquery-design.com/2013/12/css-techniques-absolute-horizontal-and-vertical-centering-in-css/

There are more than 10 techniques with Examples. Now it's up to you which you prefer.

No doubt, display:table; display:table-Cell is a better trick.

Some good Tricks are following:

Trick 1 - By using display:table; display:table-cell

HTML

<div class="Center-Container is-Table">
  <div class="Table-Cell">
    <div class="Center-Block">
        CONTENT 
    </div>
  </div>
</div>

CSS Code

.Center-Container.is-Table { display: table; }
.is-Table .Table-Cell {
  display: table-cell;
  vertical-align: middle;
}
.is-Table .Center-Block {
  width: 50%;
  margin: 0 auto;
}

Trick 2 - By using display:inline-block

HTML

<div class="Center-Container is-Inline">
  <div class="Center-Block">
     CONTENT 
  </div>
</div>

CSS code

.Center-Container.is-Inline { 
  text-align: center;
  overflow: auto;
}

.Center-Container.is-Inline:after,
.is-Inline .Center-Block {
  display: inline-block;
  vertical-align: middle;
}

.Center-Container.is-Inline:after {
  content: '';
  height: 100%;
  margin-left: -0.25em; /* To offset spacing. May vary by font */
}

.is-Inline .Center-Block {
  max-width: 99%; /* Prevents issues with long content causes the content block to be pushed to the top */
  /* max-width: calc(100% - 0.25em) /* Only for IE9+ */ 
}

Trick 3 - By using position:relative;position:absolute

<div style="position: relative; background: #ddd; border: 1px solid #ddd; height: 250px;">
  <div style="width: 50%; height: 60%; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background: #ccc; text-align: center;">
    <h4>ABSOLUTE CENTER,<br>
WITHIN CONTAINER.</h4>
    <p>This box is absolutely centered, horizontally and vertically, within its container</p>
  </div>
</div>

Here is a solution that works best for a single line of text.

It can also work for multi-lined text with some tweaking if the number of lines is known

.testimonialText{
    font-size:1em;/*Set a font size*/
}
.testimonialText:before {/*add a pseudo element*/
    content:"";
    display:block;
    height:50%;
    margin-top:-0.5em;/*half of the font size*/
}

Here is a JSFiddle

CSS:

.vertical {
   display: table-caption;
}

Add this class to the element that contains the things you want to align vertically

This is the cleanest solution I have found (IE9+) and adds a fix for the "off by .5 pixel" issue by using transform-style that other answers had omitted.

.parent-element {
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

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

Source: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

It is easy with display: flex. With the following method, the text in the div will be centered vertical:

div {
  display: -webkit-flex;
  display: flex;
  align-items: center;
  /* more style: */
  height: 300px;
  background-color: #888;
}
<div>
  Your text here.
</div>

And if you want, horizontal:

div {
  display: -webkit-flex;
  display: flex;
  align-items: center;
  justify-content: center;
  /* more style: */
  height: 300px;
  background-color: #888;
}
<div>
  Your text here.
</div>

You must see the browser version you need; in old versions the code does’t work.

</div>

Using flex be careful with differences in browsers rendering.

This works well both for Chrome and IE:

.outer {
    display: flex;
    width: 200px;
    height: 200px;
    background-color: #ffc;
}

.inner {
    display: flex;
    width: 50%;
    height: 50%;
    margin: auto;
    text-align: center;
    justify-content: center;
    align-items: center;
    background-color: #fcc;
}
<div class="outer"><div class="inner">Active Tasks</div></div>

Compare with that one that works only with Chrome:

.outer {
    display: flex;
    width: 200px;
    height: 200px;
    background-color: #ffc;
}

.inner {
    display: flex;
    width: 50%;
    height: 50%;
    margin: auto;
    background-color: #fcc;
}
<div class="outer">
<div class="inner"><span style="    margin: auto;">Active Tasks</span></div>
</div>

</div>

Simple solution to an element of not knowing values

HTML

<div class="main">
    <div class="center">
        whatever
    </div>
</div>

CSS

.main {
    position: relative
}

.center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
}

You can align center text vertically inside a div using the flexbox.

<div>
   <p class="testimonialText"> This is the testimonial text. </p>
</div>

div {
   display: flex;
   align-items: center;
}

You can learn more about it on this link: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

<!DOCTYPE html>
<html>
  <head>
    <style>
      .container{
        height:250px;
        background:#f8f8f8;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        -webkit-box-align: center;
        justify-content: center;
      }
      p{
      font-size:24px;}
    </style>
  </head>
  <body>
    <div class="container">
      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </body>
</html>

According to Adam Tomat's answer there was prepared a jsfiddle example to align the text in div

<div class="cells-block">    
    text<br/>in the block   
</div>

by use display:flex in CSS

.cells-block {
    display: flex;
    flex-flow: column;
    align-items: center;       /* vertically   */
    justify-content: flex-end; /* horisontally */
    text-align: right;         /* addition: for text's lines */
}

with another example and few explanation in blog.

Works fine

HTML

<div class="information">
    <span>Some text</span>
    <mat-icon>info_outline</mat-icon>
</div>

SASS

.information {
    display: inline-block;
    padding: 4px 0;
    span {
        display: inline-block;
        vertical-align: middle;
    }
    mat-icon {
        vertical-align: middle;
    }
}

Without and with image tag <mat-icon> (which is a font)

As simple as this, from the docs:

The vertical-align CSS property specifies the vertical alignment of an inline or table-cell box.

#HTML
<div>
  <span>Text</span>
</div>

#CSS
span {
  vertical-align: middle;
}

Not a single answer helped me, try this, add on parent div:

display:flex;
align-items:center;

  h1{
  margin:0;
  position: absolute;
  left:50%;
  top:50%;
  transform:translate(-50%, -50%);
}
.container {
    height: 200px;
    width: 500px;
    position: relative;
    border: 1px solid #eee;
}
    <div class="container">
            <h1>vertical align text</h1>
    </div>

With this trick, you can align anything if you don't want to make it center add "left:0" to align left.

</div>

Using css grid did it for me.

.outer {
  background-color: grey;
  width: 10rem;
  height: 10rem;
  display: grid;
  justify-items: center;
}

.inner {
  background-color: red;
  align-self: center;
}

<div class='outer'>
  <div class='inner'>
    Content
  </div>
</div>