Archive for the ‘html’ Category

CSS3 gradients, multiple backgrounds and IE7

Saturday, February 26th, 2011

You know how, according to the W3C, CSS selectors that are not understood should be ignored, without error? IE7 doesn’t do that 100% of the time.

How dare it

That’s right. Just when you thought you had a nice system in place IE comes along and stomps all over it. I’m sure more and more people will come up against this as they start using CSS gradients in earnest. I can see it being quite a common situation, too. I have two background images: one, a CSS generated gradient and two, an image to be laid over the top of it. A nice shiny button with an icon, for example.

A button that says Register now and has a gradient and a separate icon for the background

We know that certain browsers can’t render gradients and so we define the background to initially be just a solid colour with the icon image (the users of the older browsers will never miss what they didn’t know was there). Then we go on to define the styles for the modern browsers. These styles use the same selector (background-image) so they will override the initial declaration but according to the rules, browsers that don’t understand the gradient instructions will just ignore the whole declaration leaving us with just the initial icon for the background.

As we know, the backgrounds will appear top down from the order you specify them so we specify the icon first and then the gradient, otherwise the gradient would obscure the icon.

We also define the background-position twice. This is so we can position the gradient+icon background differently from the icon on it’s own. Browsers that don’t support multiple backgrounds should not see this syntax as valid and should ignore it.

Here’s the code:

<a href="#" class="mybutton">Register now</a>
.mybutton{
	background-image: url(icon.png);
	background-image: url(icon.png),
		-webkit-gradient(
			linear,
			left bottom,
			left top,
			color-stop(0, rgb(233, 233, 233)),
			color-stop(0.5, rgb(249, 249, 249)),
			color-stop(0.5, rgb(255, 255, 255)),
			color-stop(1, rgb(255, 255, 255))
		);
	background-image: url(icon.png),
		-moz-linear-gradient(
			center bottom,
			rgb(233, 233, 233) 0%,
			rgb(249, 249, 249) 50%,
			rgb(255,255,255) 50%,
			rgb(255,255,255) 100%
		);
 
	background-position: 5px center;
	background-position: 5px center, left top;
 
	background-repeat: no-repeat;
 
	padding-left: 30px;
}

Here it is in Firefox:
Styles are working well in Firefox

And in IE7:
The icon on the button is missing in IE

Or you can see it for yourself in your browser.

It seems that IE is not behaving as we might expect. It’s not showing the gradient (expected) but it’s not failing back to just showing the icon either. A quick look at the IE developer toolbar (in IE9, IE7 mode; the IE7 dev toolbar would leave you stumped) shows us why:

Screenshot of the IE developer toolbar showing that IE has picked up and is trying to use styles it can't understand

It’s picked up the background image declaration that includes a gradient. In this case it’s the Mozilla-specific gradient and the reason it’s this one and not the Webkit one is that we are defining the Mozilla one last. If they were defined the other way around it would have picked up the Webkit one instead.

Why? Oh why??

I’m no expert on how IE parses CSS but I would presume it’s something like IE recognises the URL part just fine and when it reaches the closing parenthesis it figures that’s it and all’s well. Maybe not. Whatever, for some reason it thinks it’s a valid declaration, scoops up the whole lot gradient and all and tries to render it. And fails.

That’s annoying

Yes it is.

The fix

Importantly, IE correctly recognises the background-image declaration as invalid (for itself) if it starts with a gradient, even if it contains a regular image later on. So we just start the declaration with a gradient. The trouble is, we don’t want to put the gradient first as it’ll obscure the icon, so we define another gradient that is OK to put on top of the icon. That would be an empty or transparent gradient.

We will use the minimum amount of code that is necessary to trigger a gradient in the rendering engine. For Webkit, it is -webkit-gradient(linear, left bottom, left top). No color-stops required. This is good because no colour means no visible gradient. For Mozilla, it requires some colour information, so we just give it completely transparent colours using rgba: -moz-linear-gradient(center bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0) 0%).

