How bad is to store all background images in CSS? - css

I have created the layout of the website (template). I used Photoshop to design the picture and sliced it to create the divs. It gave me an HTML file including the HTML and CSS code. I separated these in two files HTML and CSS. The background images were being called inside the <div id="idName"> tags as <img src=... tags. I changed this. I loaded the images in the CSS file as
idName { background-image: url(URL); }
All the images in the site are loaded like this creating the background as a whole.
Now my question is: Is this a bad practice? because if I leave the images inside the <div> tags I wont be able to put my content on top of the image. With the background-image attribute in the css file I can put my content anywhere, not having to worry about the background.

No, this is perfectly fine, and actually may be a best practice for background images. Moving the image declarations into the style sheet means the images may be downloaded a little bit later, but most browsers should have enough other resources to load in the meantime, and you'll want prioritize HTML and stylesheets before background images anyways.
Just don't use CSS backgrounds for actual images: If the fallback background color would significantly change the meaning (i.e. the image is content), you should use <img> elements with an alt= attribute. If you're not sure whether this is a good idea, consider this question.
To increase performance (by reducing the number of HTTP requests), you may want to consider using CSS sprites.

Related

responsive image inside svg

TL;DR: Is it possible to load other images based on media-query from svg included via img tag?
I generate a bunch of svg files with have tables with text and icons inside. A PDF would be semantically a better container, but I need to keep such "documents" as images for seamless embed/preview and it probably won't solve my problem. So the story is about icons.
I wrote inline styles with media queries picking icons corresponding to user's screen DPI. Icons are already bundled into sprites, so I use pattern/image[xlink:href] + fill:url(#id). Everything works as needed when I embed svg directly into HTML (DOM islands). But if I embed svg via img tag (i.e. <img src="foo.svg">), it doesn't load icons at all, let alone showing them.
I understand, that I can embed icons via data-URL, but embedding icons for all supported screen dpis seems too much. The irony is that icons are raster ones, hardly vectorizable pixel-art, so I cannot have one set of icons for all DPIs.
Is there a way to have proper icons picked by media query w/o embedding them all?
You can't load external files from an SVG used in an <img> tag (or used in other "image" contexts, like CSS background images). For security and performance reasons, SVG used as image has to behave like any other image -- a single file, no secondary resources and no scripts.
If you don't want to use inline SVG, you might consider embedding an SVG file with an <object> tag or <iframe>. However, I recommend that you actually test carefully to see whether browsers are downloading the image files even if they aren't using them because of CSS.
So since it's not possible to load conditionally: either embed or not, I should do some clever detection about raster sets. Technically not a direct answer, but in case someone needs.
I decided to go with cookies. People visit normally the same site that hosts those SVG.
I'd set a cookie for their DPI and then all SVGs served would pick proper DPI images.
For people who haven't visited the site yet, I'd go with UA sniffing: mobiles and macs get 2x, others 1x. Or just 1x for everyone.

Why put images in the background instead of using the native <img> element?

