CSS: Using Percentages in Background-Image

Last week you might have noticed we’re trialling a new experimental screen gadget in our books section — a JavaScript-powered book that allows you to thumb through the book to get a quick sense of the layout and feel.

While I might talk about that directly later, I thought I’d share some of my research on CSS background images along the way.

Like a lot of CSS/JS based animation these days, I used ‘CSS: Using Percentages in Background-Image

‘ — a large background-image containing all the frames, with background-position used to control which frame (or animation cell) is being displayed. Each click moves the background position exactly one frame down. The key advantage to using one image is you can guarantee all frames will be cached the moment your animation is ready.

There are three viable methods available to control background-position, and you are not allowed mix and match them (i.e. background-position: top 50%;).

1) Keywords : i.e. background-position: top right

Keywords are probably the most commonly used method, because they are really easy to get your head around and they work totally reliably on all browsers. You don’t even had to worry about their ordering — ‘top right’ works just as well as ‘right top’.

The main down side to keyword positioning is their lack of granularity. Three vertical (top, center, bottom) and three horizontal (left, center, right) gives you an absolute maximum of nine frame positions. There can be no ‘top centerish‘ or ‘right and a bit‘. Additionally, keywords can’t easily be manipulated mathematically like the other two numerical positioning methods.

CSS: Using Percentages in Background-Image
2) Pixels : i.e. background-position: 0px 0px

Pixel positioning is currently probably the most useful method available. Firstly, the concept is easy to understand. Once we know we are always measuring from the top left corner of both the container and the image, it isn’t hard to predict exactly where a graphic will appear before it renders.

Pixels also lend themselves nicely to be manipulated by maths. In fact, if you have a looping animation (like the book animation), you can let your sprite graphic tile and simply move your background one ‘frame height’ each cycle. When the animation reaches the last frame, the tiling will automatically present the first frame and the loop automatically begins again.

3) Percentages : i.e. background-position: 80% 50%

Percentages are great in theory, but despite there being some very good explanations of it’s subtleties out there, I get the impression they (percentages) are not well understood. I certainly didn’t.

Percentages appear at first glance to have a lot of promise as they can be manipulated easily with maths and have no practical limits on the number of positions (i.e. frames) they can display. The idea that really got me interested in using them was their ability to allow you to resize your images without having to rewrite all your pixel positioning settings — 20% is 20% regardless of your image dimensions. Theoretically you should be able to give your script an image, tell it how many frames it has, and it will work out the rest.

CSS: Using Percentages in Background-Image
It all sounded great in theory, but some quick testing confounded me. While 0%, 50% and 100% gave me the equivalents of ‘top’, ‘center’ and ‘right’, percentages like 37%, 61% and 88% seemed to veer around crazily.

The key to understanding percentages in background images is understanding that unlike pixel settings, it’s reference point moves. Any percentage refers to a percentage position on the graphic AND on the containing object.

So, when we set a background image at ‘10% 10%’, we are aligning a point on our graphic 10% across and down from it’s top left corner with a point on our HTML element 10% across and down from it’s top left corner.

I must admit this threw me at first but I drew this diagram to help explain it to myself.

This means in practice, if your graphic is the same size as your HTML element, changing the percentage will make no difference whatsoever. ‘0%’ will be identical to ‘73.5%’ and 100%.

Even when you understand the general concept it’s still not particularly intuitive. What happens if you give something a 150% X-position? It’s harder for most of us to imagine the result.

CSS: Using Percentages in Background-Image
What about if you have a four frame vertical sprite? What would it’s four Y-positions be?

I started guessing that 25% and 75% must be in the mix, but, as you can see in this test case, the four vertical frame positions are set at thirds — 0%, 33.333%, 66.666% and 100%.

Ok,.. so it’s a little strange, but once you’ve got your head around it, it should be really useful, right?

CSS: Using Percentages in Background-Image
In theory, yes, but the reality is not so hopeful. Honestly, I’m so bored with whining about IE but this is really crappy.

As far as I can tell, both IE6 and IE7 (presumably earlier versions too) have some kind of rounding error which effectively kills using percentages with this type of sprite-based work. Simple percentages like 0%, 50% and 100% are fully reliable, but ultimately no more useful than top/center/bottom.

More complex percentages appear to be a raffle. The error is small, but more than enough to ruin an animation by forcing it off center — looped animations will multiply this error on each pass. Attempting to predict the error and compensate for it in IE also proved impossible, and I can’t imagine any other solution but to stick with pixel positioning

Suffice to say, very frustrating stuff. Insert ‘rolling my eyes emoticon’ here.


Category: javascript Time: 2007-07-05 Views: 3

