Berker Yüceer
Berker Yüceer

Reputation: 7335

Is there a way to create a text that has a background image in CSS

<h2> MyTitle </h2>

I need to put a background-image to MyTitle text but only to MyTitle text.

I dont want any background in the <h2></h2> element.

Is there a way to do that in css?

Upvotes: 0

Views: 99

Answers (4)

Kyle
Kyle

Reputation: 67194

You can add a bg image to some title text by wrapping the desired text in a span and setting the css like so:

HTML

<h1>My title.<span class="myTitleBG"> My Red Title. </span>More title</h1>

CSS:

h1 span.myTitleBG
{
    display: inline-block;
    background-color: #f00; /*for example purposes*/
    background-image: url(image.png);
}

IE<7 will not see the display: inline-block;. I used this display property so you can add height and width to the span if you need to show more/less of the bg image.

http://jsfiddle.net/b2s9m/

Upvotes: 2

Mathias Bynens
Mathias Bynens

Reputation: 149594

Code:

<!DOCTYPE HTML>
<title>MyTitle</title>
<style>
  head { display: block; }
  title { display: inline; background: lime; }
</style>

Demo: http://jsbin.com/abitek

This is an example with a simple background color, but of course you could use background-image as well.

See Displaying hidden elements like <head> using CSS.


Edit now that OP mentioned he meant a heading (e.g. <h1>) and not a <title>:

The key is to use display: inline or display: inline-block.

Code:

<!DOCTYPE HTML>
<title>Test</title>
<style>
  h1 { display: inline; background: lime; }
</style>
<h1>Test</h1>
<p>Some content.

Demo: http://jsbin.com/ekusad

Again, this is an example with a simple background color, but of course you could use background-image as well.

Upvotes: 2

Bazzz
Bazzz

Reputation: 26922

I'm not completely sure what you mean with the title element as this is by default an invisible element in the head section, but I think I somehow grasp what you mean with having the background only behind the text. Try this, the background image is applied only to the text and the rest of the title element doesn't get the background image. Note that this doesn't work for the title element in the head section of your html page. It's just to indicate to you how you could set a background to a text only.

HTML

<title> <span>My Text</span> </title>

CSS

title > span {
 background-image: url(myimage.png);
}

Upvotes: 2

Ayush
Ayush

Reputation: 42450

If you mean to put a background in the titlebar, that cannot be done. Browsers only pick up text from the <title> tag and display it according to their standards.

For regular text in the body, you can use CSS to have a background like this,

<p class="backgroundText"> My text </p>

and define backgroundText class in your CSS.

Upvotes: 0

Related Questions