CSS相对于Div角落的定位 [英] CSS Positioning relative to corner of Div

查看:138
本文介绍了CSS相对于Div角落的定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个更大的div中有几个div。是否可以将所有这些div相对于父div的左上角定位?这将使某些任务的定位更容易,因为所有内部div的坐标都将相对于同一参考点。目前使用位置:relative 只是偏离其位置而不受位置的影响:相对

I have several divs within a larger divs. Is it possible to position all these divs relative to the top left corner of the parent div? This will make positioning easier for certain tasks as all the inner divs' coordinates will be relative to the same reference point. At the moment using position: relative just offsets its position from where it would be at without being affected by position: relative.

推荐答案

将父/包含div设置为 position:relative 。然后,将子div设置为 postion:absolute 。然后孩子将被绝对定位,但是相对于包含div,而不是相对于整个页面。

Set the parent/containing div to position:relative. Then, set the child divs to postion:absolute. The children will then be positioned absolutely, but relative to the containing div, not relative to the overall page.

这是一个例子: http://jsfiddle.net/jfriend00/GgNsH/

HTML:

<div id"otherStuff" style="height: 100px; background-color: #777;"></div>
<div id="container">
    <div id="child1" class="child"></div>
    <div id="child2" class="child"></div>
    <div id="child3" class="child"></div>
</div>

CSS:

#container {position: relative;}
.child {position: absolute; height: 10px; width: 10px; background-color: #777;}
#child1 {top: 10px; left: 10px}
#child2 {top: 30px; left: 30px}
#child3 {top: 50px; left: 50px}

每个孩子将从左上角定位在它的顶部/左侧值容器。

Each child will be positioned at it's top/left value from the top/left corner of the container.

这是有效的,因为这是 position:absolute 的工作原理。它将元素相对于第一个定位的父元素(位置值 relative 绝对或<的父元素)定位code>已修复)或如果未定位父项,则使用文档的左上角作为参考。这不是一个技巧,但它是如何记录的,它非常有用。

It works because that's how position: absolute works. It positions the element relative to the first positioned parent (a parent that has a position value of relative, absolute or fixed) or if no parents are positioned, then it uses the top/left corner of the document as the reference. This is not a trick, but how it's documented to work and it's extremely useful.

这篇关于CSS相对于Div角落的定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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