Вы находитесь на странице: 1из 14

Stack Exchange Inbox Reputation and Badges 1 help

Stack Overflow
Questions
Tags
Users
Badges
Unanswered
Ask Question
When to use IMG vs. CSS background-image?
up vote
781
down vote
favorite
446
In what situations is it more appropriate to use an HTML IMG tag to display an i
mage, as opposed to a CSS background-image, and vice-versa?
Factors may include accessibility, browser support, dynamic content, or any kind
of technical limits or usability principles.
html css image background-image
shareedit
edited May 23 '14 at 15:08
community wiki
17 revs, 6 users 63%
system PAUSE
locked by George Stocker? May 23 '14 at 15:08
This question's answers are a collaborative effort: if you see something that ca
n be improved, just edit the answer to improve it! No additional answers can be
added here
9
As an update, since this ranks pretty high on Google, browser scaling and image
stretching for background-image is now possible, and pretty widely supported (IE
8 and below, of course, being the exception), rendering items 4 and 7 moot in ca
ses that can allow for a fallback or ignoring such an effect for IE8 and below.
Shauna Feb 8 '13 at 15:45
caniuse.com/#search=background-image
2
Also img can have map with clickable areas and hints
Vitim.us Sep 27 '13 at 16:
08
comments disabled on deleted / locked posts / reviews | show 5 more comments
31 Answers
activeoldestvotes
1 2 next
up vote
345
down vote
accepted
Proper uses of IMG

Use IMG if you intend to have people print your page and you want the image to b
e included by default. JayTee
Use IMG (with alt text) when the image has an important semantic meaning, such a
s a warning icon. This ensures that the meaning of the image can be communicated
in all user-agents, including screen readers.
Pragmatic uses of IMG
Use IMG if you intend to have people print your page and you want the image to b
e included by default. JayTee
Use IMG if you rely on browser scaling to render an image in proportion to text
size.
Use IMG for multiple overlay images in IE6.
Use IMG with a z-index in order to stretch a background image to fill its entire
window.
Note, this is no longer true with CSS3 background-size; see #6 below.
Using img instead of background-image can dramatically improve performance of an
imations over a background.
When to use CSS background-image
Use CSS background images if the image is not part of the content. sanchothefat
Use CSS background images when doing image-replacement of text eg. paragraphs/he
aders. sanchothefat
Use background-image if you intend to have people print your page and you do not
want the image to be included by default. JayTee
Use background-image if you need to improve download times, as with CSS sprites.
Use background-image if you need for only a portion of the image to be visible,
as with CSS sprites.
Use background-image with background-size:cover in order to stretch a background
image to fill its entire window.
shareedit
edited Nov 10 '14 at 13:10
Adobe
2,70812150
answered Sep 23 '09 at 23:58
system PAUSE
12.7k144355
13
Pragmatic Use of backbround image: When you don't want to loose hair about verti
cal centering problems (of images of varying vertical size) ;)
Frank Nocke Mar
31 '13 at 17:58
4
Yes, vertical centering problems - bring on Flexbox!
Dean_Wilson Nov 17 '14 at
2:18
show 6 more comments
up vote
206
down vote
It's a black and white decision to me. If the image is part of the content such
as a logo or diagram or person (real person, not stock photo people) then use th
e <img /> tag plus alt attribute. For everything else there's CSS background ima
ges.
The other time to use CSS background images is when doing image-replacement of t
ext eg. paragraphs/headers.
shareedit

answered Jan 29 '09 at 18:31


sanchothefat
7,20941630
3
@TheoScholiadis using image replacement does not mean using an image instead of
text, but hiding the text in some way using CSS and supplying the image as a bac
kground using CSS. The document remains semantically untouched.
sanchothefat Ap
r 19 '12 at 13:16
28
Personally I hate when I can't copy "text" because it's actually an image. Call
me lazy but hey...
Shaz Jul 25 '13 at 14:35
show 9 more comments
up vote
42
down vote
I'm surprised no one's mentioned this yet: CSS transitions.
You can natively transition a div's background image:
#some_div {
background-image:url(image_1.jpg);
-webkit-transition:background-image 0.5s;
/* Other vendor-prefixed transition properties */
transition:background-image 0.5s;
}
#some_div:hover {
background-image:url(image_2.jpg);
}
This saves any kind of JavaScript or jQuery animation to fade an <img/>'s src.
shareedit
edited May 4 '14 at 17:15
community wiki
3 revs
Robbie JW
add a comment
up vote
30
down vote
Browsers aren't always set to print background images by default; if you intend
to have people print your page :)
shareedit
answered Jan 29 '09 at 18:32
JayTee
1,81221321
6
Sounds like: PRO--Use IMG if you want the image to print by default. CON--Use ba
ckground-image if you don't want the image to print by default. Nice one!
syste
m PAUSE Jan 29 '09 at 18:38
3
I think the idea is to have separate print-only CSS styles which hide the images
or change them to something more appropriate.
Blazemonger Jan 28 '14 at 17:36
add a comment
up vote
24

