如何CSS实现两个层重叠与显示?

html-css016

如何CSS实现两个层重叠与显示?,第1张

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>test</title>

<style type="text/css">

#father{

position:relative/*父盒子位置要用relative*/

margin:20px auto

width:400px

height:100px

border:1px solid red

}

#father #a{

position:absolute/*子盒子位置要用absolute*/

width:100%

height:50px

background:blue

opacity:0.6

z-index:2

}

#father #b{

position:absolute/*子盒子位置要用absolute*/

width:100%

height:80px

background:#F4AF19

text-align:right

z-index:1

}

</style>

</head>

<body>

<!--按上面的CSS定位方法布局就会重叠,那个子盒子在前面用Z-INDEX 决定-->

<div id="father">

<div id="a">我是A盒子</div>

    <div id="b">我是B盒子</div>

</div>

</body>

</html>

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

在two 和three 中间 插入一个<div class="clearboth"></div>

.clearboth { clear:bothdisplay:blockwidth:0height:0font-size:0overflow:hidden}

#three{width:xx}