I am a newby to design and looking now into the use of background instead of foreground images, which is a common practice.
I look at the techniques used, and see that:
you usually need to explicitly state the dimensions of the image (and set the foreground element to these dimensions)
you need to make the foreground element to somehow disappear with css tricks.
All this looks really hackish. So, I wonder, why on earth do all this instead of just using the native element? I am sure there is a good answer
(I did go through this When to use IMG vs. CSS background-image? , and could not figure out a clear answer)
One thing to consider as a benefit to using CSS for images is that you can load all your design images (images for UI elements, etc) with one http request rather than an http request for each individual image using a sprite. One large image that contains a grid of all your images.
As its been stated before, content images should use the img tag which also helps for people using various accessibility options when visiting your site/app. For example, if they are using a screenreader, the screenreader knows its an image and can read the img alt name or title, but if its just a div with a background image they get nothing.
The main difference is that in the img tag the image is hardcoded.
With CSS you can create different designs, switch between them, redesign the page, without altering the source code. To see the power of CSS, check http://www.csszengarden.com/, all the pages use the same HTML source, but with different CSS layout.
As #Shmiddty noted, if img is for embedded images (actual content, for example a gallery, or a picture for an article), and CSS is for design.
Also, the question you referred to, has nice list of all the use-cases: When to use CSS background-image.
The goal is to separate content from presentation. HTML should contain just content, and all presentation should be moved to the CSS. Once you achieve that, you gain a few useful side effects:
The CSS (presentational code) is cached by the user's browser, and each HTML file requested is smaller. This also has some SEO benefits (decreased code fluff).
Screen readers have to muddle through less when interpreting your page for visually impaired users. Making sure your HTML contains just content means visually impaired users reach what they're looking for much quicker.
CSS makes it possible to display the same content in different visual configurations, which is the cornerstone of the responsive web design movement. Properly delineating your content and presentation means being able to use the same HTML files across multiple platforms (desktop, tablet, smartphone).
However, there are times when images are content on a specific page. In those cases, you want to use an IMG tag, and moving the image to the CSS is actually a wrong move. A great discussion of when and where to use text to image replacement is at When to use IMG vs. CSS background-image? Basically, my personal litmus test is something like: Is this image going to be used multiple times on the site? If it is, it's probably part of the design. Once-off images are generally content.
If you're looking to move your design images to the CSS, congratulations :-p You've adopted a healthy amount of work, but started doing something worthwhile to the long-term health of your website as part of the web ecosystem. I would highly recommend looking into using the SASS/Compass system to manage your design images as sprites (see A List Apart:CSS Sprites and Spriting with Compass).
One of the main points of image replacement is to use your site title in a h1 tag for good SEO, and then hiding the text and replacing it with a custom logo.
This also makes your site more accessible. Say for example, your user has CSS disabled for whatever reason (screenreaders, maybe). They would still see the textual representation of your site title, whereas normal users would see the custom graphic.

Most efficient position for background-image property in a style sheet

I am placing a large, non-repeating background image on my website using the CSS background property. Since the image is so large, it takes a long time for some connections to render the image.
Here is my CSS:
#wrapper {
background: url('large-image.jpg) no-repeat center center;
}
I have already done the following to optimize the image for the web:
Reduced it to the lowest possible resolution that does not compromise quality
Changed the image type from a PNG to a JPEG
Styled the page so that the content is readable even without the background image
My question: To further optimize the image loading time, would it make a difference if I put the background tag at the bottom of my style sheet? Or would the effect of this be negligible?
I tend to order my CSS by the hierarchy of my HTML, so the #wrapper styles are at the top of my style sheet. Does the order of properties in a style sheet make a noticeable impact on load time when the user has a slower connection?
Location in the stylesheet will not affect the load time.
What you can do though is prevent it loading in some cases, such as on a cellphone.
For reference:
http://css-tricks.com/snippets/css/media-queries-for-standard-devices/
Those media queries aren't fail-proof, but they'll catch alot of the slower cases, which would generally be mobile devices. On the other hand, if somebody is on a 56k modem with their desktop, I just don't know what to do about it (maybe they're used to it).
You can use Jquery and waitforimages to ensure it loads after all other images, if you wish.
What could affect perceived loading time is initial #wrapper availability - i.e. if at the time of the initial load it is not part of the page and is added with JS, the background image will not begin loading - but I doubt this would be a common scenario.
Background image loading does not affect domready handlers, however if you want to speed up background availability you could try the following:
#wrapper {
background: url(large-image.png) no-repeat center center,
url(small-image.png) no-repeat center center;
}
From mdn:
With CSS3, you can apply multiple backgrounds to elements. These are
layered atop one another with the first background you provide on top
and the last background listed in the back. Only the last background
can include a background color.
What this does is effectively allows you to load a lower-res image as the bottom layer of the background, while the expensive hi-res image is still loading. Remember the good old times of lowsrc? That's the behaviour we're simulating. Note that both the low- and the hi-res image downloads begin simultaneously, so use this only if the large image is truly unbearably large.
Also: you're saying you've optimized the image; I still suggest you try Yahoo SmushIt, you'd be surprised how muich redundant data can be stripped from a PNG witout loss of quality (I currently have intermittent problems using their service, but it works after a few attempts, alternatively you could use OptiPNG but imo it would be too much effort to set it up and configure for a single image)
Update:
It has been suggested you wait for domready to fire and add your style using $("#wrapper").css(...);. What that does is add inline styling to an element, which would 1) interfere with selector specificity 2) only apply to this particular instance of #wrapper (bad if, say, it is part of ajax content coming from the server).
You could alternatively add a new css rule at runtime:
$('head').append('<style type="text/css">#wrapper {background: url(large-image.jpg) no-repeat center center;}</style>');
This would be organically added to document stylesheets and apply to all future instances of #wrapper, as well as not interfere with selector specificity. You still end up with a brief flash of unstyled content (before the handler is fired and the style is applied) so I don't advocate this approach.
See this previous question. The CSS stylesheet will be fully loaded and evaluated before the page is shown, so the location of your background-image CSS does not matter in the stylesheet.
If you want the image to only load once the rest of the content is displayed you could use jQuery:
$(window).load(function(){
$("#wrapper").css({'background-image':'url("large-image.jpg")', 'background-repeat':'no-repeat', 'background-position':'center center'});
});

