Wednesday, February 9, 2005

Finally Centering Blocks

WARNING: This blog entry was imported from my old blog on blogs.sun.com (which used different blogging software), so formatting and links may not be correct.


I'm in Prague this week, and having a great time. We're discussing
architecture and the java model. It's really exciting, but too early to blog about...



I did find out about some cool new features in NetBeans 4.1 though.
For example, if you hold the control key (or on my mac, the Command key)
all method calls under the mouse turn into hyperlinks which when clicked
jump to the referenced source.





Now for the nerdy technical digression of the week....
I've been doing some debugging at night. After somebody

brought up the issue

of the <center>> tag (which I've

mentioned before
), I decided to look into it again.
A little debugging led me to the problem in the rendering code. Basically,
let's say you're trying to center a table like this:


<table style="margin-left: auto; margin-right: auto">
<tr><td>Hello World</td></tr>
</table>



I'm using horizontal margins as auto to cause centering, which is the
CSS way to center - the <center> tag has been deprecated a long
time.



In the above html, we have an element with
"width", "margin-left" and "margin-right" all set to "auto".
According to the width computation rules for

CSS 2.1, section 10.3.3,


If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.



If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

My code was doing these rules in the order listed. In the above scenario, yes,
width is auto, so the other auto values (margin-left and margin-right) become
0, and then it solves the equation

margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

This however means that the computed position is not centered. So instead I'm now
first computing the preferred minimum width of the component (using the shrink-to-fit
approach used for absolutely positioned elements), and then I split the remaining space
in the containing block evenly between the two margins. This seems to give exactly
the behavior needed.



After hooking this behavior up to the <center>
tag, using

page import

on the Google home page shows that the google text field area is now correctly centered!


No comments:

Post a Comment