【问题标题】:center divs inside divs vertically垂直居中 div 内的 div
【发布时间】:2012-11-26 04:43:53
【问题描述】:

假设我在一个容器 div 中有 2 个 div,如下所示:

<div id="wrapper">
    <div id="title">A</div>
    <div id="text">Some text... Some text... Some text... Some text... Some text... Some text... Some text... Some text... Some text... Some text... Some text... </div>
</div>

正如您从标题中看到的那样,我正在尝试将 div title 和 text 垂直对齐,并且在父 div wrapper 内彼此相邻。到目前为止,我的 CSS 是这样的:

#wrapper
{       
    vertical-align:middle;
    display:table-cell;
}

#title
{
    background: url('path_to_purple_background') no-repeat;
    width:45px;
    height:45px;
    color:white;    
}

#text {
    width: 700px;
}

#title, #text {
    display: inline-block;
    vertical-align: middle;
}​

但到目前为止,我得到的是字母 A 不在我的 div title 中居中(而是位于 div 的左上角)。有人知道我该如何解决这个问题吗?

谢谢

【问题讨论】:

标签: html css


【解决方案1】:

只是一个想法,但是您可以将 text-align:center 属性添加到 #title 以及您可以添加的 line-height:HEIGHT OF #TITLE; 中。这会将A 与圆心对齐,并将A 的行高设置为与圆容器的高度相匹配,从而将其垂直对齐到中间。

【讨论】:

  • 它可以工作,但不能在 IE7 中,我怎样才能让 IE7 也能工作?
  • 我假设 lineHeight 不起作用,所以你可以使用&lt;!--[if IE 7]&gt; &lt;style type="text/css"&gt;line-height: IE LINE HEIGHT HERE;&lt;/style&gt; &lt;![endif]--&gt;。这将为 IE7 应用不同的行高。
【解决方案2】:

this 这样的东西怎么样?我将#test, #title 的display 属性设置为table-cell。

【讨论】:

  • div title 随着 div text 中文本的增长而增长,我不希望这样。
  • 刚刚注意到,inline-block 似乎是一个更好的解决方案。我会尝试找出vertical-align 无效的原因。
【解决方案3】:

vertical-align 的使用经常被误用。

来自W3C:

vertical-align 属性会影响 a 内的垂直定位 由行内元素生成的框的行框。

因此,如果您在段落中有内嵌图像,则可以使用它在文本规则内垂直对齐它。

在您的情况下,如果您只需要垂直对齐一条规则,您可以使用旧的line-height 技巧:

#title {
  height: 45px;
  width: 45px;
  line-height: 45px;
}

【讨论】:

    猜你喜欢
    • 2017-07-29
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    相关资源
    最近更新 更多