CSS magic - Difference between span and div tags with text-align:center;

Mon, 01/07/2013 - 13:31 -- admin

I had a question regarding spans, divs and widths and text-align: center property.  Keep in mind that the difference is not between <span> and <div> specifically, but between inline and block elements. <span> defaults to being display:inline; whereas <div> defaults to being display:block;. But these can be overridden in CSS.

 The difference in the way text-align:center works between the two is down to the width.

 A block element defaults to being the width of its container. It can have its width set using CSS, but either way it is a fixed width.

 An inline element takes its width from the size of its content text.

 text-align:center tells the text to position itself centrally in the element. But in an inline element, this is clearly not going to have any effect because the element is the same width as the text; aligning it one way or the other is meaningless.

 In a block element, because the element's width is independent of the content, the content can be positioned within the element using the text-align style.

 Finally, a solution for you:

 There is an additional value for the display property which provides a half-way house between block and inline. Conveniently enough, it's called inline-block. If you specify a <span> to be display:inline-block; in the CSS, it will continue to work as an inline element but will take on some of the properties of a block as well, such as the ability to specify a width. Once you specify a width for it, you will be able to center the text within that width using text-align:center;

 This worked well for me when I needed to position a span element with text-align:center?

 

I found this original solution on http://stackoverflow.com/questions/7756926/difference-between-span-and-div-with-text-aligncenter