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

标签 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;
}

最佳答案

当图像具有有效的 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;
}

关于css - 对齐 div 中的元素 - 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11603783/

相关文章:

HTML Float 问题 - 应该很简单但无法正常工作

CSS:将菜单居中对齐

css - 将 CSS 类添加到 select_month

jQuery .is(":visible) for an element which is absolute positioned out of viewport

html - css 页脚在两侧切割

html - 从 Bootstrap 的导航栏折叠中排除搜索栏

html - 我怎样才能使这个响应式布局居中?

html - 如何绘制垂直线和水平标记

html - 对 grid BootStrap 组件的工作原理有一些疑问?

html - 将图像与文本 CSS 对齐