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

html-css011

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像素,多出的部分,因为父容器设置了溢出隐藏,所以看不到了)

如果大盒子套小盒子,可以这样:

<div style="position:relativewidth:400pxheight:300pxbackground-color:yellow">

<div style="position:absolutebottom:0left:50pxwidth:300pxheight:150pxbackground-color:red"></div>

</div>

如果两个盒子是独立的,则可以这样:

<div style="width:400pxheight:300pxbackground-color:yellow"></div>

<div style="position:relativetop:-150pxleft:50pxwidth:300pxheight:150pxbackground-color:red">2</div>

其实有N多种方式实现,上述只是其中的一两种