css样式 div两个盒子上下叠加如下图怎么写啊?

html-css011

css样式 div两个盒子上下叠加如下图怎么写啊?,第1张

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

<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多种方式实现,上述只是其中的一两种

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

1、打开vscode,创建一个html页面。

2、在测试页面的同级目录,添加一张演示图片。

3、在测试页面中添加一个div标签,在标签内部添加一个img图片标签,设置图片的src地址。

4、在div的标签中,直接书写css的样式,设置div的宽度为500像素,高度为300像素,边框为1像素的红色框。再次在浏览器中打开,就可以看到图片,并没有填满整个div的空间。

5、想要让图片充满整个div,只需要对图片设置高宽都是100%即可。此处为了演示,将所有的img标签都设置成了100%,而且,使用的是外部css的书写形式。

6、如果图片使用的是背景图,不是img标签的形式,图片默认会在x和y轴重复,并不会拉伸,最终仍然填满了这个div的空间。

7、如果想要背景图也拉伸填满整个div空间,就需要设置背景图的,background-size: 100% 100%。