【问题标题】:Aligning elements within a div - strange behaviour对齐 div 中的元素 - 奇怪的行为
【发布时间】:2012-07-22 20:33:16
【问题描述】:

我试图在 div 元素中对齐 div 和图像,使它们水平居中。在我指定 img 元素的 src 属性之前,这似乎可以正常工作 - 为其分配图像;在这一点上它看起来像这样:

源码如下(HTML):

<div id="sContainer">
    <input id="sBox" type="text" />
    <img id="sButton" alt="Search" src="images/searchglass.jpg" />
</div>

和(CSS):

#sContainer
{
background-color:yellow;
float:left;
text-align:center;
width:560px;
}

对于那些对图像在 src 属性中没有值并因此显示 alt 文本时的外观感兴趣的人来说,这就是它的外观:

有人知道如何解决这个烦人的问题吗?

编辑:

更多 HTML 代码:

<div class="center" id="header">

    <div id="leftContainer"></div>

    <div id="sContainer">
        <input id="sBox" type="text" />
        <img id="sButton" alt="Search" src="images/searchglass.jpg" />
    </div>

    <div id="rightContainer"></div>

</div>

还有 CSS:

.center
{
clear:both;
margin-left:auto;
margin-right:auto;
width:960px;
}

#header
{
background-color:gray;
height:50px;
}

#rightContainer
{
background-color:red;
float:left;
width:200px;
}

#leftContainer
{
background-color:green;
float:left;
width:200px;
}

#sBox
{
border-bottom-color:black;
border-bottom-style:solid;
border-bottom-width:1px;
border-left-color:black;
border-left-style:solid;
border-left-width:1px;
border-top-color:black;
border-top-style:solid;
border-top-width:1px;
height:18px;
padding:5px;
width:348px;
}

#sContainer
{
background-color:yellow;
float:left;
text-align:center;
width:560px;
}

#searchContainer > *
{
vertical-align:middle;
}

【问题讨论】:

  • 如果图像也向左浮动会怎样?
  • 它们正确放置在一起,但它们不再在父 div(容器)中水平居中。

标签: css html alignment


【解决方案1】:

当图像具有有效的src 属性时,它会获得尺寸,因此会强制其父元素的高度。如果要将文本框和图像保留为内联元素,可以将父级的 line-height 调整为图像高度:

#sContainer
{
    background-color:yellow;
    float:left; // btw, does this need to be floated?
    text-align:center;
    width:560px;
    line-height: 30px;
}

但是,这不会在所有浏览器中一致地呈现,因为默认情况下,这些元素与基线垂直对齐。您希望将#sContainer 的所有子元素垂直对齐到顶部或中间。

#sContainer > *
{
    vertical-align: middle;
}

【讨论】:

  • 这行得通,但它们现在没有水平连接,只有垂直连接。结果与新评论相同。
【解决方案2】:

尝试为您的img 赋予vertical-align css 样式,例如:

#sContainer img
{
    vertical-align: -4px;
}

【讨论】:

  • 这行得通,但它们现在不是水平连接,而是垂直连接。
【解决方案3】:

http://jsfiddle.net/QUk5m/

我的建议:

  1. 将搜索栏和搜索按钮放在div 中,在本例中称为inside-container
  2. 搜索栏向左浮动,搜索按钮向右浮动
  3. 给外部容器或#sContainer 一个高度,因为里面有浮动元素
  4. 给每个元素一个高度和宽度!

显然,对我的 jsFiddle 进行更改,使其更适合您的高度/宽度和命名结构。

【讨论】:

  • 它已经在一个容器中,但我尝试了你所说的,我得到了相同的结果(它看起来像第一张图片)。
  • 我发布的代码肯定是有效的,你可能有 CSS 干扰了这个。
  • 编辑了原始帖子以显示更多 HTML。老实说,我整天都在为这件事摸不着头脑——我要秃了。
猜你喜欢
  • 1970-01-01
  • 2016-11-21
  • 2014-06-10
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
相关资源
最近更新 更多