What is the difference between inserting images before the content of a block element using the "background-image" property and "padding-left" using the "before" pseudo-class?

Suppose that you need to insert an image just to the left, let's say a small eye before the number of views. I am interested in the advantages and disadvantages of each method, as well as possible features of their implementation.

    1 answer 1

    It all depends on the specific situation and the result that you need. Both methods can be good for individual cases.

    The key difference is that using before using a picture is inserted inline and completely dependent on the content, as it is part of it.

    In the case of the background, the picture lies in the background and you can position it as you like within the container. The bonus is that if you copy several of these elements by selection, only the text will be copied, which is very convenient for pasting.

    Another case: if the text to the right of the icon can take several lines, then in the case of before it will crawl under the icon on the second line. In the case of background, all content is shifted, so the text on subsequent lines will also be aligned.

    Example:

    p { width: 200px; } .img-before:before { content:url(https://placekitten.com/g/20/20); } .img-bg { padding-left: 30px; background: url(https://placekitten.com/g/20/20) left top no-repeat; } 
     <p class="img-before">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> <p class="img-bg">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> 

    • I propose to add more before with float in response. - Qwertiy
    • As far as I know, a picture with the help of "before:" can also be positioned relative to the block "content wrapper" through "position: absolute;" - Alexander Korinskiy
    • It is possible, but for this you need to describe its positioning with additional properties, assign it to a relative parent and it will still be "copied". Plus, and the content will then have to be moved as well, because the picture itself with absolute will no longer shift it. The result is a very cumbersome code. But again, it all depends on your needs. - Sergei Varzin pm