Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How about this way for vertically positioning text inside a div?

Tags:

css

I have always looked for alternative ways for middle positioning text inside a div, There are many ways out there, from javascript dynamic positioning to the latest css units vw and vh. The other day I realised that there is another way that was always right in-front of me all time along, but I never used it, namely by displaying a div as a table cell display:table-cell;vertical-position:middle http://jsfiddle.net/manolis/TPKsf/ I haven't used it yet in production but I'm wondering what are the pros and cons of using this solution.

Thanks!

like image 854
Manolis Avatar asked Sep 18 '13 04:09

Manolis


People also ask

How do I vertically center a div?

you need to set the outer div to be displayed as a table and the inner div to be displayed as a table-cell — which can then be vertically centered. For Internet Explorer, you need to position the inner div absolutely within the outer div and then specify the top as 50%.

How align span vertically in div?

The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.

How do you Vertical-align an image in a div?

Answer: Use the CSS vertical-align Property You can align an image vertically center inside a <div> by using the CSS vertical-align property in combination with the display: table-cell; on the containing div element.


1 Answers

Internet Explorer 7 and earlier versions don't support “display:table-cell”, IE8 supports, but requires a !DOCTYPE, you can find more explanation here - http://www.tutorialrepublic.com/css-reference/css-display-property.php

Alternatively you can also vertical align text in a div through setting value of the line-height property equal the height of div, like:

Your CSS:

div{
    height: 50px;
    line-height: 50px;
    padding: 0 20px;
    border: 1px solid #000;
}

Your HTML:

<div><a href="#">Home</a> | <a href="#">About</a> | <a href="#">Contact</a></div>

The above style rule align the text inside a div vertically center or middle. You can check out this page to know how line-height works - http://www.tutorialrepublic.com/css-tutorial/css-text.php

like image 101
Alex Avatar answered Oct 26 '22 09:10

Alex