CSS 使背景与文本宽度相同,但高度不同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11455865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 04:27:39  来源:igfitidea点击:

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

cssbackground-color

提问by Squadrons

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

我试图在纯 css(无图像)中获得某种外观。

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中的跨度,h2显示内联和跨度一个块)

<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.

如果我的宽度正确,我将无法更改高度,因为 span 是一个内联元素。如果我通过使跨度成为块来获得正确的高度,则无法将宽度更改为与文本的宽度完全相同,因为它现在是块级元素并扩展为页面的整个宽度。

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

有什么想法,还是我只需要使用图像?

采纳答案by Ry-

Apply position: relative;to the <a>, and position: absolute;to the .title-bg<span>. Then set the topas appropriate, the leftto 0, and the widthand heightas appropriate.

适用position: relative;<a>,并position: absolute;适用于.title-bg<span>。然后top根据需要设置leftto0widthand height

Something like this: http://jsfiddle.net/minitech/3uzbV/

像这样的东西:http: //jsfiddle.net/minitech/3uzbV/

回答by Nathan Arthur

Use display:inline-block;.

使用display:inline-block;.

See this fiddle.

看到这个小提琴

h2 {
    display:inline-block;
    height:60px;
    background-color:blue;
    color:white;
}
<h2><a>Hello.</a></h2>

回答by Brian Flanagan

The simplest approach I use is line-height.

我使用的最简单的方法是line-height.

h2 a {color:#fff; line-height:40px; display:inline-block; background:#333;}?

Here's a jsFiddle.

这是一个jsFiddle

回答by Dpolehonski

CSS:

CSS:

a {
    font-size:1em;
    padding:1em 0 1em 0;/*set top and bottom padding to make up extra height*/
    background-color:#063;
}

Try this. Even inline elements can have padding.

尝试这个。甚至内联元素也可以有填充。