html - 如何在没有 float 的情况下水平对齐 2 个相邻的 div?

标签 html css xhtml position

我想让 2 个 div 彼此并排对齐在同一条水平线上 WITHOUT FLOATs

我试过 Position:relative ,但是没有成功

请看下面的例子: 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>

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

编辑:我希望红色框留在容器灰色框之外(就这样)谢谢

最佳答案

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>

编辑

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

#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.)

关于html - 如何在没有 float 的情况下水平对齐 2 个相邻的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17130711/

相关文章:

html - 栏中的图标太低

javascript - Jquery切换点击显示一个div同时隐藏其他div

javascript - 使用 Javascript 获取和设置元素的宽度

html - 在 bootstrap carousel 中,如何删除图像和 .carousel div 之间的空间?

css - XHTML CSS 背景没有填满整个 div

javascript - 如何默认 Html.DropDownList 不选择?

windows - 谷歌字体的行高渲染

html - 从小屏幕查看时,jQuery Mobile 会更改表单宽度吗?

javascript - 如何将效果与菜单列表和子菜单列表分开?

html - CSS 菜单(无法让标签达到全高)