将固定宽度div中心的文本与图像对齐

时间:2011-12-20 13:23:23

标签: html css

我有<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; }

3 个答案:

答案 0 :(得分: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;
}

您还需要设置固定高度(等于图像),最后设置您想要的宽度。

答案 1 :(得分:1)

header设为position:relative,将#searchBoxProp设为position:absolute。绝对定位将元素排除在布局之外,因此不会影响文本位置。标头上的相对定位可确保#searchBoxProp相对于header而不是浏览器窗口定位。

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

答案 2 :(得分:0)

最佳做法是使用背景图像,但如果不是,你可以像这样使用位置绝对值。

header{position:relative;}
header .title { position:absolute; width:100%; display:block; text-align:center; }
相关问题