CSS pseudo after/before using content or background for img?
Asked Answered
C

1

7

As for pseudo-elements :after/:before there are apparently two ways if I want to display image there:

  1. using background-image:url(imgurl.png);
  2. using content:url(imgurl.png);

Are both ways correct and valid? Why should I be using one way over another?

Apparently using the second method you cannot set the picture properties like size. But first method is generaly more taught on internet.

Ideas?

Clambake answered 13/2, 2015 at 23:51 Comment(1)
The part about resizing the image is just about the only deciding factor I can think of. You either care about scaling the image, or you don't because you're just going to use the image as is.Cutis
S
3

It depends on what your image is, just like the debate between using an <img> tag vs using background-image in your CSS.

If your image is part of your page's content, use content:url(imgurl.png);. Certainly if you want the images to be interactive or to to inform the user's experience while on your page, use content. If your image is just stylistic for your site's visual design, use background-image:url(imgurl.png);

Also, do note that you should use double colons: ::before and ::after. Only IE8 requires the single-colon versions.

Selfloading answered 14/2, 2015 at 0:17 Comment(1)
"If your image is part of your page's content," a purist would say to just use an img element, no questions asked. A purist would also say that generated content is purely presentational since it is entirely handled by CSS and is never made part of the actual content. In this case, it seems that the only reason one would use the content property is if they are interested in using the image's intrinsic dimensions and/or they don't want to size the pseudo-element manually.Cutis

© 2022 - 2024 — McMap. All rights reserved.