Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How align 2 adjacent divs horizontally WITHOUT float?

I want to make 2 divs beside each other to be aligned on the same horizontal line WITHOUT FLOATs

I've tried Position:relative ,, but no luck

See the example below : http://jsfiddle.net/XVzLK

<div style="width:200px;height:100px;background:#ccc;"> 
<div style="background:Blue; float:left; width:100px; height:100px;"></div> 
<div style="background:red; float:left; margin-left:100px; width:100px; height:100px;"></div>
</div>

From the link above, I need the red box to be on the same line of blue box with no space below ..

EDIT : I want the red box to stay outside the container gray box (just as it is) thanks

like image 770
Ahmed Moness Avatar asked Jun 16 '13 06:06

Ahmed Moness


Video Answer


2 Answers

Relative with inline-block display


#one {
		width: 200px;
		background: #ccc;
	}

	#two {
		display: inline-block;
		background: blue;
		position: relative;
		left: 0;
		width: 100px; height: 100px;
	}

	#three {
		display: inline-block;
		background: red;
		position: relative;
		left: 0;
		width: 100px; height: 100px;
	}
<div id="one"><div id="two"></div><div id="three"></div></div>

EDIT

The code below also works fine. Here, because of comments, the line feed is commented out and ignored.

#one {
		width: 200px;
		background: #ccc;
	}

	#two {
		display: inline-block;
		background: blue;
		position: relative;
		left: 0;
		width: 100px; height: 100px;
	}

	#three {
		display: inline-block;
		background: red;
		position: relative;
		left: 0;
		width: 100px; height: 100px;
	}
	<div id="one">
		<div id="two"></div><!--
		--><div id="three"></div>
	</div>

Why it works block displays take the whole width of their container, even if you set a very small width, rest of the space will be taken as margin (even if you remove margin). That's just how they behave. inline-block displays work much like inline displays except that they do respect the padding etc you give them. But they still ignore margins (someone correct me if I am wrong). Same as inline displays, if you give a line-feed between them in your HTML, it's converted to a small space. So to remove that, Here I have the HTML in a single line. If you indent the code then the div#three will be pushed down (as you have fixed width of div#one so height is only option.)

like image 167
Sourabh Avatar answered Oct 22 '22 19:10

Sourabh


If you want to avoid float, position and inline-block, here's a margin-only solution:

<div style="width:200px; background:#ccc;">
<div style="background:blue; width:100px; height:100px;"></div>
<div style="background:red; width:100px; height:100px; margin:-100px 0 0 100px;"></div>
</div>

Updated fiddle

like image 21
Mr Lister Avatar answered Oct 22 '22 19:10

Mr Lister