210

What I want is for the green background to be just behind the text, not to be 100% of the page width. Here is my current code:

h1 { 
    text-align: center; 
    background-color: green; 
}
<h1>The Last Will and Testament of Eric Jones</h1> 

Note that I cannot edit the HTML. So I cannot add an inner element like a <span> nor can i insert one with javascript, etc.

JGallardo
  • 11,074
  • 10
  • 82
  • 96
Hithere Paperbag
  • 2,648
  • 4
  • 19
  • 20
  • Can this be done without putting a span in? – thomas-peter Oct 15 '13 at 13:55
  • To avoid adding the span you could have changed the < h1 > display property from block to inline (catch is you would have ensure the elements after the < h1 > are block elements. – Dan Nov 28 '13 at 03:41
  • Wondering what you ended up doing? So many of the better options for answers mentioned changing the HTML, but at that time on the project you were not able to. – JGallardo Mar 13 '23 at 19:09

17 Answers17

281

Put the text in an inline element, such as a <span>.

<h1><span>The Last Will and Testament of Eric Jones</span></h1>

And then apply the background color on the inline element.

h1 {
    text-align: center; 
}
h1 span { 
    background-color: green; 
}

An inline element is as big as its contents is, so that should do it for you.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
112

Option 1

display: table;

  • no parent required

h1 {
    display: table; /* keep the background color wrapped tight */
    margin: 0px auto 0px auto; /* keep the table centered */
    padding:5px;font-size:20px;background-color:green;color:#ffffff;
}
<h1>The Last Will and Testament of Eric Jones</h1>

fiddle

http://jsfiddle.net/J7VBV/293/

more

display: table tells the element to behave as a normal HTML table would.

More about it at w3schools, CSS Tricks and here


Option 2

display: inline-flex;

  • requires text-align: center; on parent

.container {
    text-align: center; /* center the child */
}
h1 {
    display: inline-flex; /* keep the background color wrapped tight */
    padding:5px;font-size:20px;background-color:green;color:#ffffff;
}
<div class="container">
  <h1>The Last Will and Testament of Eric Jones</h1>
</div>

Option 3

display: flex;

  • requires a flex parent container

.container {
  display: flex;
  justify-content: center; /* center the child */
}
h1 {
    display: flex;
    /* margin: 0 auto; or use auto left/right margin instead of justify-content center */
    padding:5px;font-size:20px;background-color:green;color:#ffffff;
}
    <div class="container">
      <h1>The Last Will and Testament of Eric Jones</h1>
    </div>

about

Probably the most popular guide to Flexbox and one I reference constantly is at CSS Tricks


Option 4

display: block;

  • requires a flex parent container

.container {
  display: flex;
  justify-content: center; /* centers child */
}
h1 {
    display: block;
    padding:5px;font-size:20px;background-color:green;color:#ffffff;
}
<div class="container">
  <h1>The Last Will and Testament of Eric Jones</h1>
</div>

Option 5

::before

  • requires entering words in css file (not very practical)

h1 {
    display: flex; /* set a flex box */
    justify-content: center; /* so you can center the content like this */
}

h1::before {
    content:'The Last Will and Testament of Eric Jones'; /* the content */
    padding: 5px;font-size: 20px;background-color: green;color: #ffffff;
}
<h1></h1>

fiddle

http://jsfiddle.net/J7VBV/457/

about

More about css pseudo elements ::before and ::after at CSS Tricks and pseudo elements in general at w3schools


Option 6

display: inline-block;

  • centering with position: absolute and translateX

  • requires a position: relative parent

.container {
  position: relative; /* required for absolute positioned child */
}
h1 {
  display: inline-block; /* keeps container wrapped tight to content */
  position: absolute; /* to absolutely position element */
  top: 0;
  left: 50%; /* part1 of centering with translateX/Y */
  transform: translateX(-50%); /* part2 of centering with translateX/Y */
  white-space: nowrap; /* text lines will collapse without this */
  padding:5px;font-size:20px;background-color:green;color:#ffffff;
}
  <h1>The Last Will and Testament of Eric Jones</h1>

about

More on centering with transform: translate(); (and centering in general) in this CSS tricks article


Option 7

text-shadow: and box-shadow:

  • not what the OP was looking for but maybe helpful to others finding their way here.

h1, h2, h3, h4, h5 {display: table;margin: 10px auto;padding: 5px;font-size: 20px;color: #ffffff;overflow:hidden;}
h1 {
    text-shadow: 0 0 5px green,0 0 5px green,
                 0 0 5px green,0 0 5px green,
                 0 0 5px green,0 0 5px green,
                 0 0 5px green,0 0 5px green;
}
h2 {
    text-shadow: -5px -5px 5px green,-5px 5px 5px green,
                  5px -5px 5px green,5px 5px 5px green;
}
h3 {
    color: hsla(0, 0%, 100%, 0.8);
    text-shadow: 0 0 10px hsla(120, 100%, 25%, 0.5),
                 0 0 10px hsla(120, 100%, 25%, 0.5),
                 0 0 10px hsla(120, 100%, 25%, 0.5),
                 0 0 5px hsla(120, 100%, 25%, 1),
                 0 0 5px hsla(120, 100%, 25%, 1),
                 0 0 5px hsla(120, 100%, 25%, 1);
}
h4 { /* overflow:hidden is the key to this one */
    text-shadow: 0px 0px 35px green,0px 0px 35px green,
                 0px 0px 35px green,0px 0px 35px green;
}
h5 { /* set the spread value to something larger than you'll need to use as I don't believe percentage values are accepted */
  box-shadow: inset 0px 0px 0px 1000px green;
}
<h1>The First Will and Testament of Eric Jones</h1>
<h2>The 2nd Will and Testament of Eric Jones</h2>
<h3>The 3rd Will and Testament of Eric Jones</h3>
<h4>The Last Will and Testament of Eric Jones</h4>
<h5>The Last Box and Shadow of Eric Jones</h5>

fiddle

https://jsfiddle.net/Hastig/t8L9Ly8o/

More Options

There are a few other ways to go about this by combining the different display options and centering methods above.

Hastig Zusammenstellen
  • 4,286
  • 3
  • 32
  • 45
  • 1
    Doing this with no containers and no pseudo-elements is simply awesome! Had no idea that the `display: table` could be so powerful, but I appreciate that you provided working alternatives. – CPHPython Mar 21 '19 at 11:19
  • 1
    this is the most thorough answer I've seen on this site. Well done – Tessa Painter Sep 29 '21 at 06:00
58

A little late to game but thought I would add my 2 cents...

To avoid adding the extra mark-up of an inner span you could change the <h1> display property from block to inline (catch is you would have ensure the elements after the <h1> are block elements.

HTML

<h1>  
The Last Will and Testament of
Eric Jones</h1> 
<p>Some other text</p>

CSS

h1{
    display:inline;
    background-color:green;
    color:#fff;
}

Result
enter image description here
JSFIDDLE http://jsfiddle.net/J7VBV/

Dan
  • 10,171
  • 7
  • 38
  • 31
  • 3
    Correct? Really? This way the heading is not centered anymore (because it's displayed inline). OP's question clearly includes the requirement for a centered heading. – BalusC Mar 30 '14 at 05:39
  • 3
    @BalusC - No where in the original question does the OP specifically state the heading has to be centered. The question clearly asks how to make the green background not go full width. #justSaying – Dan Mar 30 '14 at 07:07
  • 2
    OP's screenshot and OP's initial CSS implies otherwise. – BalusC Mar 30 '14 at 15:26
  • 6
    That maybe, but we are talking specifics here - not assumptions. – Dan Mar 31 '14 at 03:02
  • 1
    this has added problem in cases.. where if

    and

    tags are immediately in next lines... then

    and

    will then be displayed on the same line. The below display:table option is a good choice if you don't want to change the source code of the

    tags itself... but only change the css.

    – ihightower Dec 19 '16 at 15:35
12

As the other answers note, you can add a background-color to a <span> around your text to get this to work.

In the case where you have line-height though, you will see gaps. To fix this you can add a box-shadow with a little bit of grow to your span. You will also want box-decoration-break: clone; for FireFox to render it properly.

EDIT: If you're getting issues in IE11 with the box-shadow, try adding an outline: 1px solid [color]; as well for IE only.

Here's what it looks like in action:

example of the css technique

.container {
  margin: 0 auto;
  width: 400px;
  padding: 10px;
  border: 1px solid black;
}

h2 {
  margin: 0;
  padding: 0;
  font-family: Verdana, sans-serif;
  text-transform: uppercase;
  line-height: 1.5;
  text-align: center;
  font-size: 40px;
}

h2 > span {
  background-color: #D32;
  color: #FFF;
  box-shadow: -10px 0px 0 7px #D32,
    10px 0px 0 7px #D32,
    0 0 0 7px #D32;
  box-decoration-break: clone;
}
<div class="container">
    <h2><span>A HEADLINE WITH BACKGROUND-COLOR PLUS BOX-SHADOW :3</span></h2>
</div>
Cobertos
  • 1,953
  • 24
  • 43
  • great tip adding the box-shadow - makes up the padding nicely. Thank you! – zumek Feb 22 '21 at 23:34
  • can we also remove the extra red color from text padding? – Gaurav Mar 22 '22 at 05:36
  • @Gaurav "Text padding" what do you mean? If you're talking about the line-height gaps, you'd want to remove the `box-shadow` and decrease `line-height`. If you still have "padding", you might need a negative `line-height` due to the font having baked in metrics that make it hard to style. You could also pull the font into something like font forge and modify the metrics directly. Might want to open a new question – Cobertos Mar 22 '22 at 06:42
  • got it, will try – Gaurav Mar 22 '22 at 12:38
  • With semi-transparent background color, this option does not render correctly. – atulmy Sep 09 '22 at 08:30
  • @AtulYadav That's going to be really tough, considering the boxes the browser will create can overlap between broken lines. The closest I could get was using borders instead of box-shadow, but aligning it between different browsers to not overlap is not possible. See https://jsfiddle.net/m4z0xeb8/ – Cobertos Sep 10 '22 at 09:51
  • This is the actual answer to the question. All others have some show-stopper. – Ben Racicot Mar 08 '23 at 23:49
9

A very simple trick to do so, is to add a <span> tag and add background color to that. It will look just the way you want it.

<h1>  
    <span>The Last Will and Testament of Eric Jones</span>
</h1> 

And CSS

h1 { text-align: center; }
h1 span { background-color: green; }

WHY?

<span> tag in an inline element tag, so it will only span over the content faking the effect.

Starx
  • 77,474
  • 47
  • 185
  • 261
5

EDIT: the answer below would apply in most cases. OP however later mentioned that they could not edit anything other than the CSS file. But will leave this here so it may be of use to others.

enter image description here

The main consideration that others are neglecting is that OP has stated that they cannot modify the HTML.

You can target what you need in the DOM then add classes dynamically with javascript. Then style as you need.

In an example that I made, I targeted all <p> elements with jQuery and wrapped it with a div with a class of "colored"

$( "p" ).wrap( "<div class='colored'></div>" );

Then in my CSS i targeted the <p> and gave it the background color and changed to display: inline

.colored p {
    display: inline;
    background: green;
}

By setting the display to inline you lose some of the styling that it would normally inherit. So make sure that you target the most specific element and style the container to fit the rest of your design. This is just meant as a working starting point. Use carefully. Working demo on CodePen

JGallardo
  • 11,074
  • 10
  • 82
  • 96
4

Try removing the text-alignment center and center the <h1> or <div> the text resides in.

h1 {
    background-color:green;
    margin: 0 auto;
    width: 200px;
}
JGallardo
  • 11,074
  • 10
  • 82
  • 96
AgnosticDev
  • 1,843
  • 2
  • 20
  • 36
4

h1 is a block level element. You will need to use something like span instead as it is an inline level element (ie: it does not span the whole row).

In your case, I would suggest the following:

style.css

.highlight 
{
   background-color: green;
}

html

<span class="highlight">only the text will be highlighted</span>
Andy
  • 588
  • 1
  • 6
  • 11
4

can use html5 mark tag within paragraph and heading tag.

<p>lorem ipsum <mark>Highlighted Text</mark> dolor sit.</p>
3

Without changing html markup

If you do not wish to change any of your html tags you can use:

h1 {
    background-color: green;  
    display: inline-block;
}

With changing html markup

This can be done using the HTML5 <mark> tag.

HTML:

<h1><mark>The Last Will and Testament of Eric Jones</mark></h1>

CSS:

mark
{
    background-color: green;
}
Dan Bray
  • 7,242
  • 3
  • 52
  • 70
3

Easily :

<p>lorem ibsum....</p>

with styles :

p{
    background-color: #eee;
    display: inline;
}


the background sets to the whole size of the element; revise the diffrence between inline elements and block elements from here

Ahmed Mansour
  • 500
  • 4
  • 14
0

Try this one:

h1 {
    text-align: center;
    background-color: green;
    visibility: hidden;
}

h1:after {
    content:'The Last Will and Testament of Eric Jones';
    visibility: visible;
    display: block;
    position: absolute;
    background-color: inherit;
    padding: 5px;
    top: 10px;
    left: calc(30% - 5px);
}

Please note that calc is not compatible to all browsers :) Just want to be consistent with the alignment in the original post.

https://jsfiddle.net/richardferaro/ssyc04o4/

Richard Feraro
  • 467
  • 4
  • 9
-1

HTML

<h1>
  <span>
    inline text<br>
      background padding<br>
      with box-shadow
  </span>
</h1> 

Css

h1{
  font-size: 50px;
  padding: 13px; //Padding on the sides so as not to stick.


  span {  
    background: #111; // background color
    color: #fff;
    line-height: 1.3; //The height of indents between lines.
    box-shadow: 13px 0 0 #111, -13px 0 0 #111; // Indents for each line on the sides.
  }
}

Demo on codepen

TiiGRUS
  • 85
  • 1
  • 4
  • Firefox requires `box-decoration-break: clone;`, https://developer.mozilla.org/en-US/docs/Web/CSS/box-decoration-break – Cobertos Dec 03 '19 at 16:48
-1

<mark> tag with background-color helped me.

Input:

<p>
    Effective <mark style="background-color: light-gray">Nov 1, 2022</mark> We will be lowering our price.
</p>

Output: Effective Nov 1, 2022 We will be lowering our price.

Ref

Mohammad Zaid Pathan
  • 16,304
  • 7
  • 99
  • 130
-2

You have to mention the width of the h1 tag..

your css will be like this

h1 {
text-align: center;
background-color: green;
width: 600px;
 }
ramya
  • 1
  • 1
-2

HTML

<h1 class="green-background"> Whatever text you want. </h1>

CSS

.green-background { 
    text-align: center;
    padding: 5px; /*Optional (Padding is just for a better style.)*/
    background-color: green; 
}
  • 3
    Any answer that is code-only could be made much more useful to people looking for a solution to this problem if you could add some context to your answer. – David Buck Nov 24 '19 at 23:38
-3

<h1 style="display:inline-block;text-align: center;background : red;">The Last Will and Testament of Eric Jones</h1>
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • Well. That's some code. Just some code. It is completely free of explanation. It has the side effect of changing how the heading behaves in relation to the content around it. It says nothing that https://stackoverflow.com/a/32919558/19068 and https://stackoverflow.com/a/20257339/19068 haven't both said already – Quentin Dec 04 '19 at 13:14
  • The user mentioned that they cannot change the HTML, adding an inline style is changing the HTML file. – JGallardo Mar 13 '23 at 19:07