先给出例子,看HTML


<div class="box">    <div class="box-1">    	box-1    </div>

    <div class="box-2">    	box-2    </div>

    <div class="box-4">    	box-4    </div></div>


写出


.box-1{
	float:left;
	width:300px;
	height:100px;
	background:#f00;
}
.box-2{
	float:left;
	width:300px;
	margin-right:-300px;
	background:#369;
}
.box-4{
	float:left;
	width:300px;
	background:#ddd
}

查看测试页面一

没错,是那margin-right:-300px惹的祸,它把它对下一元素的参考线为-300px,所以.box-4才会覆盖在box-2上面。我们看看margin的基本特性

margin 属性包括 margin-top, margin-right, margin-bottom, margin-left, margin,可以用来设置 box 的 margin area。属性 margin 可以用来同时设置 box 的四边外边距,而其他的 margin 属性只能设置其自各的外边距。

margin 属性可以应用于几乎所有的元素,除了表格显示类型(不包括 table-caption, table and inline-table)的元素,而且垂直外边距对非置换内联元素(non-replaced inline element)不起作用。

或许有朋友对非置换元素(non-replaced element)有点疑惑,稍微帮助大家理解一下。非置换元素,W3C 中没有给出明确的定义,但我们从字面可以理解到,非置换元素对应着置换元素(replaced element),也就是说我们搞懂了置换元素的含义,就懂了非置换元素。置换元素,W3C中给出了定义:

“An element that is outside the scope of the formatter, such as an image, embedded document, or applet”

从定义中我们可以理解到,置换元素(replaced element)主要是指 img, input, textarea, select, object 等这类默认就有 格式化外表范围的元素。进而可知,非置换元素(non-replaced element)就是除了 img, input, textarea, select, object 等置换元素以外的元素。

margin 始终是透明的。

仔细看下面的图,就很好理解了。

让我们醍醐灌顶

增加一个box-3,使用margin-left:300px把margin-right:-300px抵消掉


.box-3{
	float:left;
	width:0px;
	white-space:nowrap;
	margin:0 0 0 300px;
	overflow:hidden;
	background:#fe8;
}

在box-2下增加box-3


<div class="box-3">    box-3</div>

查看测试页面二

并不推荐这么做,很显然我的结构有问题。现只是作为例子。

(注:本文图片,定义直接copy译飞由浅入深漫谈margin属性

ie下的relative

-

Web前端开发

- css - 浏览器

今天遇到,记录一下。谢谢怿飞,同时我也看到他对待问题的态度(学习的地方)。

我们首先看看W3C的规定

relative
The box”s position is calculated according to the normal flow (this is called the position in normal flow). Then the box is offset relative to its normal position. When a box B is relatively positioned, the position of the following box is calculated as though B were not offset. The effect of “position:relative” on table-row-group, table-header-group, table-footer-group, table-row, table-column-group, table-column, table-cell, and table-caption elements is undefined.

元素在正常文档流(position in normal flow),并没有被移出。在ie中,relative会把元素移出文档流,但占物理位置。父容器overflow:hidden将不能隐藏。我们先看例子。

body{
	color:#fff;
}
.box-0{
	width:500px;
	height:100px;
	padding:20px 0 0 20px;
	overflow:hidden;
	background:#f60;
}
.box-1{
	width:500%;
	height:100px;
	position:relative;/*  */
	line-height:100px;
	text-indent:100px;
	background:#000;
}
<div class="box-0">
	this is box-0
	<div class="box-1">

    	this is box-1
   </div>
</div>

查看测试

发表评论

*必填

*必填