2

我无聊地在一个网站上乱搞,并试图弄清楚如何垂直对齐我的包裹,但我在大声笑中失败了。我已经水平对齐它,只需要帮助垂直对齐它。(是的,我尝试过垂直对齐:中间,但它不起作用)。

    * { margin:0;  padding:0; }
    html { height:100%; }
    body { background:/*url(images/bg.jpg)*/#14181a; }
    #wrap { width:960px;  height:55%;  margin:0 auto;  background:#293033; }

    <div id="wrap">
    <div id="logo"></div>
    <div id="navgation"></div>
    <div id="content"></div>
    <div id="footer"></div>
    </div>
4

4 回答 4

2

如果您不必支持较旧的浏览器,则可以使用显示框。我有以下课程:

.vertically_centered {
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;

  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;

  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
}

然后把任何东西都放在那里。由于您希望“wrap” div 垂直居中,请尝试将 vertical_centered 类分配给您的 body 元素。

有关使用灵活框的更多详细信息,您可能需要查看这篇文章:http ://www.css3.info/introducing-the-flexible-box-layout-module/

于 2012-04-21T01:55:17.817 回答
1

如果要垂直对齐 div 对象,请使用 position:relative 和顶部值,如下所示:

#wrap {width:960px; height:55%; margin:0 auto; background:#293033; position:relative; top:20px;}

如果您想将#wrap div 中的文本与特定的垂直对齐方式(例如动态上标)对齐,请在文本容器上使用 vertical-align:

#wrap span {font-size:14px; line-height:16px; vertical-align:2px;}
于 2012-04-21T01:52:23.170 回答
1

Vertical aligns can be accomplished using table layouts. You need an element displaying as a table-cell and it's parent should display as a table. Then you can add vertical alignment and it'll work.

First, here's a js fiddle showing it in action. It centers the contents of the wrap inside the wrap! (if I misunderstood and you need to center the wrap itself, just ask and I'll edit) http://jsfiddle.net/YWdDC/1/

    * { margin:0;  padding:0; }
    html { height:100%; }
    .wrap-wrapper {
        background: url('images/bg.jpg') #14181a;
        display: table;
     }
    .wrap {
        width:960px;
        height:300px;
        margin:0 auto;
        background:#293033;
        display: table-cell;
        vertical-align: middle;
    }​

    <div class="wrap-wrapper">
        <div class="wrap">
            <div id="logo">Logo</div>
            <div id="navgation">Nav</div>
            <div id="content">Content</div>
            <div id="footer">Footer</div>
        </div>
    </div>​
于 2012-04-21T01:38:24.297 回答
0

您的问题正是这篇文章中讨论的问题。

方法一

下面的例子做了两个(非平凡的)假设。如果您可以满足这些假设,那么此方法适合您:

  1. 您可以将要居中的内容放在块内,并为该内部内容块指定固定高度。
  2. 可以绝对定位此内容。(通常很好,因为内容居中的父元素仍然可以流动。

如果您能接受以上必需品,解决办法是:

  1. 将父容器指定为 position:relative 或 position:absolute。
  2. 在子容器上指定一个固定高度。
  3. 在子容器上设置 position:absolute 和 top:50% 以将顶部向下移动到父容器的中间。
  4. 设置 margin-top:-yy ,其中 yy 是子容器高度的一半以向上偏移项目。

...

方法二

此方法要求您能够满足以下条件:

  1. 您只有一行要居中的文本。
  2. 您可以为父元素指定固定高度。

如果您能接受以上必需品,解决办法是:

  1. 将父元素的 line-height 设置为您想要的固定高度。

我发现方法 2 通常是垂直对齐的最简单和最一致的方法,尽管它仅限于单行,这通常很好,因为我的大多数垂直对齐需求都是针对无论如何只需要一行的菜单项。

于 2012-04-21T02:11:49.053 回答