Search code examples
htmlcsspositioning

Vertically centering a span in a div


I have a div containing a span and I want the span to vertically and horizontally align to the center of my div.

Here's the fiddle : http://jsfiddle.net/RhNc2/1/

I've try margin:auto on the span and the vertical-align on the div, but it's not working

EDIT : My div and my span don't have a fixed height, it depends of the content, i've put it fixed on the fiddle just to show you


Solution

  • Vertical alignment is a tricky business, and I don't know if there's one tried-and-true way. The most reliable technique available in the last couple of years is to use a CSS table layout. The only downside to this approach is that it may not work on outdated browsers. Still, in my experience this is probably the best overall solution. See my example below:

    <style type="text/css">
        #container {    
            display:table;    
            border-collapse:collapse;  
            height:200px;  
            width:100%;
            border:1px solid #000;
        }         
        #layout {    
            display:table-row;   
        }           
        #content {    
            display:table-cell;  
            text-align:center; 
            vertical-align:middle;    
        }           
    </style>
    
    <div id="container">    
        <div id="layout">    
            <div id="content"> 
                Hello world! 
            </div>     
        </div>   
    </div> 
    

    Here's a jsFiddle: http://jsfiddle.net/aGKfd/2/

    There's another technique, but it's not as foolproof as the above technique. It involves two containers, with the outer container's position set to relative and the inner set to absolute. Using absolute positioning on the inner container you can get close, but it requires some tweaking to get it just right:

    <style type="text/css">
        #vertical{ 
            position:absolute; 
            top:50%;     
            left:0; 
            width:100%; 
            text-align:center;
        } 
        #container {
            position:relative;
            height:200px;
            border:1px solid #000;
        }
    </style>         
    <div id="container"> 
        <div id="vertical"> 
            Hello world! 
        </div>               
    </div> 
    

    Here's a jsFiddle: http://jsfiddle.net/6SWPe/