How to align two elements on the same line without changing HTML

user1074378 picture user1074378 · Jan 30, 2012 · Viewed 411.6k times · Source

I have two elements on the same line floated left and floated right.

<style type="text/css">
#element1 {float:left;}
#element2 {float:right;}
</style>

<div id="element1">
 element 1 markup
</div>
<div id="element2">
 element 2 markup
</div>

I need for element2 to line up next to element1 with about 10 pixels of padding between the two. The problem is that element2's width can change depending on content and browser (font size, etc.) so it's not always lined up perfectly with element1 (I can't just apply a margin-right and move it over).

I also cannot change the markup.

Is there a uniform way to line them up? I tried margin-right with a percentage, I tried a negative margin on element1 to bring element2 closer (but couldn't get it to work).

Answer

Sameera Thilakasiri picture Sameera Thilakasiri · Jan 30, 2012

Using display:inline-block

#element1 {display:inline-block;margin-right:10px;} 
#element2 {display:inline-block;} 

Example