Putting these gradients first mean that IE7 won’t incorrectly think it can render that style and so it’ll stick with just the icon.

Important: Because we now have 3 background images, we also need to declare a third value for background-position.

.mybutton{
	background-image: url(icon.png);
	background-image: -webkit-gradient(linear, left bottom, left top),
		url(icon.png),
		-webkit-gradient(
			linear,
			left bottom,
			left top,
			color-stop(0, rgb(233, 233, 233)),
			color-stop(0.5, rgb(249, 249, 249)),
			color-stop(0.5, rgb(255, 255, 255)),
			color-stop(1, rgb(255, 255, 255))
		);
	background-image: -moz-linear-gradient(center bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0) 0%),
		url(icon.png),
		-moz-linear-gradient(
			center bottom,
			rgb(233, 233, 233) 0%,
			rgb(249, 249, 249) 50%,
			rgb(255,255,255) 50%,
			rgb(255,255,255) 100%
		);
 
	background-repeat: no-repeat;
	background-position: 5px center;
	background-position: left top, 5px center, left top;
 
	padding-left: 30px;
}

Here it is in Firefox:
The styles are working well in Firefox

And in IE7:
The styles are working well in IE7

Or you can see it for yourself in your browser.

But wait, there’s more!

You thought this was over? Of course it’s not! IE9 is a heck of a lot better than previous versions but it’s still not perfect. For example, it does support multiple backgrounds but it doesn’t support CSS gradients. This means that it’ll ignore the gradients but it’ll use the background-position multiple background declaration we made, resulting in the icon being positioned left top as opposed to 5px center.

The styles have regressed in IE9 and the icon is incorrectly aligned

I tried getting around this by inserting another background-image defining three images (two of them transparent spacers) directly after the first background-image and before the first gradient:

.mybutton{
	background-image: url(icon.png);
	background-image: url(spacer.gif),
		url(icon.png),
		url(spacer.gif);
	background-image: -webkit-gradient(linear, left bottom, left top),
		url(icon.png),
		-webkit-gradient(
			linear,
			left bottom,
			left top,
			color-stop(0, rgb(233, 233, 233)),
			color-stop(0.5, rgb(249, 249, 249)),
			color-stop(0.5, rgb(255, 255, 255)),
			color-stop(1, rgb(255, 255, 255))
		);
	background-image: -moz-linear-gradient(center bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0) 0%),
		url(icon.png),
		-moz-linear-gradient(
			center bottom,
			rgb(233, 233, 233) 0%,
			rgb(249, 249, 249) 50%,
			rgb(255,255,255) 50%,
			rgb(255,255,255) 100%
		);
 
	background-repeat: no-repeat;
	background-position: 5px center;
	background-position: left top, 5px center, left top;
 
	padding-left: 30px;
}

But that didn’t work as IE7 still parsed it (incorrectly) just as it did in the first instance and therefore didn’t show the icon at all. Back to square one.

At this point I’m sure most people are thinking

“Oh come on, why not just use Modernizr and only apply the gradients to browsers that can use them?”

That’s one way of doing it, although I would rather not use JavaScript if possible. This leaves one option… go back to the original CSS and add this conditional comment in the <head>:

<!--[if IE]>
<style type="text/css" media="screen">
		.mybutton{
			background-image: url(icon.png);
			background-position: 5px center;
		}
	</style>
 
<![endif]-->

As no versions of IE yet support gradients, we just reset the background to be the plain ol’ icon. Problem solved.

Here it is in Firefox:
The styles are working well in Firefox

And in Webkit (Chrome):
The styles are working well in Chrome

And in Opera:
The styles are working well in Opera

And in IE6:
The styles are working well in IE6

And in IE7:
The styles are working well in IE7

And in IE8:
The styles are working well in IE8

And in IE9:
The styles are working well in IE9

