Arianule
Arianule

Reputation: 9063

centering text inside a div

I am trying to center text(horizontal and vertical) and I am having a little difficulty with this.

This is what I have tried but is only centering it horizontally, not vertically.

How can I get this text in the center?

<div class="playerDetailsPage">
            <p>
                <h4>The text will be in the center</h4>
            </p>

        </div>

css

    .playerDetailsPage {
    background-color: #edd4d4; 
    width: 630px;
    height: 390px;
    text-align: center; 
    vertical-align: middle;
    line-height: 390px;
}

Upvotes: 3

Views: 17684

Answers (2)

hattila
hattila

Reputation: 500

Vertical align middle will do nothing on a div (do nothing on a display:block element exactly). vertical aligning works with table cells. The example posted on the comment aligns the h4 becouse the line height is exactly the same as the height of the parent div. But what happens when you have two (or more) lines text? That will break.

The solution:

<div class="parent">
    <div class="aligner">
       <h4>The text will be in the center which can be several lines long, and will not break the verical centering. Lorem ipsum more text.</h4>
    </div>  
</div>

.parent {
background-color: #edd4d4; 
width: 630px;
height: 390px;
text-align: center; 
}

.parent .aligner {
display: table-cell;
height: inherit;
width: inherit;
vertical-align: middle;
}

You should use an internal aligner div and display it as a table cell (so vertcal align will work. You must specify the height and width of the internal element but fortunately inheritane comes to the rescue (so you don't have to redundantly specify it again).

Hope it helps!

Upvotes: 2

Siyah
Siyah

Reputation: 2897

Don't use tables for this kind of things. It isn't something you can solve by using a table.

For what I can see, it is working perfect. Here is a working example: http://jsfiddle.net/T7V58/1/

Your code is correct, what is the problem? Just remove the p tag and you are there.

<div class="playerDetailsPage">
           <h4>The text will be in the center</h4>
    </div>

CSS:

   .playerDetailsPage {
    background-color: #edd4d4; 
    width: 630px;
    height: 390px;
    text-align: center; 
    vertical-align: middle;
    line-height: 390px;
}

Upvotes: 7

Related Questions