【问题标题】:display:table-cell foobars center positioning of div?display:table-cell foobars div的中心定位?
【发布时间】:2010-12-03 12:14:57
【问题描述】:

如果您使用下面的代码并为其创建一个 html 页面,您将看到蓝色标题 div 左对齐。尽管标题元素具有固定宽度并且左/右边距设置为自动,但这是事实。

使表格正确居中的唯一方法是删除 display:table-cell 属性。

我需要它既居中对齐(水平),也需要子元素垂直居中(通过垂直对齐和显示指令)。

如何使 div 居中对齐和垂直对齐?

<!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; background: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>

【问题讨论】:

    标签: css


    【解决方案1】:

    我更改了您的样式以使用 许多 技术中的一种进行垂直和水平居中。我更喜欢这个,因为它对我来说最有意义。不涉及任何时髦的黑客攻击,并且可以跨多个浏览器工作。

    .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;
    }
    

    【讨论】:

    • 不知道需要垂直对齐的内容高度怎么办?
    • @JonathonHill 这与原始问题并不真正相关,但 Chris Coyier 在这里写了一篇关于它的文章。 css-tricks.com/centering-in-the-unknown
    【解决方案2】:

    删除display:table-cell;

    只需根据需要在顶部添加填充,然后从高度中减去该值。类似于以下内容:

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

    您必须根据自己的喜好调整填充/高度比。

    【讨论】:

      猜你喜欢
      • 2015-12-04
      • 2013-05-10
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多