Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting background to be same width as text, but different height

I am trying to get a certain look in pure css (no images).

What I have is:

<h2>
    <a>TITLE</a>
</h2>

I would like for the text "title" to have a black background that is the same width as the text, but a different height.

I have tried this is various permutations: (ie. span in the link, span in the h2, h2 display inline and the span a block)

<h2 class="title section-title">
    <a href="<?php echo site_url(); ?>/artwork/illustrations" >
        Illustrations<span class="title-bg"></span>
    </a>
</h2>

If I get the width right, I can't change the height because the span is an inline element. If I get the height right by making the span a block, I can't change get the width to be exactly the width of the text because it is now a block level element and expands to be the entire width of the page.

Any ideas, or will I simply have to use an image?

like image 398
Squadrons Avatar asked Jul 12 '12 15:07

Squadrons


People also ask

How do I set a background color for the width of text not the width of the entire element using CSS?

Put the text in an inline element, such as a <span> . And then apply the background color on the inline element. An inline element is as big as its contents is, so that should do it for you.

How do I make the background image fit my screen size?

Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.

Can I scale on background image?

Background images can be used for resizing and scaling.


1 Answers

Use display:inline-block;.

See this fiddle.

h2 {
    display:inline-block;
    height:60px;
    background-color:blue;
    color:white;
}
<h2><a>Hello.</a></h2>
like image 133
Nathan Arthur Avatar answered Sep 30 '22 03:09

Nathan Arthur