Tuesday, February 14, 2006

On width

Width causes two problems. First, people can't figure why an element won't accept width. Second, people can't figure out why their poor "boxes" are bigger than they expect.

Inline elements

The first problem is usually because the developer is trying to apply width to something that can't take it. For example, adding the "width" property to a span, without something more, will do nothing. Span is an inline element--or it is at least treated as such. Since inline elements don't understand width (it really doesn't make much sense), the property gets ignored. The fix is simple: make it not an inline element.

There are two ways to easy ways to make something not an inline element. The first is to change the display property (eg. display: block; or display: inline-block; the latter of which doesn't work in many browsers). The second way is to float an element. By adding float: left;, an inline element is now a box. Problem solved.

The meaning of width...

The second problem is something a bit "trickier". The typical situation looks like this:

div#something {
    width: 100px;
    padding: 5px;
    border: 1px solid #000;
    background-image: url(perfectly-100px-image.gif);
}

They are then shocked to find that their painstakingly precise 100 pixel image doesn't fit perfectly in their box. They then complain that CSS sucks.

Well, the problem is simple. The calculation for "box width" is done by adding the values for 1) width, 2) horizontal padding, and 3) horizontal borders. The problem is most certainly because most people would want to understand "width" to be "box width" and not "content width".

You see, the actual meaning of the "width" property is "content width". It sets the space that a block may use to show its content (inline or otherwise). In the code above, the content contained by #something will have a width of no more than 100px, without doing something else. The overall box, however, will be 100px (content width) + 10px (left & right padding) + 2px (left & right borders), for a total of 112px.

So, to get the "appropriate" behavior, and assuming that the borders are supposed to be on the outside of the image, the following code would work:

div#something {
    width: 90px;
    padding: 5px;
    border: 1px solid #000;
    background-image: url(perfectly-100px-image.gif);
}

0 Comments:

Post a Comment

<< Home