简体   繁体   中英

how to set background-image to pseudo element?

this is the html

<div id="tab-1">

</div>

her is the css

#tab-1:before{
    background-image: url("http://t3.gstatic.com/images?q=tbn:ANd9GcQQxJ4VT26y0vXV4ea0BVugIdFEJ3BhnZByh13xvD-LbWPocNCHHw") no-repeat;
    content: "";
    display: block;
    height: 100px;
    position: relative;
    top: 8px;
    width: 500px;

}

demo

How to display background-image? If I use background-color then it works but why not background-image? And even if sometimes works in jsfiddle but not in my localhost.

You must take out the no-repeat from the background-image as you are using a short hand syntax inside background-image property which is not valid, inorder to use short hand syntax, you need to use background property instead

#tab-1:before{
    background-image: url("http://t3.gstatic.com/images?q=tbn:ANd9GcQQxJ4VT26y0vXV4ea0BVugIdFEJ3BhnZByh13xvD-LbWPocNCHHw");
    background-repeat: no-repeat;
    content: " ";
    display: block;
    height: 100px;
    position: relative;
    top: 8px;
    width: 500px;
}

Demo (Separating background-repeat if you want to keep background-image )

Demo 2 (CSS Short hand syntax using background property)

Check out : http://jsfiddle.net/6nDKP/4/

Instead of :

 background-image: url("http://t3.gstatic.com/images?q=tbn:ANd9GcQQxJ4VT26y0vXV4ea0BVugIdFEJ3BhnZByh13xvD-LbWPocNCHHw") no-repeat;

Use :

 background: url("http://t3.gstatic.com/images?q=tbn:ANd9GcQQxJ4VT26y0vXV4ea0BVugIdFEJ3BhnZByh13xvD-LbWPocNCHHw") no-repeat;

Separate the no-repeat

#tab-1:before{
    background-image: url("http://t3.gstatic.com/images?q=tbn:ANd9GcQQxJ4VT26y0vXV4ea0BVugIdFEJ3BhnZByh13xvD-LbWPocNCHHw");
    background-repeat: no-repeat;
    content: "";
    display: block;
    height: 100px;
    position: relative;
    top: 8px;
    width: 500px;
}

Fiddle: http://jsfiddle.net/6nDKP/1/

The reason its not working is that your are including no-repeat in background-image style. Exclude it to background-repeat: no-repeat; . Then it will work fine. Here is the code:-

#tab-1:before{
    background-image: url("http://t3.gstatic.com/images?q=tbn:ANd9GcQQxJ4VT26y0vXV4ea0BVugIdFEJ3BhnZByh13xvD-LbWPocNCHHw");
    background-repeat: no-repeat;
    content: "";
    display: block;
    height: 100px;
    position: relative;
    top: 8px;
    width: 500px;

} 

Change background-image with background.

#tab-1:before{
    background: url("http://t3.gstatic.com/images?q=tbn:ANd9GcQQxJ4VT26y0vXV4ea0BVugIdFEJ3BhnZByh13xvD-LbWPocNCHHw") no-repeat;
    content: "";
    display: block;
    height: 100px;
    position: relative;
    top: 8px;
    width: 500px;

}

Demo: http://jsfiddle.net/zyuWW/

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