amit
amit

Reputation: 10261

Aligning text in center in a fixed width div with an image

I have a <div> containing an image and some text. The image is supposed to come at the left corner and the text is supposed to come in the center of the <div>. But the text is coming off a little off-center to the right due to the width of the image. How do i fix it??

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

Upvotes: 0

Views: 1347

Answers (3)

Simone
Simone

Reputation: 21272

You could set the image as background of the <div class="title"> and then set text-align:center in order to align the text properly.

The HTML could be just:

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

And the CSS:

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

You will also need to set a fixed height (equal to the image), and finally set the width you wish.

Upvotes: 2

Dominic Green
Dominic Green

Reputation: 10258

Best practice is to use a background image however if not you can use position absolue like this.

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

Upvotes: 0

ptriek
ptriek

Reputation: 9276

Set header to position:relative, and #searchBoxProp to position:absolute. Absolute positioning takes the element out of the layout, so it won't affect the text postion. The relative positioning on header makes sure that #searchBoxProp is positioned relatively to header, instead of the browser window.

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

Upvotes: 1

Related Questions