I’m currently working on porting Finicky over to HTML5 as a training exercise for building real applications (as opposed to more demoware) with HTML5 for mobile. It’s going fairly well, but there was one piece of UI that I was really worried about. It was a little complicated to render in ActionScript, and I feared it might be impossible in HTML. In fact it’s one of the few things I found much easier.
On the edit page there is a button for prompting you to take a picture of an item that you want to save. When you haven’t taken a picture, you see a little camera icon on the button. When you have already selected an image, you see a circular mask of the picture inside a circular frame created by the button. Look at the picture; it’s a lot easier to show than to explain. My designer really did a cool job there on that piece of UI, and I wanted to replicate it.
My first instinct should have been to look up “css mask” as it would probably be the easiest way if it was implemented. I didn’t. I instead went with using border radius to shape my button into a perfect circle and positioning it on top of the original button. In reviewing information on CSS Masking, I don’t think it would be the perfect solution. The images that I’ll be using in my final product are going to come from source images of different sizes. My method allows me to drop in any size/proportioned image into the background-image CSS property of my link and have it still work as a perfect circle. However, my research there makes me want to explore CSS masks more.
Anyway, back to the main point, how did I accomplish this?
First, I make an a link that I’ll use an a as the interactive part of the UI, as well as the holder for my picture. And I’ll wrap it in a div that will hold the button graphics.
I give the containing div a background-image containing the button graphic and I hard set the size to match the image size.
Once the container is done, I turn the a link into a circle by giving it a border radius of 50% of the height and width of the element. (I also used a background-color to see where I was putting it. )
Then I set the positioning to relative, to offset it within the containing div. I then fiddled with the top and left until the circle link was pretty equidistant from all sides of the containing div. It wasn’t just straight math because the drop shadow in the graphic made the blue circle of the button not completely in the center of the png file.
Finally I made a class with the picture I wanted to place in the background-image of the button.
Couple things to note here:
- I hard coded the CSS for demonstration purposes, in my app, I’ll just add the background-image dynamically via the DOM.
- This, like all awesome things, won’t work in versions of IE earlier than 9.
- However, it has much more support than using masks, so I think it also wins on that account.
Here’s a demo with the full source.