lilboy
lilboy

Reputation: 23

Which is better with HTML/CSS to show an img?

Which is better:

<img src="http://placehold.it/300x200" alt="">

or:

.img {
  content: url(http://placehold.it/300x200); /* or background-image */
}
<div class="img"></div>

Consider loading times and which is better to stop users to be able to highlight the image, (I don't know why I just don't like people highlighting images) which above option is better?

Upvotes: 1

Views: 954

Answers (4)

virat
virat

Reputation: 105

If the image is part of the content such as a logo or diagram or person then use the <img> tag plus alt attribute.

If you don't want people to highlight the image background-image would be better option.

Upvotes: 0

Alex Tulic
Alex Tulic

Reputation: 44

Setting the image through CSS means some browsers will not display the image if the user tries to print your page, and inline CSS styles become hard to manage. You should probably also set the alt, as this helps with accessibility:

<img src="example.png" alt="example image">

There's no sure fire way to prevent someone downloading an image, but if you want to prevent users from right clicking (to save image as), dragging the image etc. you can use some CSS for this:

img {
    pointer-events: none;
}

This rule will be applied to all img elements.

Upvotes: 1

Stefan Morris
Stefan Morris

Reputation: 165

It all depends on your requirements. <img> tags with alt and title attributes may provide better SEO and is easier for things like maintaining aspect ratio (just providing one dimension - width/height will maintain aspect ratio), while background images allow for easier ways to crop an image or have it dynamically change using CSS.

FYI, you can prevent users from selecting/highlighting your tag with the CSS property user-select.

Upvotes: 0

Pons Purushothaman
Pons Purushothaman

Reputation: 2261

I think it depends on the scenario.

  • If it is design(background-image) element, using image as css background will be best.
  • For elements like website logos, partner logos or icons etc(generally static images but may be clickable), any method is okay.
  • But if it is part of content, like an image in news article or blog, I think it is better use <img> tag. Since we can use 'alt' and 'title' attributes in <img>, it will help in SEO also.

Upvotes: 0

Related Questions