如何水平对齐2个相邻的div而不浮动?

Ahm*_*ess 12 html css xhtml position

我想在彼此旁边制作2个div,以在没有FLOAT的同一水平线上对齐

我试过位置:相对,但没有运气

请参阅以下示例: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>
Run Code Online (Sandbox Code Playgroud)

从上面的链接,我需要红色框在蓝色框的同一行,下面没有空格..

编辑:我希望红色的盒子留在容器灰盒子外面(就像它一样)谢谢

Sou*_*abh 14

Relativeinline-block显示屏


#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;
	}
Run Code Online (Sandbox Code Playgroud)
<div id="one"><div id="two"></div><div id="three"></div></div>
Run Code Online (Sandbox Code Playgroud)

编辑

下面的代码也可以正常工作.在这里,由于注释,换行符被注释掉并被忽略.

#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;
	}
Run Code Online (Sandbox Code Playgroud)
	<div id="one">
		<div id="two"></div><!--
		--><div id="three"></div>
	</div>
Run Code Online (Sandbox Code Playgroud)

为什么它的工作 block显示取其容器的整个宽度,即使你设置的很小width,其余的空间也将被视为边距(即使你删除了边距).这就是他们的行为方式.inline-block显示工作很像inline显示,除了他们尊重padding你给他们的等.但他们仍然忽略了margins(如果我错了,有人会纠正我).与内联显示相同,如果您在它们之间提供换行符HTML,则会将其转换为小空格.所以要删除它,这里我将HTML放在一行中.如果你缩进代码,那么div#three 将被推下(因为你有固定的宽度,div#one所以高度只是选项.)

  • 很公平.但我会把它留在那里,它不会伤害任何人.如果没有别的,那么它将来可能会有所帮助. (2认同)

bug*_*s94 5

高度和宽度固定时使用位置属性

<div style="width:200px;height:100px;position:relative;background:#ccc;"> 
   <div style="background:Blue; position:absolute; left:0%; width:50%; height:100%;">
   </div> 
   <div style="background:red; position:absolute; left:50%; width:50%; height:100%;">
   </div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 实际上这是有效的,我试图远离绝对位置,但似乎这是最可靠的方法:( (2认同)