您的位置:首页 > Web前端 > CSS

css中margin的一些易忽略的问题

2014-08-10 16:49 513 查看
代码:

<style type="text/css">
.big{
width:200px;
height:200px;
background:pink;
}
.small{ width:50px;
height:50px;
background:green;
margin-top:50px;
}
</style>
<div class="big">
<span style="white-space:pre">	</span><div class="small"></div>
</div>

效果如下:



内部.small的div设置margin-top为50px后,连同外部的div会一起向下移动50px,要想保持外部div不动,可以将.small的div设置float:left样式;

但是当margin-top设置为百分比时就完全不一样了

代码如下<style type="text/css">
html,body{height:100%;}
.big{
width:200px;
height:10%;
background:pink;
}
.small{ width:50px;
height:60%;
background:green;
margin-top:50%;
}
</style>
<div class="big">
<span style="white-space:pre">	</span><div class="small"></div>
</div>
效果如下:



margin-top本来是相对于父元素而言的,但是通过开发者工具查看,两个div的高度是随着窗口的大小变化而变化的,但是margin-top的值却保持不变,经过测量,基本为百分比的2倍高度,即使.small的div设置了float:left,只能保证父级div位置不变,其margin-top值依然不变为百分比的2倍

如下图所示:



<style type="text/css">
.big{
width:200px;
height:300px;
background:pink;
}
.small{ width:50px;
height:50px;
background:green;
margin-top:50%;
}
</style>
<pre name="code" class="html"><div class="big">
<span>	</span><div class="small"></div>
</div>


.big的div和.small的div均设置成固定长宽后,margin-top为百分比,无论父级div高度如何变化,结果显示margin-top的值不变,依然为百分比的2倍

如下如:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  css margin 百分比