简体   繁体   中英

Background-size doesn't work

Here's my CSS:

.banner-text-BG {
    background: #00A7E1 url(images/sale_tag.png) left center no-repeat !important;  
    background-size: 20px 20px;
    height: auto;
    padding: 15px;
    position: static;
    width: auto;
    -webkit-border-radius: 70px 10px 10px 70px;
    -moz-border-radius: 70px 10px 10px 70px;
    border-radius: 70px 10px 10px 70px;     
    padding-left: 70px;
}

Contrary to all the other styles, the "background-size: 20px;" has no effect on my page, is not visible in Firebug, and as a sidenote is not highlighted as a valid CSS instruction in Notepad++. Same with "background-size: 20px;" or "background-size: 20px auto;"

Am I missing something? Why does it not work?

As the background-size docs state:

If the value of this property is not set in a background shorthand property that is applied to the element after the background-size CSS property, the value of this property is then reset to its initial value by the shorthand property.

In other words, if you're using the shorthand property but don't include the background-size rule as a part of it, the separate background-size is essentially reset and ignored.

So to get around that you just need to roll it into the background shorthand you're already using by adding a slash after the background-position and including your size:

background: #00A7E1 url(http://placekitten.com/200/200) left center/20px 20px no-repeat !important;

jsFiddle example

Your use of !important in the background shorthand is preventing the background-size property from applying, at least in Chrome.

Removing the !important allows the background-sizing to take effect. See the jsfiddle: http://jsfiddle.net/QVXsj/9/

"!important" should be avoided.

I would split all background attributes as such:

.banner-text-BG {
    background-image: url(images/sale_tag.png) 
    background-position: left center;
    background-color: #00A7E1; 
    background-repeat: no-repeat;
    background-size: 20px 20px;   
}

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