1

This is my code but I want the text to only have background colorenter image description here behind it, and not stretch across the entire screen?enter image description here Any ideas?

   .section_title {
      background-color: orange;
      text-align: center;
      margin: 0px auto;
    }

HTML is

<div class="col-md-12">
  <div class="section_title">
    <h2>Choose a Pack to Print</h2>
  </div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157

3 Answers3

1

An option is adding display: inline-block; to the CSS of the text element.

isherwood
  • 58,414
  • 16
  • 114
  • 157
ShastriH
  • 210
  • 1
  • 3
  • 12
  • You may also need to add Bootstrap's `text-center` class to the parent element, and it looks like you'll want to add some horizontal padding to get the width shown in your image. – isherwood Apr 13 '15 at 23:30
  • I'm not sure this works in order for it to be responsive for a phone screen – whoaaallamapajama Apr 14 '15 at 17:23
1

One problem I found with display: inline-block; is it clears floats incorrectly. Instead, I use width: fit-content;

.highlight {
  background: yellow;
  padding: 0.5em;
  width: fit-content;
}
<h1 class="highlight">Highlight for text only!</h1>
<h1 class="highlight">Highlight me too!</h1>
iamkeir
  • 3,222
  • 2
  • 21
  • 22
  • This still doesn't work for multi-line H1 titles, etc. – Jesse Nickles Jun 13 '23 at 23:17
  • @JesseNickles could you elaborate what you mean? If you are seeking "ragged edge" on multi-line, this wasn't a factor in the SO question - for that you'd need `display: inline`. More intel here https://css-tricks.com/multi-line-padded-text/ and here https://stackoverflow.com/questions/12709313/css-background-color-on-multi-line-text – iamkeir Jun 15 '23 at 09:47
0

There's a few ways to do this, but probably the best way is to make the h2 inline or inline-block.

Using inline-block will allow you to set width/height.

.section-title {
  text-align: center;
}
.section-title h2 {
  display: inline-block;
}

The other way to do this is to set a width on the h2 and set the margin to auto;

.section-title h2 { 
  margin-left: auto;
  margin-right: auto;
  width: 50%; /* for example */
}

If you want all your headings to be a set width, I'd choose the second one (allowing for text to wrap). If you want the box to be flexible and hug the contents, I'd use the first.

Armstrongest
  • 15,181
  • 13
  • 67
  • 106