How do you add a background image for printing in IE/FF?

In other topics I've found that IE/FF doesn't print background images by default. Now that's a shame, because background images add some possibilities that are very difficult to reproduce with classical <img> tags:
You can align them both horizontally and vertically
You can crop them if they are larger than the target element (which also enables the idea of CSS sprites)
Now, it's not impossible to do, but it will require me to have different HTML layouts for printing and normal page, and the printing layout will be quite overcomplicated (since I'll have to use <table>s to achieve vertical alignment). Also, the benefits of CSS sprites will be lost.
Is there any hope? I gather that #media print doesn't help, but isn't there something else, maybe browser-specific, that would allow one to say: "Yes, this isn't a normal background, it really needs to be there even in print view"?
Not possible. You would have to some how convert your background images to img or use Canvas. Of course using canvas depends on which IE you supporting.
Its a browser setting which restricts the printing of background images. I think the logic behind it was that the vendors wanted to give the users the option of printing background images and ensure that the web developer could not alter these settings through some sort of script.
As a general rule, background images should be reserved for adding to the page design but aren't essential to understanding the content. Therefore it shouldn't matter if they are missing when the page is printed. If something (such as a product shot) is important, then it should be included as an actual image (which has the added bonus of being more accessible).
Could you look at including the image, then hiding it using CSS and duplicating is as a background image (perhaps dynamically using JS)? That way, you can ensure the image itself shows in your print stylesheet, and you get the benefits that having a background image brings. I've created a very simple example here.

CSS - using one background image with multiple images on it

I've observed that often the websites use only one background image which contains multiple images on it. For example, instead of using separately icons, all of the icons are put on one image and then the different parts of image are used in different section.
Is there any advantage to this?
How can this be used?
For example, for the following Stack Overflow sprite, how would I display just one of the images?
The technique is called CSS Sprites. Basically you use CSS's background-position property and fixed height or width for your element.
If your elemnts are fixed width and fixed height at the same time you can freely create a more compact image. See this site for more complex examples.
You are talking about CSS sprites, in which the background position changes on hover. Learn more here:
http://css-tricks.com/css-sprites/
Change the css property background-position.
yes , using sprites is good for website performs because every single component on website send different http request .So, when we use sprites images the http request become less & website performance increase.That rule is also apply on css also less css files less http request. you can yourself with the help of safari web inspector.
for more better performance download "yslow"
And with CSS sprites is also possible to make e.g. menu button hover effect without waiting until second image loads. see
It has the advantage that only one image needs to be loaded so that things like hover (roll-over) effects are faster. The technique is usually called "CSS sprites". Google for it.
It has been common for a while to put two images on one sprite sheet, but the tendency has been moving towards combining ALL of your background images on the same sprite sheet to load just one file for all of them. There's a rather good tutorial here.

Resources