如何使用位置将 DIV 元素堆叠在一起:相对 [英] How do I stack DIV elements on top of each other with position: relative

查看:48
本文介绍了如何使用位置将 DIV 元素堆叠在一起:相对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在让 div 元素垂直堆叠时遇到问题.我有一个 mainwrapper 和 2 个 div 元素,我需要将它们堆叠起来.但是每当我给出第一个内部 div position: absolute 然后 right: 0 甚至 float: right,它进入第二个 div.有没有办法解决这个问题?

<div class="test1"></div><div class="test2"><div class="test3"></div>

CSS:

.wrapper {宽度:605px;边距:0 自动;位置:相对;背景:透明;边框:1px纯黑色;高度:240px;}.test1 {边框:1px纯黑色;宽度:200px;高度:30px;显示:块;位置:绝对;右:0;}.test2 {边框:1px纯红色;宽度:600px;高度:200px;显示:块;位置:绝对;}.test3 {边框:1px纯黑色;宽度:100px;高度:20px;位置:绝对;底部:20px;右:0;}

这是我的 jsfiddle.

解决方案

Would http://jsfiddle.net/uFf9D/工作?

我注释掉了 .wrapper 上的尺寸并添加了 overflow: hidden.然后将 .test1 和 .test2 改为 position: relative 和 float: right .

编辑:重新添加宽度,因为它需要居中.

.wrapper {宽度:605px;/*高度:240px;*/溢出:隐藏;...}.test1 {/*位置:相对;*/浮动:对;...}.test2 {位置:相对;浮动:对;...}

如果你想跳过浮点数和溢出:隐藏,方向:rtl 可能是 .wrapper 上的一个可能的解决方案.. 不知道它是否有效或是否被继承.

试试这个对 .test2 的添加来填充 .test1:

宽度:100%;box-sizing: 边框框;-moz-box-sizing: 边框框;

I'm having a problem getting div elements to stack on top of each other vertically. I have a mainwrapper and 2 div elements inside them that I need to be stacked. But whenever I give the first inner div position: absolute and then right: 0 or even float: right, it goes into the second div. Is there any way around this?

<div class="wrapper">

    <div class="test1"></div>

    <div class="test2">
        <div class="test3"></div>
    </div>

</div>

CSS:

.wrapper {
    width: 605px;
    margin: 0 auto;
    position: relative;
    background: transparent;
    border: 1px solid black;
    height: 240px;
}

.test1 {
    border: 1px solid black;
    width: 200px;
    height: 30px;
    display: block;
    position: absolute;
    right: 0;
}

.test2 {
    border: 1px solid red;
    width: 600px;
    height: 200px;
    display: block;
    position: absolute;
}

.test3 {
    border: 1px solid black;
    width: 100px;
    height: 20px;
    position: absolute;
    bottom: 20px;
    right: 0;
}

Here is my jsfiddle.

解决方案

Would http://jsfiddle.net/uFf9D/ work?

I commented out the dimensions on .wrapper and added overflow: hidden. Then changed .test1 and .test2 to position: relative and float: right.

Edit: Readded the width since it's needed for centering.

.wrapper {
  width: 605px;
/*
  height: 240px;
*/
  overflow: hidden;
  ...
}

.test1 {
/*
  position: relative;
*/
  float: right;
  ...
}

.test2 {
  position: relative;
  float: right;
  ...
}

If you want to skip the floats and overflow: hidden, direction: rtl might be a possible solution on .wrapper.. don't know if it works or whether it's inherited.

Try out this addition to .test2 to fill up .test1:

width: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box;

这篇关于如何使用位置将 DIV 元素堆叠在一起:相对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