简体   繁体   中英

dynamic width for h1 background

My CSS:

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

My HTML

<h1>Hello World</h1>

The background color is always stretched to 100% of the screen. 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 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.

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.

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

You can do this by adding display: inline-block; to the CSS for your <h1> . This will make it use only as much width as its contents and still respect the margin and padding you give it.

I would suggest something like this:

HTML:

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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