This one is tricky:
If you set the width on the sidebar, float it, and don't set the width on the content (also, don't float the content either as this will cause the div to "shrink-wrap"). Then the column will behave like you desired.
#content { width: auto; display:block } /* not really necessary as these are default */
#sidebar { width: 30%; float: right }
I'd like to add that this is intrinsically flaky and often limiting. Your best bet is, if you control the layout on the server side (you've got some script that generates layouts) then append css classes to the document before it's rendered.
A pure html solution is possible, but it also relies on this particular behavior. If you want to float the #content div, it won't work (because you'll be forced to specify the dimensions to avoid the shrink wrapping effect).
You can also do this using javascript. The thing to watch out for there is you might get a FOUC (flash of unstyled content) as the javascript kicks in.
With jQuery you could do something like count the adjacent divs i.e.
jQuery('#content').nextAll().length
Then use the result to do something like:
jQuery('#content').addClass('has_sidebar').