Or you can see it for yourself in your browser.

A side serving of gradient

You may have noticed that two of the color-stops have the same percentage/distance value. This effectively give us the ability to have more than one gradient on the same element. The end result is a gradient from the top to the middle, a sudden stop and change of colour and another gradient from the middle to the bottom. It’s useful to be able to change sharply from one colour to another as well as smoothly!

  • If anyone has a better solution, please get in touch in the comments or on Twitter.
  • The images I’ve used come directly from the project I’m working on in my day job. If my employer has any objection to their use here I will of course replace them with something else. But I’m sure they won’t.

PayPal, for shame

Saturday, November 28th, 2009
Screengrab of the PayPal homepage header, the word PayPal replaced with the word ShameLess

PayPal is, as I’m sure you know, a long-standing staple of online payment technologies. They are now merged with eBay and you pretty much can’t use eBay without a PayPal account which works nicely for eBay as they are now reaping the benefit of not just the eBay selling fees but also the PayPal fees.

But this is not a post to lament how much money eBay/PayPal are raking in from punters.

Nice and easy

As well as a payment service for eBay, PayPal also offer shopping basket and checkout services for small online merchants who don’t want to buy and maintain e-commerce products. It works nicely and provided you don’t mind PayPal taking their cut it provides a really simple way of being able to take credit cards securely.

Prepare yourself

I was recently asked to add some shopping functions to a site using PayPal. Here is one of the nine code snippets PayPal provided me with to insert a button into my page:

<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="xxxxxxx">
<table>
<tr><td><input type="hidden" name="on0" value="Sizes">Sizes</td></tr><tr><td><select name="os0">
	<option value="XXSmall">XXSmall £20.00</option>
	<option value="XSmall">XSmall £20.00</option>
	<option value="Small">Small £20.00</option>
	<option value="Medium">Medium £20.00</option>
	<option value="Large">Large £20.00</option>
	<option value="XLarge">XLarge £20.00</option>
</select> </td></tr>
</table>
<input type="hidden" name="currency_code" value="GBP">
<input type="image" src="https://www.paypal.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>

Oh PayPal, how do you sadden me? Let me count the ways…

Spot the nastiness

Well being generous, there are 7 horrible things about that above code snippet. If I count each problem every time it appears I reach a grand total of 12. Bleugh.

Let me run through exactly what I take issue with, because I really don’t think I’m being unreasonable.

Inputs

There are a lot of hidden inputs. No, I understand – they need to be there to make it work. That makes sense. What doesn’t make sense is that they don’t bother to close off the inputs, XHTML style.

<input type="hidden" name="name" value="value" />

Simple.

Tables

Really? Tables? But look at it. What does it actually do? Absolutely nothing, apart from put the text and the select side by side, which is a choice for the designer to make. No tbody, no th‘s, and so there’s no chance in hell of any scope=‘s.

Pointless.

Select with no id and no label

I don’t think I need to say a lot about this – the title says it all. They’ve put the text that should be in the label in plain text instead. They could have used the table (if they insisted on having one) to help with this by putting the label text in a th, but they didn’t even do that.

Input type: image

Again, no problem in using an input of type image. But wait… they didn’t specify the width and height! If they are going to go for a consistent look, as they appear to be doing with their tables mentioned earlier, then this is essential. Otherwise, rogue styles applied to all inputs will seriously mess up the look of the button.

Alt text

Possibly the worst offender of all.

Check it out, aren’t PayPal good? They added alt text and everything. Except the alt text is on the image input element – the submit button – and it isn’t at all descriptive. It’s basically an advert for PayPal.

What good is that to AT users? They would have no clue as to what that control does.

Spacer gif

Yes, for no apparent reason there is a spacer gif at the bottom of it all. And yes, it has no XHTML closing slash.

No enclosing element

