简体   繁体   English

h1背景的动态宽度

[英]dynamic width for h1 background

My CSS: 我的CSS:

h1 {
    background-color: #f7953d;
    color: #FFF;
    width: 100%;
    padding: 6px 0 6px 10px;
    margin-bottom: 10px;
}

My HTML 我的HTML

<h1>Hello World</h1>

The background color is always stretched to 100% of the screen. 背景颜色始终拉伸到屏幕的100%。 How do I make the background color stop after "World" in the h1 tag, and not go all the way to the end of the screen? 如何在h1标签中的“World”之后停止背景颜色,而不是一直到屏幕的末尾?

H1 is by default a block element and so will span the full width of its parent container you want to make it an inline element (much like a span) in order for it to only be as wide as its contents. H1默认是一个块元素,因此它将跨越其父容器的整个宽度,使其成为内联元素(非常类似于span),以使其仅与其内容一样宽。

There are 2 possible solutions dependent on your compatability needs 根据您的兼容性需求,有两种可能的解决方案

display:inline;

will achieve the effect your after however it does mean that whatever follows your H1 could appear on the same line. 将达到您之后的效果,但它确实意味着您的H1之后的任何内容都可能出现在同一条线上。

display:inline-block;

Has the effect your after while still forcing anything following it to appear below the H1 the only downside to this is it can throw up some issues in IE<8 see quirksmode for more details 你的效果是你的后续,但仍然强制跟随它出现在H1以下的唯一缺点是它可以在IE中发现一些问题<8见quirksmode更多细节

You can do this by adding display: inline-block; 您可以通过添加display: inline-block; to the CSS for your <h1> . 到你的<h1>的CSS。 This will make it use only as much width as its contents and still respect the margin and padding you give it. 这将使其仅使用与其内容一样多的宽度,并仍然尊重您给它的marginpadding

I would suggest something like this: 我会建议这样的事情:

HTML: HTML:

 <h1>Hello World</h1>
 <div class="clear"></div>

 <p>Elements after unafected by float</p>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

CSS: CSS:

h1 {
    background-color: #f7953d;
    color: #FFF;
    padding: 6px 0 6px 10px;
    margin-bottom: 10px;
    float:left;
}

.clear {
    clear:both;
}

This works consistently (unlike inline-block which isn't supported by all browsers). 这一致地工作(不像所有浏览器都不支持的内联块)。

An inline of the element is probably not what you want since you require padding. 由于需要填充,元素的内联可能不是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM