Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html vertical alignment and align center in h2 tag

Tags:

html

Can you let me know is there any mistakes in the code below? It neither align the text in center nor in middle(vertical).

<td> <h2 style = "align:center; vertical-align:middle;">TEXT</h2></td>
like image 665
user1449596 Avatar asked Aug 19 '12 10:08

user1449596


2 Answers

To center the element on the page (horizontally AND vertically) you might want to use margins. There are different ways of doing this; this is just one of them. The margins will be half the size of the container element. Example:

<td style="width:100%; height:100%;"> 
 <h2 style="position:absolute;top: 50%; left: 50%;">TEXT</h2> 
</td>

NOTE: The vertical-align property works with images, not with text which is why you need to find other solutions to center your text on a page or within an element. One way is this; margins.

A drawback of this approach is the fact that the center of the element is not taken to center it on the page; it is pushed to the middle from the borders of the element so to speak. This means that with larger elements the top left corner will be in the center of the page instead of the center point of the element. You can fix this by using negative margins given the size of the element. You need to know the size of the element you are centering. Example:

If the element to be centered (class .centered) is 200px by 100px, the CSS to center it from the center of the element would look like this:

.centered { 
 position: fixed;  
 top: 50%;  
 left: 50%;  
 margin-top: -50px;  
 margin-left: 100px;
}
like image 166
karansolo Avatar answered Sep 18 '22 15:09

karansolo


The style you are looking for is actually called text-align, not align. Moreover, the vertical-align style won't help you here, if what you want is to vertically align the header within its cell. Try the following:

<td style="vertical-align: middle;">
    <h2 style="text-align: center;">TEXT</h2>
</td>
like image 23
aefxx Avatar answered Sep 18 '22 15:09

aefxx