CSS, Web Development

Quick Post – Width For Inline Elements

I’m always bugged when I need to align some elements that are displayed inline. The design was almost perfect, but suddenly a new element was added and I need to align it to other elements from the top.

previous-no-align1

Notice the Mobile No. label.

As you can see, the span elements on the left has width, colored in very light yellow. It is called “col1” for this example. The next span after it is called “col2” which is colored light purple. The span “col1” and “col2” are displayed block, floated left and has widths.

Inside “col2” are various elements such as labels, select elements and input elements. These elements has widths except for label. They are positioned fine. Below is their possible markup.

<p>
    <span class="col1">Test 1</span>
    <span class="col2">
        <input type="text" name="test1" id="test1" />
        <label for="test2">Test 2</label>
        <input type="text" name="test2" id="test2" />
    </span>
</p>
<p>
    <span class="col1">Result 1</span>
    <span class="col2">
        <input type="text" name="result1" id="result1" />
        <label for="result2">Result 2</label>
        <input type="text" name="result2" id="result2" />
    </span>
</p>

All I do to align them is to apply width and some margin left. However, when another devastating row was added, I run into width trouble.

after-with-align

As you can see, Date Received is added and I need to align it to Mobile No one row above it. The problem is that it is a label and we can’t apply width to label. We can’t also float and apply width to it since it is written beside inline elements which would surely mess up the entire layout.

The mission is to apply width to the labels for Mobile No and Date Received.

Google, Google…

It says that we can safely display the label as inline-block. So the CSS would look like this:

.basic-info p .l-input label.mobile,
.basic-info p .l-input label.d-received {
	margin-left: 55px;
	display: inline-block;
	width: 100px;
}

Above is my actual code. I applied margin left to push it forward then display as inline-block so that we can apply width and finally applied 100px width.

As to my surprise, it works on IE6!

Leave a reply

Your email address will not be published. Required fields are marked *