Archive

Archive for July, 2008

CSS Centering

July 8th, 2008
Comments Off

Centering content using CSS can be challenging. Depending on the support for different versions of CSS and conflicting attributes, it may seem impossible to get it working properly.

After some serious web searching, I came up with a combination of CSS attributes that when applied to a couple of div’s, work beautifully. I can’t promise that it will work in ALL browsers, but it’s worked great for me so far. I also wanted a way to abstract the ability to center the content into something that I could just call using PHP (not good for all situations, but solved my problem), so it has been put into a function for ease of use.

Static HTML implementation:

1
2
3
4
5
<div style="margin-top: 100px; text-align: center; position: absolute; left: 0px; width: 100%; height: 1px; overflow: visible; display: block;">
    <div style="width: 700px; margin-left: -350px; position: absolute; left: 50%; text-align: center;">
        Content goes here...
    </div>
</div>

PHP implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
function css_Center($html, $width_of_content, $top_margin=0, $h_offset_percent=50)
{
    $center_html = '';
   
    $margin_left = ceil($width_of_content * .5);
   
    $outside_layer_style = 'margin-top: ' . $top_margin . 'px; text-align: center; position: absolute; left: 0px; width: 100%; height: 1px; overflow: visible; display: block;';
    $centering_layer_style = 'width: ' . $width_of_content . 'px; margin-left: -' . $margin_left . 'px; position: absolute; left: ' . $h_offset_percent . '%; text-align: center;';
   
    $center_html .= '<div style="' . $outside_layer_style . '"><div style="' . $centering_layer_style . '">' . $html . '</div></div>';
   
    return $center_html;
}

Obviously, in a real implementation, it would be ideal to use external style sheets and reference a CSS class inline.

UI ,



Sponsored Links



agile ajax black hat Cake PHP centering clifford stoll css cuckoo's egg energy energy drinks espionage flash Flex hacker jquery modular MVC objects optimization performance PHP script timer smarty smarty templates stylesheet up-time uptime variable scope web 2.0 Zend Framework