There are a few questions on Stackoverflow which ask about aligning elements horizontally using CSS (divs). Generally, this is accomplished using floats, or display: inline-block
.
However, I have a pretty simple requirement, and I'm having difficulty using either of these techniques to get it to work perfectly. I simply want to horizontally align a line of text with a DIV element.
So, basically, there are 3 ways of doing this:
Method 1 (Using display: inline-block
)
<div style = "display: inline-block;">Foo</div>
<div style = "display: inline-block; padding-left: 19px">
<div style = "border: 1px solid #000000; height: 1em; width: 100px"></div>
</div>
Method 2 (Using float
)
<div style = "width: 150px">
<div style = "float:left">Foo</div>
<div style = "float:right">
<div style = "border: 1px solid #000000; height: 1em; width: 100px"></div>
</div>
</div>
Method 3 using.. (please don't kill me) a <table>
:
<table style = "width: 150px" cellpadding = "0" cellspacing = "0" border = "0">
<tr>
<td style = "width: 40px">
Foo
</td>
<td>
<div style = "border: 1px solid #000000; height: 1em; width: 100px"></div>
</td>
</tr>
</table>
These three methods render like this on Firefox:
Okay, so firstly, the problem with Method 1 (inline-block
) is that the text isn't vertically aligned (centered) with the DIV element, which looks awkward. Instead, the bottom border of the DIV is aligned with the bottom of the text. I tried adjusting padding and margins to fix this, but it didn't help.
Method 2 (float
s) looks good, but the problem with Method 2 is what happens if the text changes to something longer? Well...
So the problem with using floats is that if the text gets longer, the DIV element is knocked down to the next line. So this isn't acceptable. Note that Method 1 (inline-block
) doesn't have this problem.
The only method which meets all requirements is the one which uses a <table>
, but I don't want to use that, because ... well, reasons.
So, what's the best solution here. How can I use just DIVs with CSS to get the same result as Method 3, which uses a <table>
?