Place image before div using :before

2019-08-30 09:24发布

I'm trying to place an image before and after div using :before and :after. Unfortunately, I don't see images. Why?

Here is the code (and in jsfiddle):

<div style="border:1px solid green; padding:50px;">
  <div id="videos-part">test</div>
</div>

#videos-part{

    height: 127px;
    width: 764px;
border:1px solid red;
    margin:30px;
    padding:30px;
}
#videos-part:before{
    width: 46px;
    height:46px;
    content: "before ";
    background-image: url(http://aux.iconpedia.net/uploads/136059938344542682.png);

}
#videos-part:after{
    width: 46px;
    height:46px;
    content: " after";
    background-image: url(http://aux.iconpedia.net/uploads/136059938344542682.png);

}

4条回答
【Aperson】
2楼-- · 2019-08-30 09:56

Using pseudo element you can add images and custom icon and create custom shapes as well. Check the DEMO first.

#videos-part{
    height: 127px;
    width: 764px;
border:1px solid red;
    margin:30px;
    padding:30px;
}
#videos-part:before{
    width: 46px;
    height:46px;
    content: " ";
    position:absolute;
    top:30px;
    left:30px;
    background-image: url("http://lorempixel.com/50/50/");

}
#videos-part:after{
    width: 46px;
    height:46px;
    content: " ";
    position:absolute;
    top:30px;
    left:60px;
    background-image: url("http://placehold.it/100x50");

}
查看更多
冷血范
3楼-- · 2019-08-30 09:56

here's an updated fiddle http://jsfiddle.net/vlrprbttst/u234x/7/

1) the urls of your images are wrong (i've put a placeholder) 2) content must stay empty 3) you may need to apply relative to the parent div and absolute to the pseudo elements :before and :after and place them using top/bottom left/right values

查看更多
我命由我不由天
4楼-- · 2019-08-30 10:05

Add display:inline-block to #videos-part before and after selectors.

#videos-part:after, #videos-part:before {
    display:inline-block;
}

Updated fiddle here.

查看更多
唯我独甜
5楼-- · 2019-08-30 10:12

You need to apply this syntax:

content: url(imageURL); with no background-image.

CSS:

#videos-part{

    height: 127px;
    width: 764px;
border:1px solid red;
    margin:30px;
    padding:30px;
}
#videos-part:before{
    width: 46px;
    height:46px;
    content: url(http://aux.iconpedia.net/uploads/136059938344542682.png);
}
#videos-part:after{
    width: 46px;
    height:46px;
    content: url(http://aux.iconpedia.net/uploads/136059938344542682.png);

}

Demo

查看更多
登录 后发表回答