Home > Software design >  CSS how to make the background to have size of content
CSS how to make the background to have size of content

Time:11-12

enter image description here

I attached an image with a text, I want the element background to have the same size as the text, which would be the same size as the highest letter. I cannot find a css property to do it.

This is my expected result: enter image description here

CodePudding user response:

Just use a span with no padding properties ..

<span style="background-color:#0000FF; color:#FFF; font-size:26px; padding: 0;">
    <a href="" style="color:#FFF; text-decoration:none;">
        Our Offer
    </a>
</span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

UPDATE

As @Huangism mentioned, fonts all have their own spacing above and below making room for the swing on a g or j for instance.

I defined the font in this example, because the CSS in your document might not match the font, and have different spacing above and below. You can then manipulate height and line-height to compensate, and reach the desired output. Note that I set the span to inline-block otherwise the height property is ignored:

span {
  display: inline-block;
  font-size: 48px;
  background-color: #0000FF;
  color:#FFF;
  font-family: 'Times New Roman';
  line-height: 34px;
  height: 35px;
}
<span>
    <a href="" style="color:#FFF; text-decoration:none;">Our Offer</a>
</span>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Two possibilities that occur to me. One is the cleaner one but it still has a slight gap at the top and bottom. The other really has no spacing but is very unflexible.

1 Variant

.c {
  display: inline;
  background-color:blue;
  color: white;
  font-size: 34px;  
}
<div>  
  <p class="c">Our Offer</p>
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

2 Variant

div.relative {
  position: relative;
  width: 165px;
  height: 28px;
  border: 3px solid #000;
  background-color: blue;
} 

div.absolute {
  position: absolute;
  top: -7px;
  left: -2px;    
  font-size:34px;
  color: white;
}
<div class="relative">
  <div class="absolute">Our Offer</div>
</div>
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related