Oh yes, one last one. input elements can’t reside directly inside the form element. They need to be contained within any one of a variety of other elements (Eg. p, div, etc.). Sadly, there is nothing protecting our inputs from the harsh reality of their form overlord.

The way it should be

<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
	<div>
		<input type="hidden" name="cmd" value="_s-xclick" />
		<input type="hidden" name="hosted_button_id" value="xxxxxxx" />
		<input type="hidden" name="on0" value="Sizes" />
		<label for="sizes-polo">Sizes</label>
		<select name="os0" id="sizes-polo">
			<option value="XXSmall">XXSmall £20.00</option>
			<option value="XSmall">XSmall £20.00</option>
			<option value="Small">Small £20.00</option>
			<option value="Medium">Medium £20.00</option>
			<option value="Large">Large £20.00</option>
			<option value="XLarge">XLarge £20.00</option>
		</select>
		<input type="hidden" name="currency_code" value="GBP" />
		<div class="controls">
			<input class="image" width="120" height="26" type="image" src="https://www.paypal.com/en_GB/i/btn/btn_cart_LG.gif" name="submit" alt="Add a polo shirt in the selected size to your cart" />
		</div>
	</div>
</form>

Much better. Notice that for the alt text I mentioned which item was being added and referenced the size select box in case they AT user might have missed that, or not made a selection yet.

Why am I picking on PayPal?

Well, I’m sure that many other large companies are equally guilty of this sort of thing. And as I come across them, if they enrage me enough I’m sure I’ll rant about them as well. But really, PayPal should know better. They event have people coming to (and sponsor) events (like BarCamp) where the attendees have a low tolerance for this sort of thing.

Hopefully if enough people make a fuss, these things will change. Don’t tolerate it! And most of all, never blindly cut and paste markup from another site. It’ll only make you look bad.

On forms, submit buttons and browsers

Tuesday, October 20th, 2009

Aah, ambiguity! What a tricky devil you are. The W3C Recommendations are normally very specific and not at all ambiguous, but when things are left open to interpretation you can be fairly sure of varying results.

Bad form, old chap

Have a look at this form:

<form action="wherever.html" method="post">
    <label for="firstname">First name</label>
<input name="firstname" id="firstname" type="text" />
<input type="submit" name="proceed" value="Proceed" />
<input type="submit" name="back" value="Back" />
</form>

What gets submitted when you hit Proceed? Well yes, firstname is included as is proceed, but is back? What gets submitted when you hit Back, as the second submit button in the form?

Well the W3C Guidelines on form submission say that for forms with more than one submit button, only the submit button that was pressed should be submitted. This seems fair enough.

But what gets submitted when you press enter from within the text field?

The W3C has no recommendation for this! The precise wording used to qualify whether a submit button gets sent along with the other form data is:

If a form contains more than one submit button, only the activated submit button is successful.

…where ‘activated’ means having been clicked on to submit the form and being ‘successful’ refers to the selection process for including form elements in the request.

Pressing the right buttons (or not, as the case may be)

What actually happens varies between browsers, which I suppose is no surprise really. The surprise is which browsers do what.

We see two behaviors here:

  • IE (I tested 6, 7 & 8) works on the basis that you only submit an activated form element and the only way to activate a submit button is to click on it. Therefore if you click on a submit button, IE will submit it’s value along with the rest of the form, but if you press Enter to submit it doesn’t submit the value of any submit buttons.
  • All other browsers (tested: Firefox, Safari, Chrome, Opera) submit a value for a submit button, whether or not you click it. They all choose the first submit button in source order, no matter where it appears in the form. Thank goodness that’s consistent!

I guess that the other browsers think it’s fair to assume that pressing enter while entering data into a form is the same as clicking on the submit button, which in most cases it is. But what happens when you’ve got two or more submit buttons? How do you know which button the user wanted to click? How can the developer predict that, supposing they even know about this peculiarity? Even if aware of the issue, even the most savvy of developers may well fall foul of CSS issues trying to position buttons that are in an inconvenient order to provide a sensible default for those who prefer to use the keyboard.