down vote
If you have your CSS in an external file, then it's often convenient to display
an image that's used frequently across the site (such as a header image) as a ba
ckground image, because then you have the flexibility to change the image later.
For example, say you have the following HTML:
<div id="headerImage"></div>
...and CSS:
#headerImage {
width: 200px;
height: 100px;
background: url(Images/headerImage.png) no-repeat;
}
A few days later, you change the location of the image. All you have to do is up
date the CSS:
#headerImage {
width: 200px;
height: 100px;
background: url(../resources/images/headerImage.png) no-repeat;
}
Otherwise, you'd have to update the src attribute of the appropriate <img> tag i
n every HTML file (assuming you're not using a server-side scripting language or
CMS to automate the process).
Also background images are useful if you don't want the user to be able to save
the image (although I haven't ever needed to do this).
Steve
shareedit
answered Apr 10 '09 at 6:18
Steve Harrison
40.6k116667
7
Background images can certainly be saved with some minimal view source spelunkin
g, just not as easily as right-clicking on an image.
Michael Hackner Dec 2 '10
at 16:03
1
@TRiG Unless there's a transparent overlay or page-specific context menu modific
ation to prevent you from doing that. I've seen that before, and in my opinion i
t's quite silly because you don't even need to go spelunking in source, if the p
age has fully loaded then in Firefox at least you can click Tools>Page Info/alt+
t, i/right-click and select View Page Info, browse to the Media section, and sav
e all the items you want from the list. Of course, there are ways to prevent eve
n that, like embedding the image in a Flash file or other weird tricks, but even
those can be bypassed or accounted for.
JAB Jun 27 '13 at 18:46
show 2 more comments
up vote
21
down vote
About the same as sanchothefat's anwser, but from a different aspect. I always a
sk myself: if I may remove completely the stylesheets from the website, the rema
ining elements do only belong to the content? If so, I did my job well.
shareedit
answered Apr 20 '09 at 17:01

Trk Gbor
15.7k74772
add a comment
up vote
21
down vote
Some answers overcomplicate the scenario here. This is a dead simple situation.
Just answer to this question every time you'd like to place an image:
Is this part of the content or part of the design?
If you can't answer this, you probably don't know what you're doing or what you
want to do!
Also, DO NOT consider beside the two technique, just because you'd wish to be "p
rinter friendly" or not. Also DO NOT hide content from a SEO point of view with
CSS. If you find yourself managing your content in CSS files, you shot yourself
in the leg. This is just a trivial decision of what is content or not. Every oth
er aspect should be ignored.
shareedit
edited Jun 22 '13 at 8:58
community wiki
2 revs
Dyin
add a comment
up vote
14
down vote
I would add another two arguments:
An img tag is good if you need to resize the image. E.g. if the original image i
s 100px by 100 px, and you want it to be 80px by 80px, you can set the CSS width
and height of the img tag. I don't know of any good way to do this using backgr
ound-image.
Using background-image is good when you need to dynamically switch between sprit
es. E.g. if you have a button image, and you want a separate image displayed whe
n the cursor is hovering over the element, you can use a background image contai
ning both the normal and hover sprites, and dynamically change the background-po
sition.
shareedit
answered Aug 24 '11 at 16:03
community wiki
Anders Rabo Thorbeck
show 1 more comment
up vote
11
down vote
Foreground = img.
Background = CSS background.
shareedit
answered May 22 '09 at 18:03

cjk
29.6k34983
1
Sure, but what about the little down-arrow indicator next to the "menu" button,
or other such elements. How do you classify that- foreground or background?
dud
ewad Feb 3 at 18:52
add a comment
up vote
11
down vote
Use background images only when necessary e.g. containers with image that tiles.
One of the major PROS by using IMAGES is that it is better for SEO.
shareedit
answered Sep 18 '10 at 14:14
community wiki
Marc Uberstein
2
Can you elaborate?
nafg May 1 '13 at 2:36
3
Probably because you can use the alt attribute.
David Jun 7 '13 at 16:54
3
Doesn't that depend on whether you WANT SEO for that specific image? I don't see
why you would go for SEO on an image that is part of the styling of the page, n
ot the content (e.g. an email icon on your contact page). So actually, I'd rathe
r turn your statement around. Only use IMAGES when necessary (that being content
-related, print-related and/or SEO-related).
Volzy May 2 '14 at 9:59
add a comment
up vote
8
down vote
Here's a technical consideration: will the image be generated dynamically? It te
nds to be a lot easier to generate the <img> tag in HTML than to try to dynamica
lly edit a CSS property.
shareedit
answered Feb 2 '09 at 22:30
Bryan M.
10.4k73555
1
And what about inline styles? This question really must not decided by this idea
.
Trk Gbor Apr 20 '09 at 16:54
show 2 more comments
up vote
8
down vote
Using a background image, you need to absolutely specify the dimensions. This ca
n be a significant problem if you don't actually know them in advance or cannot
determine them.
A big problem with <img /> is overlays. What if I want an CSS inner shadow on my
image (box-shadow:inset 0 0 5px rgb(0,0,0,.5))? In this case, since <img /> can
't have child elements, you need to use positioning and add empty elements which
equates to useless markup.
In conclusion, it's quite situational.

shareedit
edited Feb 16 '14 at 14:21
community wiki
2 revs, 2 users 80%
Mat
show 1 more comment
up vote
8
down vote
Above answers considers only Design aspect . I am listing it in SEO aspects.
When to use <img />
When Your Image need to be indexed by search engine
If it has relation to content not to design.
If your image is not too small ( not iconic images ).
Images where you can add alt and title attribute.
When to use CSS background-image
Images Purely Used to Design.
No Relation With Content.
Small Images which we can play with CSS3.
Repeating Images ( In blog author icon , date icon will be repeated for each art
icle etc.,).
As i will use them based on these reasons. These are Good practices of Search En
gine Optimization of Images.
shareedit
answered May 23 '14 at 6:44
community wiki
subhash
add a comment
up vote
7
down vote
Use CSS background-image in a case of multiple skins or versions of design. Java
script can be used to dynamically change a class of an element, which will force
it to render a different image. With an IMG tag, it may be more tricky.
shareedit
answered Feb 13 '09 at 18:29
MK_Dev
2,28121535
2
@sanchothefat, true, however, in this case image source would need to be kept in
JS instead of CSS. IMO css file would be more appropriate to keep file name.
M
K_Dev Feb 16 '09 at 0:34
show 1 more comment
up vote
7
down vote
One more benefit from using the <IMG> tag is related to SEO - i.e. you can provi
de additional information about the image in the ALT attribute of the image tag,
while there's no way to provide such information when specifying the image thro
ugh CSS and in that case only the image file name may be indexed by search engin
es. The ALT attribute definitely gives the <IMG> tag SEO advantage over the CSS

approach. That's why IMO you should specify the images you want to rank well in
the image search results (e.g. Google Image Search) using the <IMG> tag.
shareedit
answered Apr 10 '13 at 10:23
community wiki
Pavel Vladov
add a comment
up vote
7
down vote
A couple of other scenarios where background-image should be used:
When you want the image to change when the mouse is hovered upon it.
When you want to add rounded corners to the image. If you use img, the image lea
ks out of the rounded corners.
shareedit
edited Aug 9 '14 at 12:25
community wiki
2 revs
Behrang
1
Well 5 years ago a lot of things didn't work on many browsers ;-)
jme11 Aug 9 '
14 at 12:28
show 2 more comments
up vote
5
down vote
What about the size of the image? If I use the img tag, the browser scales the i
mage. If I use css background, the browser just cuts a chunk from the larger ima
ge.
shareedit
answered May 22 '09 at 18:00
anonymous
add a comment
up vote
5
down vote
Also, i have a gallery section which has inconsistent picture sizes so even thou
gh those images are obviously considered content, I use background images and ce
nter them in divs with a set size. This is similar to what facebook does in thei
r albums..
shareedit
answered May 31 '11 at 17:52
community wiki
Chris
add a comment
up vote
5
down vote
img is an html tag for a reason, therefore it should be used. For referencing or
to illustrate things, people e.g: in articles.
Also if the image has a meaning or has to be clickable an img is better than a c
ss background. For all other situation, I think, a css background can be used.

Although, it is a subject that needs to be discussed over and over.


Web Student from Paris, France
shareedit
edited Feb 15 '12 at 6:52
community wiki
2 revs, 2 users 80%
user589956
add a comment
up vote
5
down vote
In regards to animating images using CSS TranslateX/Y (The proper way to animate
html) - If you do a Chrome Timeline recording of CSS background-images being an
imated vs IMG tags being animated you will see the paint times are drastically s
horter for the CSS background-images.
shareedit
answered Jan 11 '13 at 21:21
community wiki
eivers88
add a comment
up vote
5
down vote
There's another reason! If you have a responsive design and want to split usage
of low, medium, and high-res images for devices through media queries, you shoul
d use backgrounds as well.
shareedit
answered Jan 28 '13 at 13:44
community wiki
Maarten
1
maarten, terscheling is not Pipeable I heard from Vincent willems. So how do you
think it can work on PyMol
Mehdi Nellen Aug 27 '14 at 10:24
1
Please refer to the documentation as to how pipeable it is pieterpeitshoeve.nl/r
ondleiding
Maarten Aug 28 '14 at 11:02
1
can you have a look on telegram for pylol
Mehdi Nellen Aug 28 '14 at 11:07
add a comment
up vote
4
down vote
Just a small one to add, you should use the img tag if you want users to be able
to 'right click' and 'save-image'/'save-picture', so if you intend to provide t
he image as a resource for others.
Using background image will (as far as I'm aware on most browsers) disable the o
ption to save the image directly.
shareedit
answered Nov 21 '11 at 12:52

community wiki
dougajmcdonald
add a comment
up vote
4
down vote
A small input, I have had problems with responsive images slowing down the rende
ring on iphone for up to a minute, even with small images:
<!-- Was super slow -->
<div class="stuff">
<img src=".." width="100%" />
</div>
But when switching to using background images the problem went away, this is onl
y viable if targeting newer browsers.
shareedit
answered Sep 6 '13 at 6:56
community wiki
winthers
show 2 more comments
up vote
2
down vote
You can use IMG tags if you want the images to be fluid and scale to different s
creen sizes. For me these images are mostly part of the content. For most elemen
ts that are not part of the content, I use CSS sprites to keep the download size
minimal unless I really want to animate icons etc.
shareedit
answered May 5 '12 at 3:23
community wiki
shingokko
add a comment
up vote
2
down vote
I use image instead of background-image when i want to make them 100% stretchabl
e which supported in most browsers.
shareedit
answered Jan 14 '13 at 16:49
community wiki
max
add a comment
up vote
2
down vote
If you want to add an image only for the special content on the page or for only
one page the you should use IMG tag and if you want to put image on more than o
ne pages then you should use CSS Background Image.
shareedit
answered Apr 27 '13 at 19:52
community wiki
Vishal Gupta

add a comment
up vote
2
down vote
HTML is for content and CSS is for design. Is the image necessary and does it ne
ed to be picked up by screen readers? If the answer is yes, then put the image i
n the HTML. If it is purely for styling, then you can use the background-image p
roperty in CSS to inject the image. Just as a lot of people here have already me
ntioned, you can then use a pseudo element on the image if you like.
shareedit
answered Feb 15 '14 at 5:03
community wiki
carltonstith
add a comment
up vote
1
down vote
Another background-image PRO: Background-images for <ul>/<ol> lists.
Use background images if they are part of the overall-design and are repeated on
multiple pages. Preferably in background sprite form for optimization.
Use tags for all images that are not part of the overall design, and are most li
kely placed once, like specific images for articles, people, and important image
s that deserve to be added to google images.
** The only repeated image that I enclose in a <img> tag is the site/company log
o. Because people tend to click it to go to the homepage, thus you wrap it with
an <a> tag.
shareedit
answered Mar 3 '14 at 22:28
community wiki
Gillian Lo Wong
add a comment
up vote
1
down vote
IMG load first because the src is in the html file itself whereas in the case of
background-image the source is mentioned in stylesheet so the image loads after
the stylesheet loaded, delaying the loading of the webpage.
shareedit
answered Apr 10 '14 at 13:34
community wiki
Sagi_Avinash_Varma
show 1 more comment
up vote
1
down vote
Also note that most search engine spiders don't index CSS background images ther
efore the background images will be ignored and you won't be able to get any tra
ffic from search engines (no SEO benefit in short).
Where as all images defined with tags are indexed (unless manually excluded) and
can bring in traffic from search engines if their title/alt attributes and file

names are optimized properly (w.r.t some keyword).


shareedit
answered Apr 16 '14 at 8:39
community wiki
Nadeem Khan
add a comment
1 2 next
protected by Josh Crozier Feb 20 '14 at 0:23
Thank you for your interest in this question. Because it has attracted low-quali
ty answers, posting an answer now requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead?
Not the answer you're looking for?
Browse other questions tagged html css i
mage background-image or ask your own question.
asked
6 years ago
viewed
171489 times
active
7 months ago
Blog
Welcome, Nicolas Chabanovsky and Stack Overflow in Russian!
Hot Meta Posts
4 Should I be more lenient in approving suggested edits to community wikis?
22 What happens to tumbleweed badge when question is deleted
22 OP posted code in comment => User brought it to question via edit
Looking for a job?
Systems Developer - Native in JAVA
Casumo
Ta' Xbiex, Malta / remote / relocation
javasql
Software Engineer (All Levels)
National Instruments Roman
Cluj-Napoca, Romania / relocation
cc++
Software Engineer for IoT Performance Optimization
Intel
Bucharest, Romania
c++multithreading
Mobile Apps Developer - Android - $15/hr
Crossover
Bucharest, Romania / remote
androidjava
Linked
3 Follow up to background-image vs img tag
4 Which is a better way to create circular buttons: <img>, or background-image?
-2 Standard compliant and/or best practice way to display an image in html/css
0 HTML <img> or CSS background-image? Which to choose?

3 What is the advantage of using background image


c <img> to create image with link?
0 What are the differences in dynamically setting
an img tag?
0 Img Tag vs Div Background
0 Background images vs. <img> tags in sliders
9 Element with CSS display: none; breaking layout
12 Background instead of inline images for mobile
s?
see more linked questions
Related

in a div instead of the classi


a background-image or creating

- causing misalignment
optimization with media querie

148 CSS Display an Image Resized and Cropped


1206 How to give text or an image a transparent background using CSS?
358 Is embedding background image data into CSS as Base64 good or bad practice?
639 Is it possible to combine a background image and CSS3 gradients?
0 HTML img vs CSS backround-image for language flags
6 CSS Background Image Not Displaying
1 CSS background-image and image of html img tag
1 Can you set a background image to an image?
3 css background-image callback without using img element
0 HTML <img> or CSS background-image? Which to choose?
Hot Network Questions
How to display a selectlist in the title portion of a pageblock
I have been asked to complete a project without any concrete specifications
What are the advantages of squawking 7700?
Has a non-carbon-based form of life been discovered since 2010?
Why is executing Java code in comments allowed?
When "How To Ask" is too subtle
Why (and since when) is the name "Sol" used instead of "The Sun"?
Difficult Intermediate Value Theorem Problem- two roots
On adding sugar to water, does the entropy increase or decrease?
What's the safest way to protect your valuable belongings from robbery at the be
ach?
How can I intuitively understand gravity assists?
Is it grammatically correct to say or to write "some brain"?
How do native speakers 'guess' the pronunciation of the letters in a word they s
ee for the first time?
What does the arrow on VCC in a BJT bias circuit mean?
How to help students remember Half vs. Whole rests
How do I prevent a folder inside of /tmp from being cleaned up?
Why do we need coordinate-free descriptions?
What careers not requiring an academic degree might be open to a self-learner wh
o wants to do research on pure mathematics?
When using && and sudo on the first command, is the second command run as sudo t
oo?
Tax deductions on empty property
How can I close $messages.registerWarning in Tridion 2013 SP1?
A word for when you are almost crying, but not quite yet?
xkcd-Style Page Numbering
Is it okay to ask for respect from interviewer?
tour help blog chat data legal privacy policy work here advertising info mobile
contact us feedback
TECHNOLOGY
LIFE / ARTS
CULTURE / RECREATION
SCIENCE OTHER
Stack Overflow
Server Fault
Super User
Web Applications
Ask Ubuntu

Webmasters
Game Development
TeX - LaTeX
Programmers
Unix & Linux
Ask Different (Apple)
WordPress Development
Geographic Information Systems
Electrical Engineering
Android Enthusiasts
Information Security
Database Administrators
Drupal Answers
SharePoint
User Experience
Mathematica
Salesforce
more (14)
Photography
Science Fiction & Fantasy
Graphic Design
Seasoned Advice (cooking)
Home Improvement
Personal Finance & Money
Academia
more (10)
English Language & Usage
Skeptics
Mi Yodeya (Judaism)
Travel
Christianity
Arqade (gaming)
Bicycles
Role-playing Games
more (21)
Mathematics
Cross Validated (stats)
Theoretical Computer Science
Physics
MathOverflow
more (7)
Stack Apps
Meta Stack Exchange
Area 51
Stack Overflow Careers
site design / logo 2015 stack exchange inc; user contributions licensed under cc
by-sa 3.0 with attribution required
rev 2015.6.12.2653

Вам также может понравиться