2

For a while I was stumped my centered background images were not pixel-perfect aligned in their containers. I even got different results within the same browser but different windows

Finally I found out what is happening, but I'm still short of a robust cross-browser solution.

The case: I'm working on a collapsable tree-view in javascript. Everything is functioning alright, but in some cases the collapse/expand buttons are off one pixel to the left.

The images for these buttons are user-definable, as well as the size (width) of the container they appear in. The images are drawn in the center of these containers with background-position: center center;. Now there are cases the image can't be fit exactly in the center of the container (for example, centering a 9px image in a 20px container, there's a 1-pixel difference on either side). This should be no problem, as long as we have consistent behaviour on how the browser handles this.

But here's where it gets messy: I've implemented this tree-view inside a wrapper centered with margin:0 auto; based on the browsers viewport. And here is when I get different results when both the viewport centering and background centering don't fit exactly within the pixel boundaries.

This is probably hard to follow, so I've squeezed the problem into a fiddle: http://jsfiddle.net/3y65wgu8/1/

CSS:

#wrapper1 {
    width:400px;
}
#inner1 { /* perfect center */
    margin:0 auto;
    width:200px; 
    height:50px;
}
#wrapper2 {
    width:399px;
}
#inner2 { /* 1px-offcenter */
    margin:0 auto;
    width:200px; 
    height:50px;
}
#container { /* image 1px-offcenter (9px centered in 12px container) */
    width:12px; 
    height:12px;
    background:url(data:image/gif;base64,R0lGODlhCQAJALMAANLNve/s58a7rd7Vznuatf////f39wAAALXD1vfz7+fj3tbTxsa6pdbPxt7b0sa2pSH5BAAAAAAALAAAAAAJAAkAAAQoEJFJiSw4l6mxmUYYJgp4nKczJUngKsOkOMOyNMAECALDPAJLhYKIAAA7) no-repeat center center #444;
}

HTML:

<div id="wrapper1">
    <div id="inner1">
        <div id="container"></div>
    </div>
</div>
<div id="wrapper2">
    <div id="inner2">
        <div id="container"></div>
    </div>
</div>

Two different wrappers centering their content, containing two identical containers having a small button drawn as background. Chrome seems to be the only browser that draws the buttons in alignment consistently, but firefox and IE show the problem I described. Try resizing your browser window, and see the buttons bounce from one side to the other.

My question is: how can I get at least identical results, without losing flexibility on button/container/wrapper sizing and styling.

EDIT: Here's a picture that illustrates my use-case:

Example

The area marked in blue is the container that holds the collapse button. This area is always square, but may vary in size. The button can be any image smaller than this container and is placed directly on top where the lines meet. No stretching or scaling should occur on the image. In this example the button is too far to the left. Resizing my browser window makes the image jump in and out of correct alignment, as the fiddle above describes.

3
  • Is the container for the image a fixed size? If so, then if you store metadata for the image in a database (e.g. location, caption) then perhaps you could also store the image dimensions. Given the image dimensions, you can calculate, server-side (Math.Floor), an integer value for the desired offset for background-position for each image, and then you will not be at the mercy of the browser's undesired rounding. Sep 27, 2014 at 21:48
  • @AndrewMorton no it isn't, the appearance of the treeview is largely customizable and can virtually be any size. However this container is always square. The size of the image is also variable. Fetching the image's metadata and use those should work in most cases, but I feel there must be a simpler solution :) Sep 27, 2014 at 23:30
  • While adding a JsFiddle is nice, please also do post the relevant code section within the question. JsFiddle could stop working one day, and a question should remain understandable without external resources.
    – k0pernikus
    Sep 28, 2014 at 2:03

2 Answers 2

1

There seems to be no way around this than to resize the image container when the image inside can't be centered pixel-perfect, to have consistent cross-browser behaviour on the positioning. Therefore I need to fetch the image meta-data either server-side or client-side.

Server-side (1): Using getimagesize and getimagesizefromstring and was obviously the way to go. But then I bumped into a problem in my current use-case: the tree is rendered using AJAX, and the relative URL for the image is not relative to the location of the AJAX script.

Issues: So, for this to work I either have to pass both URL and absolute PATH (or absolute path alone, and have the URL figured out by stripping $_SERVER['DOCUMENT_ROOT'] from it). This approach seems counter-intuitive and restrictive on the developer's part trying to implement this tree module. So I abandoned this idea.

Server-side (2): Ask for the image dimensions at design time. Plain and simple, place the responsibility at the implementer.

Issues: Not very elegant, but it works :). (solution 1)

Client-side: I've but both images inside a hidden DIV, and I fetch the size of the image from the onload event. If by this data the images used inside the containers appear off-center ( image.width%2 != container.width%2 , image.height%2 != container.height%2 ), I loop through these containers and resize them by one pixel in either width or height.

Issues: I don't like the idea of using hidden elements with triggers for the sole purpose of working around this positioning problem. However, it provides a solid cross-browser solution. The only downside is that there seems to be a slight delay before the images 'snap in position' (at least in FireFox). The obvious solution for this is to have the containers show the images after resizing the container. (solution 2)

1
  • Thanks for posting a solution to this difficult problem:) I tried several other CSS centering methods using display:table, display:inline-block, floating, and absolute positioning, and the 1px drift was still there, or it borked in IE9 or under. Oct 19, 2014 at 23:51
0

This may be worth a quick try. When inspecting the Fiddle, I noticed that #wrapper1 had a width of 400px and #wrapper2 had a width of 399px. I changed the width of #wrapper2 to 400px for consistency.

I added background-size:cover; to the button because the button image appears to be a different size than its container. Give this a try and see what you think.

If you need to keep #wrapper2 at 399px, then change the background position in the code below to background-position:top left; while using background-size:cover;.

Another option for your current code would be to make the background image the same size as its 12px by 12px container, use background-position:top left;, and remove the background color. When creating button backgrounds, its helpful if the background is the same size as its container.

Note: You could also use CSS styles to create the button look on the div, and not use an image.


#wrapper1 {width:400px;}
#wrapper2 {width:400px;}
#container {
width:12px;
height:12px;
background-repeat:no-repeat;
background-position:center center;
background-size:cover;
-webkit-background-size:cover;
-moz-background-size:cover;
-o-background-size:cover;
background-image:url(data:image/gif;base64,R0lGODlhCQAJALMAANLNve/s58a7rd7Vznuatf////f39wAAALXD1vfz7+fj3tbTxsa6pdbPxt7b0sa2pSH5BAAAAAAALAAAAAAJAAkAAAQoEJFJiSw4l6mxmUYYJgp4nKczJUngKsOkOMOyNMAECALDPAJLhYKIAAA7);
}
2
  • I used the 400px div and the 399px div as an example of perfect-center and 1px-offcenter behaviour, to show both scenarios at once. For 400px/399px in the example, you should consider this your browser window, which can be of course be any size. cover is also unpreferable, as it stretches the image to fill the entire container, where I just want the image to appear in the middle in original size. This image is user-provided. I'll update my question to clearify. Sep 27, 2014 at 22:51
  • Thanks for the clarification. I tried several other methods including shrink wrapping the div and sizing with padding, and the drift still occurred when an odd sized pixel image (9px) is within an even sized (12px) container. Is there a way to make the container an odd, or even size to match the image (ex: 9px-9px image in a 13px-13px container)? Another option where you may have more styling control is to insert the physical image using CSS #container:before {content:url(data:image/gif;...); This is an interesting question, so please post if you find your own solution. Sep 29, 2014 at 19:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.