开发者

display:table-cell foobars center positioning of div?

开发者 https://www.devze.com 2023-01-28 11:27 出处:网络
If you take the code below and create an html page of it, you will see that the blue header div gets left aligned. This is despite the fact that the header element has a fixed width and left/right mar

If you take the code below and create an html page of it, you will see that the blue header div gets left aligned. This is despite the fact that the header element has a fixed width and left/right margins are set to auto.

The only way I can get the table centered properly is to remove the display:table-cell property.

I need it to be both center aligned (horizontally) and also need the child elements to be centered vertically (via the vertical-align and display directives).

How can I make the div be center aligned and also vertical aligned?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<style type="text/css">
body {margin:0; padding:0; text-align:center;}
.wrapper {padding-top:59px; text-align:left;}
.header {height:138px;width:917px; backg开发者_StackOverflow社区round:blue;margin:0 auto; text-align:center; vertical-align: middle; display:table-cell; }
</style>
</head>
<body>
<div class="wrapper">
    <div class="header">
        <div class="siteTitle"><a href="#">Site Title Here</a></div>
        <div class="tagline">Tagline goes here</div>
    </div>
</div>
</body>


I changed your styles to use one of many techniques for vertical and horizontal centering. I prefer this one because it makes the most sense to me. No funky hacks involved and works across multiple browsers.

.wrapper
{
    position: absolute;
    top: 50%;
    margin-top: -69px; /* half main elements height*/
    left: 0;
    width: 100%;
}

.header
{
    width: 917px;
    height: 138px;
    margin: 0 auto;
    background-color: #cccccc;
    overflow: auto; /* allow content to scroll inside element */
    text-align: center;
}


Drop the display:table-cell;

Just add padding to the top as needed and subtract that value from the height. Something like the following:

.header {
    height:88px;
    padding:50px 0 0 0;
    width:917px;
    background:blue;
    margin:0 auto;
    text-align:center;
}  

You'll have to adjust the padding/height ratio to your taste.

0

精彩评论

暂无评论...
验证码 换一张
取 消