Andrew
Andrew

Reputation: 3999

How can I center text between the top and bottom of a div?

I want to align my text to the middle of my div, but I can't seem to make it work. How can I do this?

Thanks for the help!

<div style="height:40px;">Personal Information</div>

"Personal Information" should be centered between the top and bottom.

Upvotes: 0

Views: 20433

Answers (7)

Tetelo Silas
Tetelo Silas

Reputation: 1

Let's say vertical-center is the name of your div class and the content you want to center is inside the div.

Then, this is the CSS code:

.vertical-center {
    display: flex;
    align-items: center;
    height: 100px; /* Adjust the height as needed */
}

Upvotes: 0

Kumar_Vikas
Kumar_Vikas

Reputation: 845

You can use a neat Trick of margin:0 auto; to align the contents inside the div to center. In this case the following code should work fine,

HTML:

 <div style="height:40px;"><span>Personal Information</span></div>

CSS:

 span
    { 
      width: 50%;
      margin: 20px auto;
      text-align: center;
      display:block
    }

Upvotes: 0

ngen
ngen

Reputation: 8966

How about this?

CSS:

#outer {
    height: 400px;
    overflow: hidden;
    position: relative;
    width: 100%;
}

#outer[id] {
    display: table;
    position: static;
}

#middle {
    position: absolute;
    top: 50%;
    width: 100%;
    text-align: center;
} /* for explorer only */

#middle[id] {
    display: table-cell;
    vertical-align: middle;
    position: static;
}

#inner {
    position: relative;
    top: -50%;
    text-align: center;
} /* for explorer only */

#inner {
    margin-left: auto;
    margin-right: auto;
}

div.greenBorder {
    border: 1px solid green;
    background-color: ivory;
}

HTML

<div id="outer" class="greenBorder">
    <div id="middle">
        <div id="inner" class="greenBorder"> center

        </div>
    </div>
</div> 

http://jsfiddle.net/3NjUF/4/

This is with the height of 40px: http://jsfiddle.net/3NjUF/5/

Upvotes: 1

John K.
John K.

Reputation: 5474

CSS:

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

INLINE:

<div style="display:table-cell; vertical-align:middle;">Personal Information</div>

UPDATE:

This works on JSFIDDLE...

div {
 display:table-cell;
 width: 200px;
 height: 200px;
 vertical-align:middle;
 background: red;
}

Upvotes: 5

Daniel Casserly
Daniel Casserly

Reputation: 3500

try this(yellow is there to show that it is in the center of the div

  <html>
  <body>
  <div style="height:40px; background-color:yellow">
  <div style="position:absolute; top:50%; display:table">Personal Information</div>
  </div>

  </body>
  </html>

Upvotes: 0

Evan Mulawski
Evan Mulawski

Reputation: 55334

You can use the table-cell display style to achieve this:

CSS

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

Upvotes: 2

yoda
yoda

Reputation: 10981

Making line-height the size of the element. It will, however, only work if you have only one line of text.

Upvotes: 3

Related Questions