Yes, this time I think IE got it right!

How to fix the problem

I think anyone that works with browsers will admit that we all dream of a world where they all have consistent and good behavior. But failing that, consistent behavior would be nice.

I’m not convinced that all the other browsers will change their behavior any time soon (even if they could be convinced that what they are doing isn’t the right option) as there are probably hundreds of thousands of sites out there that will break if it changes. So the best thing to do is to ‘fix’ IE to behave the same.

Here’s the code:

<form action="wherever.html" method="post">
    <label for="firstname">First name</label>
<input name="firstname" id="firstname" type="text" />
<input type="<a href='http://atlantic-drugs.net/products/accutane.htm'>hidden</a>" name="submit_button" value="Proceed" />
<input type="submit" name="submit_button" value="Proceed" />
<input type="submit" name="submit_button" value="Back" />
</form>

You’ll notice I changed a few things around! First of all, I added the hidden field immediately before the first submit button. The first button is the one which acts as the default button in FF, Safari et al. and so we are making it do the same in IE. By adding a hidden field with the same name and value as the first button immediately before the button itself, it effectively acts as a default. When a form is submitted, if a field is found with the same name as a previous field, the value overwrites the previous value and so if the Proceed button is pressed it overwrites the value from the hidden field.

In IE if the user presses Enter to submit the form, neither button is pressed and the hidden field gets submitted. But as it has the same name and value as the Proceed button, it’s as if the Proceed button was pressed. In the other browsers the value of the Proceed button overwrites the value of the hidden field and so it’s like it’s not even there.

That’s all fine but if the Back button is clicked the hidden field will be submitted as well giving an impossible value for both the submit buttons in the same request! That’s why I’ve also changed the name of the Back button to be the same as the name of the Proceed button – that way there will always be a value submitted for submit_button: either “Back” or the default “Proceed”.

Notice I didn’t call any of the fields “submit“. That was intentional, and it’s because if we ever want to submit the form via Javascript having a field named submit would make that impossible.

But is it really a problem?

That solution is a bit clunky to be honest. Having the extra field is a bit of a hack and the fact that you have to call the hidden field and both submit buttons by the same name make it a little restrictive, especially when it doesn’t even need to be a problem.

Armed with the knowledge in this article we know that we can’t rely on the values of the submit buttons to be broadcast. If we don’t know which button has been clicked, we simply choose a default action and perform that unless we detect the alternative action. In PHP and for the first form it would go something like this:

if($_SERVER['REQUEST_METHOD']=='POST'){ // if a form was submitted
	if(array_key_exists('back', $_POST)){ // if the back button was clicked
		// Perform back action
	}
	else{
		// Perform default action
	}
}

So long as you don’t assume the button to be clicked in order to perform the default action, life will be good!

REST For The Weekend

Tuesday, August 25th, 2009

Oh well, the weekend’s over again. What did you do? I got an impressive sunburn, bought some delicious fruit and veg at the market and looked into RESTful architectures, among other things. Although I would love to tell you about my culinary adventures, what I’m going to write about now is REST. It should be noted that in this case REST is not sitting in front of the TV and has nothing to do with the title of this blog, despite what you may think!

What REST is not

There seems to be some confusion over exactly what a RESTful architecture is. Some people think it is pretty URLs:


http://www.mysite.com/portfolio/design/someclient

as opposed to:

http://www.mysite.com/index.php?section=portfolio »
    &subsection=design&client=someclient

This is not RESTful.

Some people think REST is a bunch of actions triggered by visiting URLs:


http://www.mysite.com/contact/email/send

This isn’t RESTful either.

Being resourceful

REST stands for REpresentational State Transfer and it’s all about resources. That is to say, data presented in a formatted way and made available at specific, addressable points of entry. Most of the time when people talk about a REST interface they will be talking about the web and URLs, but REST is not limited to this technology. So long as each resource on a system can be identified uniquely, manipulated, each request for resources includes enough information that the client knows how to process it and has the ability to contain references to other resources then it can be called RESTful.

