块级元素的一些小问题

来源:互联网 发布:windows字体怎么设置 编辑:程序博客网 时间:2024/05/18 02:00

之前在学css时就碰到过这些问题,现在来整理一下(本文所指盒子若无特殊说明,均为块级标签)

一:当两个盒子为父子关系时,子盒子设置margin-top时,会发生一件奇怪的事情

我们来看看是什么奇怪的事情,代码如下:

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>        <style type="text/css">            #box1{                width: 500px;                height: 500px;                background: #ccc;            }            #box2{                width: 300px;                height: 300px;                background: #333;                margin-top: 200px;            }        </style>    </head>    <body>        <div id="box1">            <div id="box2"></div>        </div>    </body></html>

按照所写代码,效果应该是里面的小盒子离顶部会有200个像素的距离,也就是小盒子的底边和大盒子的底边重叠,就像这样:这里写图片描述
但是呢,实际情况却是这样:这里写图片描述
那么,为什么会这样呢,其实我也不知道,浏览器这种东西就是有这样或那样的小玩意阻碍着我们,但就是这些东西,我们跨过了它们,我们才得以成长。

本宝宝总结几种解决方法如下:

1.给父级添加透明边框
将以上代码css部分改为:

<style type="text/css">            #box1{                width: 500px;                height: 500px;                background: #ccc;                border: 1px solid transparent;            }            #box2{                width: 300px;                height: 300px;                background: #333;                margin-top: 200px;            }        </style>

2.给父级盒子设置overflow:hidden;
将css部分代码改为:

<style type="text/css">            #box1{                width: 500px;                height: 500px;                background: #ccc;                overflow: hidden;            }            #box2{                width: 300px;                height: 300px;                background: #333;                margin-top: 200px;            }        </style>

3.给父级或者给子级设置display:inline-block;

<style type="text/css">            #box1{                width: 500px;                height: 500px;                background: #ccc;                display: inline-block;            }            #box2{                width: 300px;                height: 300px;                background: #333;                margin-top: 200px;                /*display: inline-block;*/            }        </style>

4.给父级或者子级盒子添加浮动

<style type="text/css">            #box1{                width: 500px;                height: 500px;                background: #ccc;                /*float: left;*/            }            #box2{                width: 300px;                height: 300px;                background: #333;                margin-top: 200px;                float: left;            }        </style>

二:当两个盒子为兄弟关系时,上面的盒子设置margin-bottom,同时下面的盒子设置margin-top时,会出现重叠现象

该重叠现象会比较margin-top和margin-bottom的值,取两者中较大的一个值,应用到样式中。在设置时注意下就好了。

阅读全文
0 0
原创粉丝点击