2012-07-22 66 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