Centering div horizontally and replacing table with div

October 30, 2009

There are many ways to center HTML content horizontally on the page. Traditionally, many webmasters use tables for layouts, and often solely to center content horizontally; some use floating divs; some even revert to absolute positioning and usage of JavaScript.

Today I’m glad to tell you about a very easy, very fast, and very predictable way of centering your content horizontally. Meet the display: inline-block CSS rule!

As soon as you apply it to the divs you need to center, just add the text-align: center rule to their container, and you’re done! Your divs will maintain their alignment at all times, from very small to very large window widths. You can see a demonstration here; remember to check out the source code to see how cleanly it looks.

Update
Apparently Internet Explorer can only assign inline-block display type to elements that are natively inline (such as spans). So we just replace divs with spans, and voila! Everything works now in IE, too, while nothing changes in other browsers.

Update 2
Pay attention to the “vertical-align: top” CSS rule. Without it, IE would align the tallest span in the row by the bottom of the row, while Firefox and Webkit-based browsers align such spans by the top of the row by default. Adding this rule allows our markup to look completely uniform in all major browsers.

Update 3
It is also possible to achieve the desired effect without reverting to spans: use IE conditional comments to tell it that divs are inline, while all other browsers get the inline-block rule. This will allow your markup to remain valid from W3 specs point of view even when you need to inject block elements into your centered elements (doing so with spans will violate the specs). I will update my example accordingly.

There are only two minor caveats to keep in mind (both of them are illustrated in the supplied example page):
1) In the end of the horizontal block you want to center, put a
element.
2) Comment out newlines between elements in a horizontal block, otherwise in some browsers you will see white spaces between them.

Please report if you find a case where this method fails to deliver.


GMail + TIFF = ?

October 24, 2009

I’ve patiently waited for nearly a year after I reported this bug for the first time, but now I think it is time to file the report the second time and to amuze my readers. So, open your GMail and send an email with an attached little-endian TIFF image (grab the one you see in this post, I have been unable to find other files this exploit will work with). Below the message text, you will see a preview of your TIFF image. Or, rather, a preview of a *random* TIFF image (or so it seems).
A preview for another different image is shown in every message this TIFF is attached to; this is very dangerous as somebody could use this method to automate retrieval of images sent by other GMail users.
On the bright side, you don’t get to know who sent the images you see, and you only have the low-res preview to play with (if you download the TIFF file, you’ll see the correct one).

A file that causes such a vulnerability can be downloaded here. Please only use it to confirm the bug, and do not abuse it!

Update: Google has acknowledged my bug report as of 2009-10-26 08:00 MSD, and the TIFF preview feature in GMail has been disabled. The bug has been assigned ID #532113728.


Поехали!

October 17, 2009

Дорогие друзья!
Рад сообщить, что сайт SpaceTrackr запущен и ждёт своих пользователей.
SpaceTrackr позволяет отслеживать местоположение космических объектов (искусственных спутников Земли, орбитальных станций, космического мусора) в реальном времени, а также отображать зону их видимости и траектории полёта. В каталоге SpaceTrackr содержится более пяти тысяч актуальных космических объектов; каталог обновляется ежечасно.
Сайт находится в состоянии открытой беты, т.е. на нем могут встречаться баги, лаги и прочие неприятности; просьба сообщать о них по специально организованному интерфейсу фидбэка.
Сайт абсолютно бесплатен для пользования и не содержит рекламы.

Итак, добро пожаловать на SpaceTrackr!

Работа выполнена в качестве развития проекта в интересах НИИЯФ МГУ им.М.В.Ломоносова.


Rounded corners

July 20, 2008

In the past few years, literally dozens of methods to produce cross-browser rounded rectangles have been developed [1] [2]. However, most of those I have read either rely on excessive and incomprehensible markup, use browser hacks (which is sort of frowned upon [3] by web development gurus), or use background images (which makes the boxes nearly impossible to scale correctly without noticeable overhead on the server side).

All of this has motivated me to research a solution that satisfies the following conditions:

  1. It works in the top browsers (Internet Explorer, Mozilla Firefox, Safari and Opera).
  2. It is built on valid XHTML.
  3. It supports different visual styles and box sizes.
  4. It does not rely on outright CSS hacks and browser bugs.
  5. It does not rely on Javascript browser recognition (ideally, that is).

Dealing with Mozilla Firefox was an easy one: it has (kind of) implemented [4] the CSS3 draft’s border-radius property since Firefox 1.0 [5]. To use it, apply the -moz-border-radius property to your element. Note that Mozilla’s version of the border-radius is different from the W3 proposal: it doesn’t support elliptic arcs in favour of specifying different values for all corners.

Dealing with Safari 3.1 is equally easy: apply the -webkit-border-radius property. Webkit implementation follows the CSS3 draft proposal.

Here’s a sample stylesheet portion which provides rounded borders in both Firefox and Safari:

.roundrect {
...other properties...
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}

Beating Internet Explorer and Opera is somewhat more complicated. I have decided to draw the box using VML (not to be confused with VRML) in IE, and to use SVG in Opera. First, we need to make the browser aware of the VML and SVG namespaces. This is how it can be done:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:vml="urn:schemas-microsoft-com:vml" xmlns:svg="http://www.w3.org/2000/svg">

VML is proprietary Microsoft technology, and is thus only supported by Internet Explorer (version 5.0 and higher). So we need to enable VML drawing in IE and make sure that it doesn’t mess up everything in other browsers. To do this, we use conditional comments [6], which are also only supported by IE. Conditional comments can safely be used, since other browsers see them and all markup in between as perfectly valid comments. Include the following in the head of your document:

<!--[if IE 7]>
<style type="text/css">
vml\:* {
behavior: url(#default#VML);
display: inline-block;
}
</style>
<![endif]-->

Now you can put your VML-drawn rounded rectangles wherever you see fit. Just remember to wrap them into conditional comments so IE doesn’t get the piece written for other browsers, and vice-versa. Example:

<!--[if IE 7]>
<vml:roundrect class="roundrect" style="border: 0px" fillcolor="#ffffcc" strokecolor="navy" arcsize="25%">Hello world!</vml:roundrect>
<![endif]-->
<!--[if !IE]>-->
<div class="roundrect">Hello world!</div>
<!--<![endif]>-->

Let’s deal with Opera now. We’ll use an SVG background image in our box (method originally described in [7]). SVG, being an XML-based vector drawing language, supports variable box sizes and visual styles, and the image can even be customized with CSS. Unfortunately, the only method known to me of making things work in Opera 9.5 that does not break compatibility with Safari 3.1 requires some Javascript browser sniffing:

<script type="text/javascript">
if (window.opera) {
document.documentElement.className += document.documentElement.className ? ' ' + "opera" : "opera";
}
</script>

The window.opera object is, unsurprisingly, proprietary and specific to Opera, which enables us to look for it and apply a style named e.g. “opera” to the document:

.opera .roundrect {
border: 0px;
background-image: url("roundrect.svg");
}

The image roundrect.svg can be customized to anything your heart desires; here’s a sample.

That’s it, we’ve done it. I haven’t tested this solution in anything except Firefox 3, IE7, Safari 3.1 and Opera 9.5, so feel free to report any bugs you encounter. Also I’ll be grateful to know how to modify this solution to support Konqueror.