2011-12-20 96 views
0

我有一個<div>包含圖像和一些文本。圖像應該出現在左上角,文本應該在<div>的中心。但由於圖像的寬度,文字偏離右邊偏右。 我該如何解決?使用圖像對齊固定寬度div中的文本

<header> 
<img id="searchBoxProp" src="/resources/images/searchBoxProp.png"> 
<div class="title">RECIPE SEARCH</div> 
</header> 


header #searchBoxProp { margin: -16px 0 0 2px; width: 43px; float: left; } 
header .title { text-align: center; margin-left: 0 auto; } 

回答

1

設置headerposition:relative,並#searchBoxPropposition:absolute。絕對定位將元素排除在佈局之外,因此它不會影響文本的位置。標題上的相對位置確保#searchBoxProp相對於header定位,而不是瀏覽器窗口。

header { 
    position:relative; 
} 
#searchBoxProp { 
    position:absolute; 
    left:0px; /* set to your needs */ 
    top:0px; /* set to your needs */ 
} 
+0

最好設置太寬100%,然後居中文本,所以你沒有定義左邊,它會自動改變,如果父容器改變。 – 2011-12-20 13:36:57

+0

@DominicGreen OP提到圖片必須位於左側角落 - 所以我認爲這是他想要的位於左上角的圖標 - 而不是全寬背景。 – ptriek 2011-12-20 13:42:39

2

你可以設置圖片爲<div class="title">的背景,然後以正確對齊文本設置text-align:center

的HTML可能只是:

<header> 
    <div class="title">RECIPE SEARCH</div> 
</header> 

而CSS:

div.title { 
    background-image:url('/resources/images/searchBoxProp.png'); 
    background-repeat:no-repeat; 
    text-align:center; 
} 

您還需要設置一個固定的高度(等於圖像),最後設置你的寬度希望。

+0

+1應該自己想到:-)因爲圖片需要位於標題的左上角,所以我會在標題上設置背景,然後添加無重複位置... – ptriek 2011-12-20 13:32:43

+0

是的,我忘了那個。謝謝:) – Simone 2011-12-20 13:33:18

+0

當有人決定使用背景而不是爭論時,Allways很高興:) – 2011-12-20 13:42:37

0

最佳做法是使用背景圖片,但如果不是,您可以像這樣使用位置絕對值。

header{position:relative;} 
header .title { position:absolute; width:100%; display:block; text-align:center; } 
+0

示例在這裏http://jsfiddle.net/CgY2u/1/ – 2011-12-20 13:37:28

相關問題