如何获得具有相对位置的重叠div? [英] How can I get overlapping divs with relative positions?

查看:170
本文介绍了如何获得具有相对位置的重叠div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将几个div彼此排成一行,但也希望它们与上一个div重叠.

I want a few divs to be positioned in a line next to each other, but also allow them to overlap the previous div.

我要获取的是具有特定时间长度的事件的div的时间轴.这些事件可以相互重叠.

What I'm trying to get is a timeline with divs for events of certain length. The events can overlap each other.

我的想法是给每个div相同的顶部位置,z索引增加,左侧位置增加(根据事件发生的时间).稍后,我将通过鼠标悬停事件弹出各个div,以可视化重叠.

My idea was to give each div the same top position, an increasing z-index and an increasing left position (according to the time of the event). Later I would pop individual divs out by mouse-over events to visualise the overlap.

我要做的是使每个div置于下一个div下.摆弄top属性,可以使它们水平对齐,但看不到图案.

What I do is to make it so each div gets placed under the next one. With fiddling of the top attribute I can get them to align horizontally, but I don't see the pattern.

 <div class="day">
         <div style="top: 35px; left: 200px; background-color: red; height: 50px; width:24px; z-index: 1; position: relative;"> </div>
         <div style="top: 35px; left: 220px; background-color: green; height: 50px; width:24px; z-index: 2; position: relative;"> </div>
         <div style="top: 35px; left: 225px; background-color: blue; height: 50px; width:48px; z-index: 3; position: relative;"> </div>
 </div> 

如果我使用绝对位置,则元素会飞出周围的div,并且绝对位于页面中的某个位置.

If I use absolute positions, the elements fly out of the surrounding div and are positioned absolutely at some place in the page.

推荐答案

很简单.使用绝对定位进行内部div划分,但使用相对定位的div进行包装:

It's simple. Make an inner div using absolute positioning but wrapped with a div that uses relative positioning:

<div id="container" style="position: relative;width:200px;height:100px;top:100px;background:yellow">
    <div id="innerdiv1" style="z-index: 1; position:absolute; width: 100px;height:20px;background:red;">a</div>
    <div id="innerdiv2" style="z-index: 2; position:absolute; width: 100px;height:20px;background:blue;left:10px;top:10px;"></div>
</div>

您可以使用其他方法,例如负边距,但是如果要动态更改HTML,则不建议使用.例如,如果要移动内部div的位置,只需设置容器的top/left/right/bottom CSS属性或使用JavaScript(jQuery或其他方式)修改属性即可.

它将使您的代码保持干净和可读性.

You can use another method like negative margin, but it's not recommended if you want to dynamically change HTML. For example, if you want to move the position of the inner div(s), just set the top/left/right/bottom CSS properties of the container or modify the properties using JavaScript (jQuery or otherwise).

It will keep your code clean and readable.

这篇关于如何获得具有相对位置的重叠div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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