在div中对齐元素 - 奇怪的行为

时间:2012-07-22 20:33:16

标签: css html alignment

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

picture of the problem

源代码如下(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属性中没有值的情况感兴趣的人,因此显示替代文本,这就是它的样子:

picture of problem

任何人都知道如何解决这个恼人的问题?

修改

更多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;
}

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

尝试为img提供vertical-align css样式,例如:

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

答案 2 :(得分:0)

http://jsfiddle.net/QUk5m/

我的建议:

  1. 将搜索栏和搜索按钮放在div中,在此示例中名为inside-container
  2. 将搜索栏浮动到左侧,将搜索按钮浮动到右侧
  3. 给外部容器或#sContainer一个高度,因为你已经在里面放了元素
  4. 给每个元素一个高度和宽度!
  5. 显然,对我的jsFiddle进行更改,以更好地适应您的高度/宽度和命名结构。

相关问题