3

See my codepen. I look to make the blue background color scale to fit with the text, "My Pet". I tried display: inline and padding, but I couldn't figure out how to set the background to fit with the text responsively, rather than being full width. Also, how can I set the opacity of the background color but not the text?

After googling, I still struggle to find a solution.

HTML:

<div class="myDiv">
    <div class="bgImage">
        <h1>My Pet</h1> 
    </div>
</div>

CSS:

.myDiv h1 {
    font-family: 'Gabriela', serif;
    color: #FFF;
    margin: auto;
    text-align: center;
    font-size: 3.5em; 
    border-radius: 20px;
    background-color: #2ba6cb;  
/*  padding: 0.5em 0.2em 0.8em 0.5em;*/
}
Web_Designer
  • 72,308
  • 93
  • 206
  • 262
thunderRX5
  • 143
  • 1
  • 2
  • 14

4 Answers4

9

Is this what you're trying to achieve?

.myDiv {
  text-align: center;
}

.myDiv h1 {
  display: inline-block;
  font-family: 'Gabriela', serif;
  color: #FFF;
  font-size: 3.5em;
  border-radius: 20px;
  background: rgba(43, 166, 203, 0.5 /* alpha value for background */);
  padding: 0.5em 0.2em 0.8em 0.5em;
}
<div class="myDiv">
  <h1>My Pet</h1> 
</div>
Ana
  • 35,599
  • 6
  • 80
  • 131
2

even shorter

width: max-content;

.myDiv h1 {
    font-family: 'Gabriela', serif;
    color: #FFF;
    margin: auto;
    text-align: center;
    font-size: 3.5em; 
    border-radius: 20px;
    background-color: #2ba6cb; 
    width:max-content; 
    padding:2px 20px;
}
<div class="myDiv">
    <div class="bgImage">
        <h1>My Pet</h1> 
    </div>
</div>
Pooya
  • 31
  • 4
1

Is that what you were trying to get? This way you can set opacity of bgImage

.myDiv h1 {
    font-family: 'Gabriela', serif;
    color: #FFF;
    margin: auto;
    text-align: center;
    font-size: 3.5em; 
}

.myDiv {
  text-align:center;
}

.myDiv .bgImage{
  display:inline-block;
  background-color: #2ba6cb;
      border-radius: 20px;
    padding: 0.5em 0.2em 0.8em 0.5em;
}
<div class="myDiv">
    <div class="bgImage">
        <h1>My Pet</h1> 
    </div>
</div>
austin wernli
  • 1,801
  • 12
  • 15
1

You can just display your h1 as a table-cell and add the required padding around the text.

Note the last two rules to selector below....

.myDiv h1 {
    font-family: 'Gabriela', serif;
    color: #FFF;
    margin: auto;
    text-align: center;
    font-size: 3.5em; 
    border-radius: 20px;
    background-color: #2ba6cb;  
    display: table-cell;
    padding: 0 0.5em ;
}
Stef
  • 341
  • 1
  • 8