A RESTful system is a stateless system; each resource request in a RESTful system should be completely independent of any other. It should not rely on cookies, session variables or any other state maintaining solutions. This is because a REST request is intended to be performed on the current state of the specified resource and the resource should be able to be encapsulated in a single response.

Strict instructions

It might have slipped under the radar but a couple of paragraphs above I mentioned that a REST response should include information for the client on how to process the data. In the case of a web service (and it should be assumed from here on out I’ll be talking about web services) the MIME type should be sufficient. For example, if you are serving your response up as JSON you’d want to use the MIME type: application/json. The MIME type is contained within the header of the response.

In a similar manner, the client needs to tell the server what it wants to do with the specific resource. We can do this by specifying the correct HTTP Method as part of the request.

Method in madness

So the HTTP methods most people are used to are: GET (the default method, what you get when you hit enter after typing a URL) and POST (the method used for submitting most forms). The others we are interested in are PUT and DELETE. Using these four methods we can instruct a RESTful interface to perform the basic CRUD operations:

  • Create = POST
  • Read = GET
  • Update = PUT
  • Delete = DELETE (rather unsurprisingly)

Using these methods you can manipulate a resource in any way you like from that single addressable entry point. If you have the URL for the resource, in a RESTful architecture you know you won’t have to append strings to the URL to make it do things (Eg ?action=delete) – you just change the method used to request the resource in the request header.

Obviously if your system is externally accessible you will probably want to limit access to the ‘unsafe’ POST, PUT and DELETE methods.

Not for everyone

So as you can tell, REST isn’t something you should strive to include just for the sake of it. I can’t stress this enough: there’s no point in shoehorning REST into a site or project when it is not really needed. The main use for it it most likely to be for Web Service APIs and anything that is highly resource driven. Think of it as a series of defined views on a database or other resource and you can’t go too far wrong.

I am currently working on a web based file system for storing assets as part of a CMS. It has an API so that you can add, edit, read and delete assets from external locations, providing that you present the right credentials. This almost seems like the perfect application for REST as each entry – be it a file or a folder – needs to have the basic CRUD operations performed on it. The whole URL structure is basically the directory tree and every point in that tree is addressable and will accept all the different methods.

Testing, testing

This is all very well, but how do you go about testing these crazy HTTP methods, practically? You can’t have a page full of links to click because a link is a GET request. There’s no way of changing that.

Forms offer a little flexibility – you can specify the method you want to use with the method attribute. Unfortunately this is restricted to GET and POST. If you try anything other than that it will default to GET.

To test these request methods, you have to hand craft an HTTP request. You can do this in the server-side scripting language of your choice (Eg PHP, Ruby, Python etc) OR you can download one of the handy Firefox extensions that kindly developers have made available for nothing for this very purpose! My personal favourite is RESTClient by Chao ZHOU but there are plenty of others for you to choose from. Here are a few:

Using RESTClient

It’s pretty simple really. The basic interface looks like this:

The RESTClient interface displays fields for method, url, header and request body along with an area in which to display the response. At the top are controls to open & save your request amongst other things.

The RESTClient interface displays fields for method, url, header and request body along with an area in which to display the response. At the top are controls to open & save your request amongst other things.

  1. Choose your request method
  2. Type the resource location
  3. Add any request headers you need (this is like items from form fields)
  4. Type the request body you want to transmit (this can be left blank most of the time)
  5. Hit send

What you will get back is the response as the server sends it. You can inspect the header and the body to make sure it’s coming back as you’d expect and so your application that will consume the response won’t get any nasty surprises!

Hopefully you are interested in RESTful architectures now, and are feeling inspired to go off and write one of your own!

For more information on this topic, check out the Wikipedia article on REST