2012-07-22 36 views
0

我想对齐一个div和一个div元素内的图像,使它们水平居中。这似乎工作正常,直到我指定img元素的src属性 - 分配一个图像;此时它看起来像这样:对齐div内的元素 - 奇怪的行为

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属性中获得值时显示alt文本,看起来像这样:

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; 
} 
+0

如果将图像浮起,会发生什么情况? – 2012-07-22 20:36:17

+0

它们被正确放置在一起,但它们不再在父div(容器)中水平居中。 – TheBoss 2012-07-22 21:06:17

回答

0

尝试给您imgvertical-align css样式,例如:

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

这工作,但他们现在不水平,只有垂直。 – TheBoss 2012-07-22 21:15:00

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; 
} 
+0

这工作,但他们现在不水平,只有垂直。与较新评论相同的结果。 – TheBoss 2012-07-22 21:16:50

0

http://jsfiddle.net/QUk5m/

我的建议:

  1. 将搜索栏,并在div搜索按钮,在这个例子叫inside-container
  2. 浮动搜索栏左侧,和搜索右边的按钮
  3. 给外部容器或#sContainer一个高度,因为y你有漂浮的元素在里面
  4. 给每个元素的高度和宽度!

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

+0

它已经在一个容器中,但我尝试了你所说的并获得了相同的结果(它看起来像第一个图像)。 – TheBoss 2012-07-22 22:33:00

+0

我发布的代码肯定有效,你可能有CSS干扰这一点。 – Charlie 2012-07-22 22:36:11

+0

编辑原始帖子以显示更多HTML。老实说,我一整天都在挠头 - 我要去秃头。 – TheBoss 2012-07-22 22:54:23