CSS如何控制 2个div 的 部分 重叠在一起 并将其中一个div的内容固定显示在上层

html-css010

CSS如何控制 2个div 的 部分 重叠在一起 并将其中一个div的内容固定显示在上层,第1张

重叠在一起需要改变默认的布局方式,将其中一个显示在上层需要设置深度顺序,这两点分别用如下样式完成

position: absolute /*设置为绝对定位*/

z-index:999        /*设置重叠的上下次序,值越大月在上方*/

示例如下

创建Html元素

<div class="top">

<div class="b">我是绝对定位,并且重叠在上方</div>

<div class="a">我是默认定位</div>

</div>

设置css样式

div.top{margin:50pxpadding:20pxwidth:200pxheight:200pxborder:2px dashed #ebbcbe}

div.top div{width:100pxheight:100pxpadding:10pxcolor:white}

div.a{background:red}

div.b{background:greenposition:absolutetop:100pxleft:100pxz-index:999}

观察显示效果

在做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}