How to align two elements on the same line without changing HTML
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).
Solution 1:
Using display:inline-block
#element1 {display:inline-block;margin-right:10px;}
#element2 {display:inline-block;}
Example
Solution 2:
div {
display: flex;
justify-content: space-between;
}
<div>
<p>Item one</p>
<a>Item two</a>
</div>
Solution 3:
#element1 {float:left;}
#element2 {padding-left : 20px; float:left;}
fiddle : http://jsfiddle.net/sKqZJ/
or
#element1 {float:left;}
#element2 {margin-left : 20px;float:left;}
fiddle : http://jsfiddle.net/sKqZJ/1/
or
#element1 {padding-right : 20px; float:left;}
#element2 {float:left;}
fiddle : http://jsfiddle.net/sKqZJ/2/
or
#element1 {margin-right : 20px; float:left;}
#element2 {float:left;}
fiddle : http://jsfiddle.net/sKqZJ/3/
reference : The Difference Between CSS Margins and Padding
Solution 4:
By using display: inline-block; And more generally when you have a parent (always there is a parent except for html) use display: inline-block;
for the inner elements. and to force them to stay in the same line even when the window get shrunk (contracted). Add for the parent the two property:
white-space: nowrap;
overflow-x: auto;
here a more formatted example to make it clear:
.parent {
white-space: nowrap;
overflow-x: auto;
}
.children {
display: inline-block;
margin-left: 20px;
}
For this example particularly, you can apply the above as fellow (i'm supposing the parent is body. if not you put the right parent), you can also like change the html and add a parent for them if it's possible.
body { /*body may pose problem depend on you context, there is no better then have a specific parent*/
white-space: nowrap;
overflow-x: auto;
}
#element1, #element2{ /*you can like put each one separately, if the margin for the first element is not wanted*/
display: inline-block;
margin-left: 10px;
}
keep in mind that white-space: nowrap;
and overlow-x: auto;
is what you need to force them to be in one line. white-space: nowrap; disable wrapping. And overlow-x:auto; to activate scrolling, when the element get over the frame limit.