CSS属性margin负值与float效果浅谈

来源:互联网 发布:投稿网站源码 编辑:程序博客网 时间:2024/06/07 05:49
<html lang="en">
<head>
<meta charset="UTF-8">

<title>Document</title>

<style>

*{margin:0;padding:0;}

</style>

</head>
<body>
<div class="box" style="width: 400px;width: 400px;">
<div style="float: left;width:100px;height: 200px;background: green;"></div>
<div style="width:100px;height: 200px;background: red;position: relative;padding: 10px;">


</div>
</div>
</body>

</html>

会得到如下效果


这时由于背景颜色为绿色的div由于浮动效果在最上面,盖住了背景颜色为红色的div


demo2

改变红色div的宽为200px;时

<div class="box" style="width: 400px;width: 400px;">
<div style="float: left;width:100px;height: 200px;background: green;"></div>
<div style="width:20000px;height: 200px;background: red;position: relative;padding: 10px;">

</div>

效果如下



demo3

在未浮动的红色div里面嵌套两个相对定位div时,并且都有内容。

<div class="box" style="width: 400px;width: 400px;">
<div style="float: left;width:100px;height: 200px;background: green;"></div>
<div style="width:200px;height: 200px;background: red;position: relative;">
<div id="demo1" style="position: absolute;top: 0;left: 0;">2222</div>
<div id="demo2" style="position: absolute;top: 0;right: 0;">3333</div>
</div>
</div>

可以实现如下效果


这时浮动的绿色div被红色覆盖了

demo4

现在在红色div里面在嵌套一个p标签附带文字内容

<div class="box" style="width: 400px;width: 400px;">
<div style="float: left;width:100px;height: 200px;background: green;"></div>
<div style="width:200px;height: 200px;background: red;position: relative;padding: 10px;">
<div id="demo1" style="position: absolute;top: 0;left: 0;">2222</div>
<div id="demo2" style="position: absolute;top: 0;right: 0;">3333</div>
<p>内容内容内容内容内容内容</p>
</div>
</div>

如下效果


浮动的元素绿色div不见存在于

中间线左边的位置(中间线为辅助线实际效果没有中间线),

这里浮动元素占位但是却被红色div覆盖,但是红色div里面的p标签内容却被绿色div影响,很怪异。

demo5

给绿色浮动元素加上margin负值

<div class="box" style="width: 400px;width: 400px;margin:110px;">
<div style="float: left;width:100px;height: 200px;background: green;margin-left:-110px;"></div>
<div style="width:200px;height: 200px;background: red;position: relative;padding: 10px;">
<div id="demo1" style="position: absolute;top: 0;left: 0;">2222</div>
<div id="demo2" style="position: absolute;top: 0;right: 0;">3333</div>
<p>内容内容内容内容内容内容</p>
</div>
</div>

这时我们可以看见浮动的绿色div如图



原创粉丝点击