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
Getting background to be same width as text, but different height
提问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 top
as appropriate, the left
to 0
, and the width
and height
as appropriate.
适用position: relative;
于<a>
,并position: absolute;
适用于.title-bg
<span>
。然后top
根据需要设置left
to0
和width
and 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
回答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.
尝试这个。甚至内联元素也可以有填充。