Related post

  • How can I use HTML/CSS to add a background image to an email? 2010-10-12

    I've been trying to get background images working in my Email HTML and have had no luck. I'm using Outlook 2007 to test my HTML code. My method is: Create my .htm file Save it in %appdata%\Microsoft\Signatures Create a New email and set that HTM file

  • Use the_post_thumbnail as background image in LESS CSS 2013-09-20

    I'm trying to use the_post_thumbnail featured image as the background image to a div container within a page template file. I'm using LESS CSS and wondered if it was possible to pass in a Wordpress tag to the LESS file or use PHP in anyway? If not, I

  • How to access an image in an array to CSS? .post-title { background-image: url(img[0].src); } 2016-01-16

    How to correct below code? .post-title { background-image: url(img[0].src); } I'm using this code in blogger to create a snippet and img[0].src doesn't work in CSS. How can I access the image in this array for CSS?

  • Using 4096*4096 background image in uinty tk2d 2013-03-20

    I am new to Unity and I am developing a game using unity its a 2d game i am using tk2d framework. I have a big background image(4096*4096) how can I load this background so only visible part of the background has to be rendered so it wont effect the

  • use jpg as background image 2015-12-08

    I am trying to install a custom background image on my xfce desktop. When I browse for the image the file is grayed out regardless of what I do. I trier to chmod it to my username, place it in /usr/share/background/ - nothing helped. How can I use my

  • How do I extract a portion of an image in canvas and use it as background image for a div? 2016-01-27

    This is how my code looks: document.addEventListener('DOMContentLoaded', function () { var canvas = document.querySelector('canvas'); var ctx = canvas.getContext("2d"); var imageData = ctx.getImageData(0, 0, 300, 300); var tile = { 'id': 1, 'dat

  • store image src in a js variable so that it can be used to display background image 2016-01-16

    How to store image src of the above image tag in a javascript variable? <img class="preview" alt="Styling with a Bandana" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover="upDate(this)&q

  • css: why does my background images jump when hovering? 2016-01-16

    I would have supposed that if I give each item a fixed size and hide the underline with some margin, and then I take that margin away, it should work without issues. But it still seems to hop whenever I hover it. Please help me understand why. https:

  • Use two different background images, one in odd pages and the other on even pages? 2014-08-10

    I would like to know if there is a code on preambule wich allows me to alternate 2 images, placing one of them as background on even numbered pages, and the other one the odd numbered pages. Actually I have one image for every page. I'm using in my p

  • CSS Background Image 2014-11-07

    I currently have a <div> in the page layout that has this hero image set as the background, making a nice banner across each page. I would like this banner to be unique for each page without having to crack open Visual Studio. I was hoping to have p

  • How to fadeOut/In background-image using JavaScript? 2016-01-25

    I'm trying to fadeOut/In the background-image property of body using the following code: var main = function() { var currentPath = 0; var MudaCenario = function(){ var paths = ["url('res/teatro1.jpg')", "url('res/teatro2.jpg')", "

  • Changing a background image of body (in CSS) depending on the season (Current Calendar Month) 2016-01-28

    I'd like to change my HTML background depending on the date, but what I've written isn't working properly. I can't find any applicable examples and I'm struggling to complete it. I just want the start of a new season to change the background of my HT

  • Css background image position animates 2016-02-14

    I am trying to make a menu that has background images that are attached an a:hover. I have different size menu links, so I figured I could have part of the image aligned left the other aligned right, and a center image that can stretch, When I apply

  • Change background image per page 2014-01-16

    I would like to have a different background image as per PAGE (category) When the user goes to the home.php, call it A, it shall have a background image, then if I send them to a page B, I would like the background image to change. Can anyone steer m

  • How to let admin upload background image for view page and webform page? 2015-04-10

    I would like admin to upload background image for each and every different pages in my drupal 7 site. For normal content type like basic page, BackgroundField module works perfectly where admin can upload images in the file field. But in webform page

  • When is background-image not wrapped in: url(); 2015-07-28

    In CSS you declare a background-image by wrapping it inside a url('') ... is there an example when you don't need do this and if not why does it even exist? Even when you're using base64 you still wrap it in a url and I can't seem to find a reasoning

  • Struggling to set position on my background image 2016-01-24

    i was doing for my project regarding my portfolio. I was started coding for the layout and place some navigation bar, images, headers etc. I was placing the ship image in the content background. But when i place the slideshow in the content, the ship

  • How can I make my background image be fully seen on a page 2016-02-02

    I'm trying to put a background image in the center of the page, but the image goes out of the page and seen only partially. This is my css code: body{background-image:url(../img/music_palace_logo2.png); background-repeat:no-repeat; background-positio

  • div onclick function to change body background image 2016-02-14

    I want a small picture that acts like a button, to be click-able with a function to change the body background-image. I am a total newbie and I'm trying to learn. The most simple way, I thought, would be to have a div with a background-image. I have

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C) avrocks.com, All Rights Reserved.

processed in 1.378 (s). 13 q(s)