css布局时,div互相重叠是为什么

html-css06

css布局时,div互相重叠是为什么,第1张

在做css+div布局是重叠有很多中情况,我给你分析分析

首先看看一个容器套两个字容器的情况,在我们做布局的时候网页中div之间的关系基本都可以简化到这种关系。

代码如下

<!DOCTYPE html>

<html>

<head>

    <title>DIV_TEST</title>

    <meta charset="utf-8"/>

    <style type="text/css">

        div{border: 1px solid #000}

        #top1{

            width: 200px

        }

        #top1Sun1{

            background-color: aquamarine

            width: 150px

        }

        #top1Sun2{

            background-color: bisque

            width: 150px

        }

    </style>

</head>

<body>

    <div id="top1">

        top1

        <div id="top1Sun1">top1Sun1</div>

        <div id="top1Sun2">top1Sun2</div>

    </div>

</body>

</html>

下面我们来看一下那种方式可能会产生重叠

1、margin为负数的情况

现在我们将top1Suan2的margin-top设置成-10px

可以看到top1Sun2向上偏移了10个像素,因此这中情况是可能产生重叠的。

2、绝对定位

这个不用解释了,肯定可以产生重叠

3、父容器高度不固定,子容器使用float,看看父容器的兄弟容器会不会产生偏移

不使用float的时候是这样的

代码如下

<!DOCTYPE html>

<html>

<head>

    <title>DIV_TEST</title>

    <meta charset="utf-8"/>

    <style type="text/css">

        div{border: 1px solid #000}

        #top1{

            width: 600px

        }

        #top1Sun1{

            background-color: aquamarine

            width: 150px

            height: 200px

        }

        #top1Sun2{

            background-color: bisque

            width: 150px

            height: 200px

            margin-top: -10px

        }

        #top2{

            height: 100px

            background-color: #eee

        }

    </style>

</head>

<body>

    <div id="top1">

        top1

        <div id="top1Sun1">top1Sun1</div>

        <div id="top1Sun2">top1Sun2</div>

    </div>

    <div id="top2"></div>

</body>

</html>

现在让top1Sun1、top1Sun2的float都为left

你会发现,top2容器居然和top1发生了重叠

发生这种情况的原因是因为top1我们没有设置固定高度,当他的两个字容器向左浮动时,top1的高度就不会被他的子容器撑开了,这是我们可以选择两个方法给top1提供高度占位,一种是设置固定高度,还有一种是设置top1的overflow为hidden(这种方式会让父容器高度自适应字容器),现在我们把top1的overflow设置为hidden看下效果

布局达到了我们预想的效果(top1Sun2因为设置了margin-top:-10px所以会往上偏移10像素,多出的部分,因为父容器设置了溢出隐藏,所以看不到了)

css的hover就能实现(但不兼容IE6,因为IE6不支持a标签以为的hover,想兼容ie6需要用js)

首先需要用的position设置绝对或相对位置然后用z-index设置层叠高度(数越大越在最上面,可以为负数)

然后当hover时将其z-index的值改的很大就可以了

JS同理

这里指提供思路,具体怎么写可以好好研究研究有助于你的提高

纯手动望采纳

tags: [css]

categories: [css/Less]

该元素完全没有设定边框border、内边距paddng、高度height、最小高度min-height 、最大高度max-height时可能会发生。

以上情况的组合会产生复杂的外边距折叠(普通文档流中块框的垂直边界才会发生边界叠加),行内框、浮动框或绝对定位框之间的边界不会叠加。

参考: 外边距折叠|MDN