2011-12-20 122 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