2

this is my code:

HTML:

<div id="hello">
Hello
</div>

CSS:

#hello {
  font-size:30px;
  background-color:red;
}

As you can see in the fiddle (https://jsfiddle.net/en27xg3b/), the background color is on all the div. I want it to be only where the "Hello" is.

I'm pretty sure it's a simple code, but I forget how to do it.

Web O
  • 103
  • 2
  • 9
  • Possible duplicate of [How do I set background color of text only in CSS?](http://stackoverflow.com/questions/14310154/how-do-i-set-background-color-of-text-only-in-css) –  Dec 25 '16 at 15:59
  • Try googling for "background color on text only". –  Dec 25 '16 at 15:59

4 Answers4

3
  1. Use inline-block or inline: https://jsfiddle.net/en27xg3b/1/

#hello {
  font-size:30px;
  background-color:red;
display: inline-block;
}
<div id="hello">Hello</div>

  1. Or wrap the text in a span: https://jsfiddle.net/en27xg3b/2/

#hello span {
  font-size:30px;
  background-color:red;
}
<div id="hello"><span>Hello</span></div>
pol
  • 2,641
  • 10
  • 16
2

Wrap your text inside a span. Like this

#hello span{
  font-size:30px;
  background-color:red;
}
<div id="hello">
  <span>Hello</span>
</div>
ab29007
  • 7,611
  • 2
  • 17
  • 43
1

<div> tag is display block so it fill background full.

In this case, You only set display : inline; for <div> tag

Like this https://jsfiddle.net/en27xg3b/4/

nartoan
  • 368
  • 2
  • 9
0

I would take a look at http://www.w3schools.com/cssref/tryit.asp?filename=trycss_text_background

but what you can do is have a style

<style>
span.highlight {
  background-color:red;
}
</style>

now in your html you can do

<div id="hello">
  <span class="highlight">
    Hello
   </span>
   More Text
</div>  
MZaragoza
  • 10,108
  • 9
  • 71
  • 116