css中利用margin来隐藏元素

来源:互联网 发布:百度地图数据下载 编辑:程序博客网 时间:2024/06/12 01:30

例如

<style>

div

{

width:200px;

height:200px;

background-color:lightlue;

margin:0px 0px 0px -999em;

}

</style>

<div>

&nbsp;

</div>

<p>i am okok</p>


1.将margin-left:设置成比元素宽度还大的负值,就能将元素相左移动出body(或包含框),这样在效果上就像把元素隐藏起来了,只是之后跟随的段落不会,不会忽视div的高度,仍然保持原位置,除非设置了margin-bottom,


2.如果把元素的margin-bottom也设置为负值,那么之后跟随的元素(如p元素)会上浮,如果负值的绝对值大于元素的高度,之后跟随的元素(如段落)会好上浮到元素的顶部以上。


3.元素(如div)只有贴着那一边,才能有效的实施margin 的负值效果。

<style>

div

{

width:200px;

height:200px;

}

</style>

<body>

<div>

</div>

</body>

这种情况之下实施margin-top margin-left会有效果  实施marign-bottom时之后跟随的元素会有相应的上下位置变化,实施margin-right时不会有太大效果。

如果把div浮动float到right时,marin-right会有效果,margin-left不会。


4.如果是元素左右侧有元素时


<style>

div

{

width:200px;

height:200px;

float:left;

}

div.one

{

background-color:yellow

margin-left:-100px;

}

div.two

{

background-color:blue;

}


</style>

<body>

<div class="one">&nbsp;</div><div class="two">&nbsp;</div>

<p>i am okok</p>

</body>


如果是两个元素并排,div.one的margin-left为负值时,这两个元素整体相左移动。

如果div.one的margin-right为负值时,div.two会向左移动覆盖一部分div.one.


如果div.two的margin-right也为负值时,i am okok这段文字就会向左偏移,位于div.two中一部分。因为margin为负值时就相当于元素的边界缩小。

如果div.two的margin-bottom为负值且绝对值足够大时,相对于元素的高度足够小时,这时i am okok这段文字就会向左移动,相对于div.two不纯在一样。


实例代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>


body
{
width:1000px;
height:1000px;
margin:200px auto;
border:1px solid red;
color:#f00;
}




div.one
{
padding:0px;
float:left;
width:200px;
height:200px;
background-color:blue;
margin-bottom:-190px;


}


div.t
{
width:200px;
height:200px;
background-color:yellow;
float:left;

}




p
{
background-color:lightpink;
height:300px;
}


</style>
</head>


<body>
<div class="t">&nbsp;</div>
<div class="one">
&nbsp;
</div>
<p>i am okok</p>
</body>
</html>


实例图片:







0 0
原创粉丝点击