CSS css背景颜色延伸到文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8568245/
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
css background color extend as far as text?
提问by Matt
How would I set the background color of a text that doesn't expand to width of its parent div
? I used h1
{background color:white;}
and wrapped h1
around the text I want, but the white background just extends beyond text. It's almost like you're just highlighting the words.
我将如何设置不扩展到其父级宽度的文本的背景颜色div
?我使用h1
{background color:white;}
并h1
环绕了我想要的文本,但白色背景只是超出了文本范围。这几乎就像你只是突出了这些词。
回答by eveevans
h1 is a block element, so , it will use all the available area. so change this element to inline, for only use its width
h1 是块元素,因此,它将使用所有可用区域。所以将此元素更改为内联,仅使用其宽度
h1 {
display: inline;
background-color: white;
}
回答by lonesomeday
The trouble is that h1
is a block-level element, and by default block level elements will expand to fill all the available width of the parent element.
问题在于它h1
是一个块级元素,默认情况下,块级元素会扩展以填充父元素的所有可用宽度。
The easiest way to solve this is to float
the element:
解决这个问题的最简单方法是float
元素:
h1 {
background-color: white;
float: left;
}
You will then need to style the following paragraph, so that it doesn't flow round the heading element:
然后,您需要设置以下段落的样式,使其不会围绕标题元素流动:
p {
clear: left;
}
If you are comfortable not supporting IE7 and below, you can use the adjacent sibling selector to make this selection neater, so that only p
elements directly after h1
elements will be so styled:
如果你不支持 IE7 及以下版本,你可以使用相邻的兄弟选择器使这个选择更整洁,这样只有p
元素之后的h1
元素才会如此样式:
h1 + p {
clear: left;
}